Beispiel #1
0
        public void SingletonSessionsTests()
        {
            Binding binding = new WSHttpBinding();
            string address = "http://localhost/" + Guid.NewGuid().ToString();
            using (ServiceHost host =
                      new ServiceHost(typeof(SingletonCounter), new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(ISessionRequired), binding, "withSession");
                host.AddServiceEndpoint(typeof(ISessionNotAllowed), binding, "woutSession");

                host.Open();

                ISessionRequired withSession =
                    ChannelFactory<ISessionRequired>.CreateChannel(
                        binding,
                        new EndpointAddress(address + "/withSession"));
                withSession.IncrementCounter();
                ((ICommunicationObject)withSession).Close();

                ISessionNotAllowed woutSession =
                    ChannelFactory<ISessionNotAllowed>.CreateChannel(
                        binding,
                        new EndpointAddress(address + "/woutSession"));
                woutSession.IncrementCounter();
                ((ICommunicationObject)woutSession).Close();

            }
        }
		public static Binding CreateMexHttpBinding ()
		{
			var b = new WSHttpBinding (SecurityMode.None) {
				Name = "MetadataExchangeHttpBinding",
				Namespace = "http://schemas.microsoft.com/ws/2005/02/mex/bindings"};
			return b;
		}
Beispiel #3
0
        public void SingletonInitialization()
        {
            // Initialize Counter
            SingletonCounter myCounter = new SingletonCounter();
            myCounter.Counter = 5;

            string address = "http://localhost/" + Guid.NewGuid().ToString();
            Binding binding = new WSHttpBinding();
            using (ServiceHost host = new ServiceHost(myCounter))
            {
                // Host
                host.AddServiceEndpoint(typeof(ICounter), binding, address);
                host.Open();

                // Client
                ICounter counter = ChannelFactory<ICounter>.CreateChannel(binding, new EndpointAddress(address));
                counter.IncrementCounter();
                Assert.AreEqual(6, counter.GetCurrentValue());
                ((ICommunicationObject)counter).Close();
            }
        }
Beispiel #4
0
        private static Binding GetTargetBinding()
        {
            Binding result;

            switch (Program.GlobalConfig.WCFBinding)
            {
            case GlobalConfig.EWCFBinding.NetTcp:
                result = new NetTcpBinding {
                    MaxBufferPoolSize      = MaxMessageSize,
                    MaxBufferSize          = MaxMessageSize,
                    MaxReceivedMessageSize = MaxMessageSize,
                    ReaderQuotas           =
                    {
                        MaxArrayLength         = MaxMessageSize,
                        MaxStringContentLength = MaxMessageSize
                    },

                    // We use SecurityMode.None for Mono compatibility
                    // Yes, also on Windows, for Mono<->Windows communication
                    Security = { Mode = SecurityMode.None }
                };

                break;

            case GlobalConfig.EWCFBinding.BasicHttp:
                result = new BasicHttpBinding {
                    MaxBufferPoolSize      = MaxMessageSize,
                    MaxBufferSize          = MaxMessageSize,
                    MaxReceivedMessageSize = MaxMessageSize,
                    ReaderQuotas           =
                    {
                        MaxArrayLength         = MaxMessageSize,
                        MaxStringContentLength = MaxMessageSize
                    },

                    // We use SecurityMode.None for Mono compatibility
                    // Yes, also on Windows, for Mono<->Windows communication
                    Security = { Mode = BasicHttpSecurityMode.None }
                };

                break;

            case GlobalConfig.EWCFBinding.WSHttp:
                result = new WSHttpBinding {
                    MaxBufferPoolSize      = MaxMessageSize,
                    MaxReceivedMessageSize = MaxMessageSize,
                    ReaderQuotas           =
                    {
                        MaxArrayLength         = MaxMessageSize,
                        MaxStringContentLength = MaxMessageSize
                    },

                    // We use SecurityMode.None for Mono compatibility
                    // Yes, also on Windows, for Mono<->Windows communication
                    Security = { Mode = SecurityMode.None }
                };

                break;

            default:
                ASF.ArchiLogger.LogGenericWarning(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(Program.GlobalConfig.WCFBinding), Program.GlobalConfig.WCFBinding));
                goto case GlobalConfig.EWCFBinding.NetTcp;
            }

            result.SendTimeout = new TimeSpan(0, 0, Program.GlobalConfig.ConnectionTimeout);
            return(result);
        }
Beispiel #5
0
        public MyCustomApplicationContext()
        {
            // Initialize Tray Icon
            trayIcon = new NotifyIcon()
            {
                Icon    = Resources.StyxAPI,
                Visible = true,
                Text    = "Styx Sign Helper"
            };
            trayIcon.Click += new EventHandler(TrayIcon_Click);

            try
            {
                jsonAddress = new Uri(string.Format("{0}:{1}", localUrl, ConfigurationManager.AppSettings["port"]));
            }
            catch
            {
                jsonAddress = new Uri("http://localhost:64321");
            }
            try
            {
                soapAddress = new Uri(string.Format("{0}:{1}/soap", localUrl, ConfigurationManager.AppSettings["soapport"]));
            }
            catch
            {
                soapAddress = new Uri("http://localhost:64322/soap");
            }

            if (hostJson == null)
            {
                try
                {
                    hostJson = new WebServiceHost(typeof(SignService), jsonAddress);
                    hostJson.AddServiceEndpoint(typeof(ISignService), new WebHttpBinding(), "");
                    hostJson.Open();
                }
                catch (CommunicationException commProblem)
                {
                    Console.WriteLine("There was a communication problem. " + commProblem.Message);
                }
            }

            if (hostSoap == null)
            {
                try
                {
                    hostSoap = new ServiceHost(typeof(SoapService), soapAddress);
                    ServiceMetadataBehavior smb = hostJson.Description.Behaviors.Find <ServiceMetadataBehavior>();
                    if (smb == null)
                    {
                        smb = new ServiceMetadataBehavior
                        {
                            HttpGetEnabled = true
                        }
                    }
                    ;
                    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                    hostSoap.Description.Behaviors.Add(smb);
                    hostSoap.AddServiceEndpoint(
                        ServiceMetadataBehavior.MexContractName,
                        MetadataExchangeBindings.CreateMexHttpBinding(),
                        "mex"
                        );
                    var wsHttpBinding = new WSHttpBinding(SecurityMode.None);
                    hostSoap.AddServiceEndpoint(typeof(ISignService), new BasicHttpBinding(), "");
                    hostSoap.Open();
                }
                catch (CommunicationException commProblem)
                {
                    Console.WriteLine("There was a communication problem. " + commProblem.Message);
                }
            }

            //rkApp.SetValue("styxWebAPI", Application.ExecutablePath);
        }
Beispiel #6
0
    public void StartService(ExternalCommandData commandData)
    {
        if (IsActive)
        {
            return;
        }

        try
        {
            Uri baseAddress = new Uri("http://localhost:9000/ModelServiceHost");
            SHost = new ServiceHost(typeof(ModelService), baseAddress);

            WSHttpBinding binding = new WSHttpBinding();
            binding.OpenTimeout    = new TimeSpan(0, 10, 0);
            binding.CloseTimeout   = new TimeSpan(0, 10, 0);
            binding.SendTimeout    = new TimeSpan(0, 10, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 10, 0);

            SHost.AddServiceEndpoint(typeof(BIM_Service.IModelService), binding, "ModelService");

            // Check to see if the service host already has a ServiceMetadataBehavior
            ServiceMetadataBehavior smb = SHost.Description.Behaviors.Find <ServiceMetadataBehavior>();
            // If not, add one
            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
            }
            smb.HttpGetEnabled  = true;
            smb.HttpsGetEnabled = true;
            SHost.Description.Behaviors.Add(smb);

            SHost.AddServiceEndpoint(typeof(IMetadataExchange), binding, "ModelService/mex");

            NetTcpBinding netBinding = new NetTcpBinding();
            netBinding.OpenTimeout    = new TimeSpan(0, 10, 0);
            netBinding.CloseTimeout   = new TimeSpan(0, 10, 0);
            netBinding.SendTimeout    = new TimeSpan(0, 10, 0);
            netBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);

            SHost.AddServiceEndpoint(typeof(BIM_Service.IModelService), netBinding, "net.tcp://localhost:8700/ModelServiceHost/ModelService");

            ServiceDebugBehavior debug = SHost.Description.Behaviors.Find <ServiceDebugBehavior>();

            // if not found - add behavior with setting turned on
            if (debug == null)
            {
                SHost.Description.Behaviors.Add(
                    new ServiceDebugBehavior()
                {
                    IncludeExceptionDetailInFaults = true
                });
            }
            else
            {
                // make sure setting is turned ON
                if (!debug.IncludeExceptionDetailInFaults)
                {
                    debug.IncludeExceptionDetailInFaults = true;
                }
            }

            SHost.Open();

            IsActive = true;

            m_rvtApp = commandData.Application.Application;
            m_rvtDoc = commandData.Application.ActiveUIDocument.Document;

            TaskDialog.Show("Server Satus", "Running at \n" + baseAddress.AbsoluteUri);

            if (debugServiceData)
            {
                foreach (ServiceEndpoint s in SHost.Description.Endpoints)
                {
                    string operations = "";

                    foreach (OperationDescription op in s.Contract.Operations)
                    {
                        operations += "\t" + op.Name + "\n";
                    }

                    TaskDialog.Show("Endpoint", "EndPoint " + s.Name + ":\n" +
                                    "Adress: " + s.Address.Uri.AbsoluteUri + "\n" +
                                    "Binding Name: " + s.Binding.Name + "\n" +
                                    "Binding NameSpace: " + s.Binding.Namespace + "\n" +
                                    "Binding OpenTimeout: " + s.Binding.OpenTimeout + "\n" +
                                    "Contract Name: " + s.Contract.Name + "\n" +
                                    "Contract Operations:\n" + operations +
                                    "Contract Configuration Name: " + s.Contract.ConfigurationName + "\n" +
                                    "IsSystemEndpoint: " + s.IsSystemEndpoint + "\n" +
                                    "Listen Uri: " + s.ListenUri.AbsoluteUri + "\n" +
                                    "Listen Uri Mode: " + s.ListenUriMode);
                }
            }
        }
        catch (Exception e)
        {
            TaskDialog.Show("Ups...", e.Message);
            if (IsActive)
            {
                IsActive = false;
                SHost.Close();
            }
            return;
        }
    }
Beispiel #7
0
        public void WSHttpBindingTest()
        {
            var wsHttpBinding = new WSHttpBinding();

            wsHttpBinding.TransactionFlow
        }
Beispiel #8
0
        public static void Main(string [] args)
        {
            int    port = 0;
            string certfile = null;
            string certpass = null;
            bool   no_sc = false, no_nego = false;

            foreach (string arg in args)
            {
                if (arg == "--help")
                {
                    Usage();
                    return;
                }
                if (arg.StartsWith("--port:"))
                {
                    int.TryParse(arg.Substring(7), out port);
                    continue;
                }
                if (arg == "--no-sc")
                {
                    no_sc = true;
                    continue;
                }
                if (arg == "--no-nego")
                {
                    no_nego = true;
                    continue;
                }
                if (arg.StartsWith("--certfile:"))
                {
                    certfile = arg.Substring(11);
                    continue;
                }
                if (arg.StartsWith("--certpass:"******"unrecognized option: " + arg);
                return;
            }
            if (certfile == null || certpass == null)
            {
                Console.WriteLine("specify certificate information to identify this service.");
                return;
            }

            if (port <= 0)
            {
                port = 8080;
            }
            Uri listeningUri = new Uri("http://localhost:" + port);

            ServiceHost host = new ServiceHost(
                typeof(WSTrustSecurityTokenService), listeningUri);

            host.Description.Behaviors.Find <ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = true;
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

            smb.HttpGetEnabled = true;
            host.Description.Behaviors.Add(smb);

            WSHttpBinding binding = new WSHttpBinding();

            binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
            if (no_sc)
            {
                binding.Security.Message.EstablishSecurityContext = false;
            }
            if (no_nego)
            {
                binding.Security.Message.NegotiateServiceCredential = false;
            }
            ServiceCredentials credentials = new ServiceCredentials();

            credentials.ServiceCertificate.Certificate = new X509Certificate2(certfile, certpass);
            //credentials.IssuedTokenAuthentication.AllowUntrustedRsaIssuers = true;
            host.Description.Behaviors.Add(credentials);

            host.AddServiceEndpoint(
                typeof(IWSTrustSecurityTokenService),
                binding,
                listeningUri);

            host.Open();
            Console.WriteLine("Type [ENTER] to close ...");
            Console.ReadLine();
            host.Close();
        }
        static bool UsesCertificateClientCredentials(ServiceEndpoint endpoint)
        {
            bool usesCertificates = false;

            if (endpoint.Binding is NetTcpBinding)
            {
                NetTcpBinding binding = endpoint.Binding as NetTcpBinding;
                if (binding.Security.Mode == SecurityMode.Transport)
                {
                    usesCertificates = binding.Security.Transport.ClientCredentialType == TcpClientCredentialType.Certificate;
                }
                if (binding.Security.Mode == SecurityMode.Message || binding.Security.Mode == SecurityMode.TransportWithMessageCredential)
                {
                    usesCertificates = binding.Security.Message.ClientCredentialType == MessageCredentialType.Certificate;
                }
            }
            if (endpoint.Binding is NetMsmqBinding)
            {
                NetMsmqBinding binding = endpoint.Binding as NetMsmqBinding;
                if (binding.Security.Mode == NetMsmqSecurityMode.Transport || binding.Security.Mode == NetMsmqSecurityMode.Both)
                {
                    usesCertificates = binding.Security.Transport.MsmqAuthenticationMode == MsmqAuthenticationMode.Certificate;
                }
                if (binding.Security.Mode == NetMsmqSecurityMode.Message || binding.Security.Mode == NetMsmqSecurityMode.Both)
                {
                    usesCertificates = binding.Security.Message.ClientCredentialType == MessageCredentialType.Certificate;
                }
            }
            if (endpoint.Binding is WSHttpBinding)
            {
                WSHttpBinding binding = endpoint.Binding as WSHttpBinding;
                if (binding.Security.Mode == SecurityMode.Transport)
                {
                    usesCertificates = binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.Certificate;
                }
                if (binding.Security.Mode == SecurityMode.Message || binding.Security.Mode == SecurityMode.TransportWithMessageCredential)
                {
                    usesCertificates = binding.Security.Message.ClientCredentialType == MessageCredentialType.Certificate;
                }
            }
            if (endpoint.Binding is WSDualHttpBinding)
            {
                WSDualHttpBinding binding = endpoint.Binding as WSDualHttpBinding;
                if (binding.Security.Mode == WSDualHttpSecurityMode.Message)
                {
                    usesCertificates = binding.Security.Message.ClientCredentialType == MessageCredentialType.None;
                }
            }
            if (endpoint.Binding is BasicHttpBinding)
            {
                BasicHttpBinding binding = endpoint.Binding as BasicHttpBinding;
                switch (binding.Security.Mode)
                {
                case BasicHttpSecurityMode.Message:
                {
                    usesCertificates = binding.Security.Message.ClientCredentialType == BasicHttpMessageCredentialType.Certificate;
                    break;
                }

                case BasicHttpSecurityMode.TransportCredentialOnly:
                case BasicHttpSecurityMode.TransportWithMessageCredential:
                case BasicHttpSecurityMode.Transport:
                {
                    usesCertificates = binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.Certificate;
                    break;
                }
                }
            }
            if (endpoint.Binding is WebHttpBinding)
            {
                WebHttpBinding binding = endpoint.Binding as WebHttpBinding;
                if (binding.Security.Mode == WebHttpSecurityMode.Transport)
                {
                    usesCertificates = binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.Certificate;
                }
            }
            return(usesCertificates);
        }
Beispiel #10
0
        static IDictionary <string, string> GetSystem(ConfigSettings settings, StringDictionary parameters)
        {
            string remotePWD = null;
            string domain    = null;
            string remoteUID = UpdateSettings(settings, "remoteloginid", parameters["remoteuid"], true);

            if (remoteUID != null && remoteUID.Length > 0)
            {
                //--------------------------------------------------
                // If we have specified remote crendentials,
                // squirt them into the Settings
                //--------------------------------------------------
                remotePWD = UpdateSettings(settings, "remotepassword", parameters["remotepwd"], true);
                domain    = UpdateSettings(settings, "domain", parameters["domain"], true);
                UpdateSettings(settings, "UserRemoteCredential", "YES", true);
            }

            if (_system == null)
            {
                WSHttpBinding   binding          = new WSHttpBinding(SecurityMode.Message, false);
                EndpointAddress endpointAdddress = new EndpointAddress(
                    UpdateSettings(settings, "systemstoreendpointaddress", parameters["systemstoreendpointaddress"], true));
                ConfigurationSettingsProvider.DashBoardStore.DashBoardClient client = new Common.ConfigurationSettingsProvider.DashBoardStore.DashBoardClient(binding, endpointAdddress);

                string environment = UpdateSettings(settings, "environment", parameters["environment"], true);
                string database    = UpdateSettings(settings, "database", parameters["database"]);
                string datasource  = UpdateSettings(settings, "datasource", parameters["datasource"]);

                string uid = UpdateSettings(settings, "uid", "{default}");
                string pwd = UpdateSettings(settings, "password", "{default}");

                StringBuilder sb = new StringBuilder();
                sb.Append("    GetHRPlusSystemObject ");
                sb.AppendLine();
                sb.AppendFormat("      Environment : '{0}'", environment);
                sb.AppendLine();
                sb.AppendFormat("      Database : '{0}'", database);
                sb.AppendLine();
                sb.AppendFormat("      Datasource : '{0}'", datasource);
                sb.AppendLine();
                sb.AppendFormat("      UID : '{0}'", uid);
                sb.AppendLine();
                sb.AppendFormat("      PASSWORD : '******'", pwd);
                sb.AppendLine();
                Debug.WriteLine(sb.ToString());

                // If we have specified remote drendentails, squirt them into the Settings
                if (remoteUID != null && remoteUID.Length > 0)
                {
                    System.Net.NetworkCredential networkCredential =
                        new System.Net.NetworkCredential(remoteUID, remotePWD, domain);
                    client.ClientCredentials.Windows.ClientCredential = networkCredential;
                }
                _system = client.GetHRPlusSystemObject(environment, database, datasource, uid, pwd);
                if (_system == null)
                {
                    throw new NullReferenceException("GetHRPlusSystemObject returned a *null* reference.");
                }
            }

            return(_system);
        }
        /// <summary>
        /// Create a WCF "Binding" instance of the type described in the "endpoint"
        /// </summary>
        /// <param name="endpoint"></param>
        /// <returns>An initialized Binding suitable for use with a WCF ServiceHost</returns>
        public static Binding CreateBinding(WcfEndpoint endpoint)
        {
            /*
             * If you are using the CreateServiceHost method, which uses this CreateBinding method
             * then you MUST have a section in your application configuration file with the below
             * bindings.  If you alredy have a bindings section then verify that the below entries
             * are in your binding section.
             *
             * The IC supports three binding types "BasicHttpBindings", "WSHttpBinding" and "CustomBinding".
             * Within each binding type there are 1 or more named binding configurations.  Currently
             * the IC (excluding Telenor) uses "basicHttpBinding" with the name "nonCertBinding" for all
             * but one WCF interface.  The "customBinding" named "PlainXml" is handy for generic WCF
             * interface that does NOT expose a specific interface and will accpet pretty much anything sent.
             * Using "PlainXml" it is up to the service instance class to determine if the incoming data
             * is any good.
             *
             * Even though this method supports the binding type "WSHttpBinding" I haven't seen
             * any entries in any of the client projects that have a binding section of that type,
             * so I don't have a sample to put here.  If you are reading this because you are using
             * "WSHttpBinding" and tracked your problem down to this section, then you probably
             * need to create such a binding section now.   Please add a copy of your "WSHttpBinding"
             * section to this comment when you are done.
             *
             *
             *
             * note: If your application file has different values for some of the setting then it
             *       is likely that someone changed them for the specific client (with any luck they
             *       left a comment in the config file stating why the changed the value)
             *
             *   <bindings>
             *     <basicHttpBinding>
             *       <binding name="myBinding"
             *              hostNameComparisonMode="StrongWildcard"
             *              receiveTimeout="00:01:00"
             *              sendTimeout="00:01:00"
             *              openTimeout="00:01:00"
             *              closeTimeout="00:01:00"
             *              maxBufferSize="6535600"
             *              maxBufferPoolSize="524288"
             *              maxReceivedMessageSize="6535600"
             *              transferMode="Buffered"
             *              messageEncoding="Text"
             *              textEncoding="utf-8"
             *              bypassProxyOnLocal="false"
             *              useDefaultWebProxy="true">
             *         <!-- FORNOW - Uncomment once all developers have installed certs.
             *                   <security mode="Transport">
             *                       <transport clientCredentialType="Certificate" />
             *                   </security>
             *                   -->
             *       </binding>
             *       <binding name="nonCertBinding"
             *              hostNameComparisonMode="StrongWildcard"
             *              receiveTimeout="00:01:00"
             *              sendTimeout="00:01:00"
             *              openTimeout="00:01:00"
             *              closeTimeout="00:01:00"
             *              maxBufferSize="6535600"
             *              maxBufferPoolSize="524288"
             *              maxReceivedMessageSize="6535600"
             *              transferMode="Buffered"
             *              messageEncoding="Text"
             *              textEncoding="utf-8"
             *              bypassProxyOnLocal="false"
             *              useDefaultWebProxy="true">
             *         <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
             *       </binding>
             *     </basicHttpBinding>
             *     <customBinding>
             *         <binding name="PlainXml">
             *           <textMessageEncoding messageVersion="None" />
             *           <httpTransport />
             *         </binding>
             *     </customBinding>
             *   </bindings>
             *
             */

            // Instantiate the binding.
            Binding binding = null;

            if (endpoint.Binding.ToLower() == typeof(BasicHttpBinding).Name.ToLower())
            {
                if (!string.IsNullOrEmpty(endpoint.BindingConfiguration))
                {
                    binding = new BasicHttpBinding(endpoint.BindingConfiguration);
                }
                else
                {
                    binding = new BasicHttpBinding();
                }
            }
            else if (endpoint.Binding.ToLower() == typeof(WSHttpBinding).Name.ToLower())
            {
                if (!string.IsNullOrEmpty(endpoint.BindingConfiguration))
                {
                    binding = new WSHttpBinding(endpoint.BindingConfiguration);
                }
                else
                {
                    binding = new WSHttpBinding();
                }
            }
            else if (endpoint.Binding.ToLower() == typeof(CustomBinding).Name.ToLower())
            {
                if (!string.IsNullOrEmpty(endpoint.BindingConfiguration))
                {
                    binding = new CustomBinding(endpoint.BindingConfiguration);
                }
                else
                {
                    binding = new CustomBinding();
                }
            }
            else
            {
                throw new IntegrationException(string.Format("The binding, {0}, configured for {1} {2}, is not supported.\r\nThe supported bindings are {3}, {4} and {5}.\r\nPlease verify that the desired WCF Binding is present in your application config file.", endpoint.Binding, typeof(WcfEndpoint).Name, endpoint.Name, typeof(BasicHttpBinding).Name, typeof(WSHttpBinding).Name, typeof(CustomBinding).Name));
            }

            return(binding);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            TestGetConsumer();


            WSHttpBinding binding = new WSHttpBinding();

            binding.Name               = "DemographicService";
            binding.Security           = new WSHttpSecurity();
            binding.Security.Mode      = SecurityMode.TransportWithMessageCredential;
            binding.Security.Transport = new HttpTransportSecurity();
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;
            binding.Security.Message = new NonDualMessageSecurityOverHttp();

            //Set the ClientCredential property to use certificate authentication type
            binding.Security.Message.ClientCredentialType       = MessageCredentialType.Certificate;
            binding.Security.Message.NegotiateServiceCredential = false;
            binding.Security.Message.EstablishSecurityContext   = false;

            EndpointAddress endpoint = new EndpointAddress(new Uri("https://staginghixservice.lh1ondemand.com/v2_0/Demographic.svc"));

            WebConfiguration config = new WebConfiguration(endpoint, binding);

            DemographicServiceTestConsoleApp.ServiceRef.DemographicServiceClient client = new DemographicServiceTestConsoleApp.ServiceRef.DemographicServiceClient(binding, endpoint);

            client.Endpoint.EndpointBehaviors.Add(new Wex1CloudEndpointBehavior("TLS12"));

            //Both the client and the service are authenticated with certificates
            //Setting the X.509 certificate that the client uses to authenticate against the service
            client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "biztalk.nreca.org");

            //Specifiy the certificate to be used when authenticating a service to the client
            client.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "allsvc.lh1ondemand.com");


            DemographicServiceTestConsoleApp.ServiceRef.AddConsumerRequest addRequest = new DemographicServiceTestConsoleApp.ServiceRef.AddConsumerRequest();

            DemographicServiceTestConsoleApp.ServiceRef.ChangeConsumerRequest chgRequest = new DemographicServiceTestConsoleApp.ServiceRef.ChangeConsumerRequest();

            DemographicServiceTestConsoleApp.ServiceRef.ConsumerRequest getRequest = new DemographicServiceTestConsoleApp.ServiceRef.ConsumerRequest();

            getRequest.ConsumerKey = new DemographicServiceTestConsoleApp.ServiceRef.ConsumerKey();
            getRequest.ConsumerKey.ConsumerIdentifier = "001806804";
            getRequest.ConsumerKey.EmployerCode       = "16093";
            getRequest.ConsumerKey.AdministratorAlias = "NRC";

            getRequest.MessageId = "190207563";

            NRECA.DemographicService.ChangeConsumerRequest chgcanonicalRequest = new NRECA.DemographicService.ChangeConsumerRequest();
            chgcanonicalRequest.ConsumerDemographicInformation = new NRECA.DemographicService.Consumer();
            chgcanonicalRequest.ConsumerDemographicInformation.ClassEffectiveDate            = DateTime.Parse("2019-02-05");
            chgcanonicalRequest.ConsumerDemographicInformation.ClassName                     = "All";
            chgcanonicalRequest.ConsumerDemographicInformation.DateOfBirth                   = DateTime.Parse("1981-01-15");
            chgcanonicalRequest.ConsumerDemographicInformation.DateOfHire                    = DateTime.Parse("2019-02-05");
            chgcanonicalRequest.ConsumerDemographicInformation.Division                      = "unassigned";
            chgcanonicalRequest.ConsumerDemographicInformation.EmployeeNumber                = "001806804";
            chgcanonicalRequest.ConsumerDemographicInformation.EmployerEmployeeId            = "0018068040116093001";
            chgcanonicalRequest.ConsumerDemographicInformation.EmploymentStatus              = NRECA.DemographicService.EmploymentStatusValues.Active;
            chgcanonicalRequest.ConsumerDemographicInformation.EmploymentStatusEffectiveDate = DateTime.Parse("2019-02-05");
            chgcanonicalRequest.ConsumerDemographicInformation.FirstName                     = "Daniel";
            chgcanonicalRequest.ConsumerDemographicInformation.Gender           = NRECA.DemographicService.GenderTypeValues.Male;
            chgcanonicalRequest.ConsumerDemographicInformation.FirstName        = "Daniel";
            chgcanonicalRequest.ConsumerDemographicInformation.LastName         = "Adams";
            chgcanonicalRequest.ConsumerDemographicInformation.Password         = "******";
            chgcanonicalRequest.ConsumerDemographicInformation.PayrollFrequency = "Select a Payroll";
            chgcanonicalRequest.ConsumerDemographicInformation.PayrollFrequencyEffectiveDate = DateTime.Parse("2019-02-05");
            chgcanonicalRequest.ConsumerDemographicInformation.SocialSecurityNumber          = "479827553";
            chgcanonicalRequest.ConsumerDemographicInformation.UserName = "******";

            chgcanonicalRequest.ConsumerDemographicInformation.HomeAddress = new NRECA.DemographicService.Address();
            chgcanonicalRequest.ConsumerDemographicInformation.HomeAddress.AddressLine1 = "3032 Harrison Rd";
            chgcanonicalRequest.ConsumerDemographicInformation.HomeAddress.City         = "Ames";
            chgcanonicalRequest.ConsumerDemographicInformation.HomeAddress.State        = "IA";
            chgcanonicalRequest.ConsumerDemographicInformation.HomeAddress.ZipCode      = "50010";

            chgcanonicalRequest.ConsumerDemographicInformation.HomePhone                   = new NRECA.DemographicService.PhoneNumber();
            chgcanonicalRequest.ConsumerDemographicInformation.HomePhone.AreaCode          = "515";
            chgcanonicalRequest.ConsumerDemographicInformation.HomePhone.PhoneNumberMember = "988-3908";

            chgcanonicalRequest.ConsumerKey = new NRECA.DemographicService.ConsumerKey();
            chgcanonicalRequest.ConsumerKey.ConsumerIdentifier = "001806804";
            chgcanonicalRequest.ConsumerKey.EmployerCode       = "16093";
            chgcanonicalRequest.ConsumerKey.AdministratorAlias = "NRC";

            chgcanonicalRequest.MessageId = "190207563";

            //NRECA.DemographicService.AddConsumer addcanonicalRequest = new AddConsumer();
            //addcanonicalRequest.consumerRequest = new NRECA.DemographicService.AddConsumerRequest();
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation = new NRECA.DemographicService.Consumer();
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.ClassEffectiveDate = DateTime.Parse("2019-02-05");
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.ClassName = "All";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.DateOfBirth = DateTime.Parse("1981-01-15");
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.DateOfHire = DateTime.Parse("2019-02-05");
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.Division = "unassigned";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.EmployeeNumber = "001806804";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.EmployerEmployeeId = "0018068040116093001";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.EmploymentStatus = NRECA.DemographicService.EmploymentStatusValues.Active;
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.EmploymentStatusEffectiveDate = DateTime.Parse("2019-02-05");
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.FirstName = "Daniel";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.Gender = NRECA.DemographicService.GenderTypeValues.Male;
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.LastName = "Adams";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.Password = "******";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.PayrollFrequency = "Select a Payroll";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.PayrollFrequencyEffectiveDate = DateTime.Parse("2019-02-05");
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.SocialSecurityNumber = "479827553";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.UserName = "******";

            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomeAddress = new NRECA.DemographicService.Address();
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomeAddress.AddressLine1 = "3032 Harrison Rd";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomeAddress.City = "Ames";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomeAddress.State = "IA";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomeAddress.ZipCode = "50010";

            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomePhone = new NRECA.DemographicService.PhoneNumber();
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomePhone.AreaCode = "515";
            //addcanonicalRequest.consumerRequest.ConsumerDemographicInformation.HomePhone.PhoneNumberMember = "988-3908";

            //addcanonicalRequest.consumerRequest.ConsumerKey = new NRECA.DemographicService.ConsumerKey();
            //addcanonicalRequest.consumerRequest.ConsumerKey.ConsumerIdentifier = "001806804";
            //addcanonicalRequest.consumerRequest.ConsumerKey.EmployerCode = "16093";
            //addcanonicalRequest.consumerRequest.ConsumerKey.AdministratorAlias = "NRC";

            //addcanonicalRequest.consumerRequest.MessageId = "190207563";


            //Mapper.Initialize(cfg => {
            //cfg.CreateMap<NRECA.DemographicService.AddConsumerRequest, DemographicServiceTestConsoleApp.ServiceRef.AddConsumerRequest>().DisableCtorValidation();
            //cfg.CreateMap<NRECA.DemographicService.Consumer, DemographicServiceTestConsoleApp.ServiceRef.Consumer>().DisableCtorValidation();
            //cfg.CreateMap<NRECA.DemographicService.ConsumerKey, DemographicServiceTestConsoleApp.ServiceRef.ConsumerKey>().DisableCtorValidation();
            //);

            //var Output = Mapper.Map<DemographicServiceTestConsoleApp.ServiceRef.AddConsumerRequest>(addcanonicalRequest.consumerRequest);
            //var config1 = new MapperConfiguration(cfg => {
            //    cfg.CreateMap<NRECA.DemographicService.AddConsumerRequest, DemographicServiceTestConsoleApp.ServiceRef.AddConsumerRequest>().DisableCtorValidation().ForMember(destination => destination.ConsumerDemographicInformation, opts => opts.MapFrom(source => source.ConsumerDemographicInformation));
            //    cfg.CreateMap< NRECA.DemographicService.Consumer, DemographicServiceTestConsoleApp.ServiceRef.Consumer>().DisableCtorValidation();
            //    cfg.CreateMap<NRECA.DemographicService.ConsumerKey, DemographicServiceTestConsoleApp.ServiceRef.ConsumerKey>().DisableCtorValidation();
            //});


            var config1 = new MapperConfiguration(cfg => {
                cfg.CreateMap
                <NRECA.DemographicService.Address, DemographicServiceTestConsoleApp.ServiceRef.Address>()
                .ForMember(destination => destination.ExtensionData, opts => opts.Ignore());
            });


            var config2 = new MapperConfiguration(cfg => {
                cfg.CreateMap
                <NRECA.DemographicService.Consumer, DemographicServiceTestConsoleApp.ServiceRef.Consumer>()
                .ForMember(destination => destination.ExtensionData, opts => opts.Ignore())
                .ForMember(destination => destination.HomeAddress, opts => opts.Ignore())
                .ForMember(destination => destination.HomePhone, opts => opts.Ignore())
                ;
            });

            var config3 = new MapperConfiguration(cfg => {
                cfg.CreateMap
                <NRECA.DemographicService.ConsumerKey, DemographicServiceTestConsoleApp.ServiceRef.ConsumerKey>()
                .ForMember(destination => destination.ExtensionData, opts => opts.Ignore())
                ;
            });

            var config4 = new MapperConfiguration(cfg => {
                cfg.CreateMap
                <NRECA.DemographicService.PhoneNumber, DemographicServiceTestConsoleApp.ServiceRef.PhoneNumber>()
                .ForMember(destination => destination.ExtensionData, opts => opts.Ignore());
            });

            config1.AssertConfigurationIsValid();
            config2.AssertConfigurationIsValid();
            config3.AssertConfigurationIsValid();
            config4.AssertConfigurationIsValid();

            var mapper1 = config1.CreateMapper();
            var mapper2 = config2.CreateMapper();
            var mapper3 = config3.CreateMapper();
            var mapper4 = config4.CreateMapper();


            DemographicServiceTestConsoleApp.ServiceRef.Address caddr = mapper1.Map <DemographicServiceTestConsoleApp.ServiceRef.Address>(chgcanonicalRequest.ConsumerDemographicInformation.HomeAddress);

            DemographicServiceTestConsoleApp.ServiceRef.Consumer consumer = mapper2.Map <DemographicServiceTestConsoleApp.ServiceRef.Consumer>(chgcanonicalRequest.ConsumerDemographicInformation);

            DemographicServiceTestConsoleApp.ServiceRef.ConsumerKey ckey = mapper3.Map <DemographicServiceTestConsoleApp.ServiceRef.ConsumerKey>(chgcanonicalRequest.ConsumerKey);

            DemographicServiceTestConsoleApp.ServiceRef.PhoneNumber cph = mapper4.Map <DemographicServiceTestConsoleApp.ServiceRef.PhoneNumber>(chgcanonicalRequest.ConsumerDemographicInformation.HomePhone);

            chgRequest.ConsumerDemographicInformation             = consumer;
            chgRequest.ConsumerDemographicInformation.HomeAddress = caddr;
            chgRequest.ConsumerDemographicInformation.HomePhone   = cph;
            chgRequest.ConsumerKey = ckey;

            DemographicServiceTestConsoleApp.ServiceRef.GetConsumerResponse getresp = client.GetConsumer(getRequest);


            NRECA.DemographicService.GetConsumerResponse1 resp1 = new GetConsumerResponse1();
            resp1.GetConsumerResult = new NRECA.DemographicService.GetConsumerResponse();

            resp1.GetConsumerResult.ConsumerInformation = new NRECA.DemographicService.Consumer();

            resp1.GetConsumerResult.OperationResult = new NRECA.DemographicService.OperationResult();
            resp1.GetConsumerResult.OperationResult.ExecutionMessages                     = new NRECA.DemographicService.ExecutionMessage[getresp.OperationResult.ExecutionMessages.Length];
            resp1.GetConsumerResult.OperationResult.ExecutionMessages[0]                  = new NRECA.DemographicService.ExecutionMessage();
            resp1.GetConsumerResult.OperationResult.ExecutionMessages[0].Code             = getresp.OperationResult.ExecutionMessages[0].Code;
            resp1.GetConsumerResult.OperationResult.ExecutionMessages[0].Description      = getresp.OperationResult.ExecutionMessages[0].Description;
            resp1.GetConsumerResult.OperationResult.ExecutionMessages[0].NotificationType = (NRECA.DemographicService.ExecutionNotificationValues)getresp.OperationResult.ExecutionMessages[0].NotificationType;
            resp1.GetConsumerResult.MessageId = getresp.MessageId;
            resp1.GetConsumerResult.OperationResult.OperationSucceeded = getresp.OperationResult.OperationSucceeded;



            var config5 = new MapperConfiguration(cfg => {
                cfg.CreateMap
                <DemographicServiceTestConsoleApp.ServiceRef.Consumer, NRECA.DemographicService.Consumer>()
                .ForMember(destination => destination.HomeAddress, opts => opts.Ignore())
                .ForMember(destination => destination.HomePhone, opts => opts.Ignore())
                ;
            });

            var config6 = new MapperConfiguration(cfg => {
                cfg.CreateMap
                <NRECA.DemographicService.Address, DemographicServiceTestConsoleApp.ServiceRef.Address>()
                .ForMember(destination => destination.ExtensionData, opts => opts.Ignore());
            });

            var config7 = new MapperConfiguration(cfg => {
                cfg.CreateMap
                <NRECA.DemographicService.PhoneNumber, DemographicServiceTestConsoleApp.ServiceRef.PhoneNumber>()
                .ForMember(destination => destination.ExtensionData, opts => opts.Ignore());
            });

            config5.AssertConfigurationIsValid();
            config6.AssertConfigurationIsValid();
            config7.AssertConfigurationIsValid();

            var mapper5 = config5.CreateMapper();
            var mapper6 = config6.CreateMapper();
            var mapper7 = config7.CreateMapper();

            NRECA.DemographicService.Consumer    csr   = mapper6.Map <NRECA.DemographicService.Consumer>(getresp.ConsumerInformation);
            NRECA.DemographicService.Address     gaddr = mapper1.Map <NRECA.DemographicService.Address>(getresp.ConsumerInformation.HomeAddress);
            NRECA.DemographicService.PhoneNumber gph   = mapper4.Map <NRECA.DemographicService.PhoneNumber>(getresp.ConsumerInformation.HomePhone);


            resp1.GetConsumerResult.ConsumerInformation             = csr;
            resp1.GetConsumerResult.ConsumerInformation.HomePhone   = gph;
            resp1.GetConsumerResult.ConsumerInformation.HomeAddress = gaddr;
            //resp1.AddConsumerResult.OperationResult = cresp6;

            //Console.WriteLine(resp.OperationResult.ExecutionMessages[0].Description);
            Console.ReadKey();
        }
Beispiel #13
0
        public static void startCAFImportImpl(ICswResources CswResources, string CAFDatabase, string CAFSchema, string CAFPassword, CswEnumSetupMode SetupMode)
        {
            CswNbtResources _CswNbtResources = (CswNbtResources)CswResources;

            //connect to the CAF database
            CswDbVendorOpsOracle CAFConnection = new CswDbVendorOpsOracle("CAFImport", CAFDatabase, CAFSchema, CAFPassword, (CswDataDictionary)_CswNbtResources.DataDictionary, _CswNbtResources.CswLogger, CswEnumPooledConnectionState.Open, "");

            string Error = "";

            if (false == CAFConnection.IsDbConnectionHealthy(ref Error))
            {
                throw new CswDniException(CswEnumErrorType.Error, "Check the supplied parameters for the CAF database.", Error);
            }

            //Run the SQL to generate the table, views, triggers, and other setup operations.
            //there is no clean solution for running the contents of .SQL file from inside C#, so please forgive the horrible hacks that follow.
            //Assumptions made here:
            //   the only PL/SQL blocks are the deletes at the top of the script and the triggers at the bottom,
            //   the / at the end of PL/SQL is always at the beginning of a line,
            //   triggers always have two lines of spaces before them, except the very first trigger, which has 3

            string CAFSql = generateCAFSql(_CswNbtResources);

            //add a / before the first trigger and split the file into an array of strings on space-only preceded / chars (breaking off potential PL/SQL blocks)
            string[] SQLCommands = Regex.Split(CAFSql
                                               .Replace(");\r\n\r\n\r\ncreate or replace trigger", ");\r\n\r\n\r\n/\r\ncreate or replace trigger")
                                               .Replace("create or replace procedure", "\r\n/\r\ncreate or replace procedure")
                                               .Replace("/*+", "*+"),//Strip slash out of Oracle Hints to prevent splitting the view query
                                               @"\s+/");

            foreach (string Command in SQLCommands)
            {
                //If we stripped a slash out of an Oracle Hint, put it back in
                string SQLCommand = Command.Replace("*+", "/*+");
                //if the string starts with any of these, it's a PL/SQL block and can be sent as-is
                if (SQLCommand.Trim().StartsWith("begin") || SQLCommand.Trim().StartsWith("create or replace trigger") || SQLCommand.Trim().StartsWith("create or replace procedure"))
                {
                    CAFConnection.execArbitraryPlatformNeutralSql(SQLCommand);
                }
                //otherwise, we need to further split out each command on ; chars
                else
                {
                    foreach (string SingleCommand in SQLCommand.Split(';'))
                    {
                        if (SingleCommand.Trim() != String.Empty)
                        {
                            CAFConnection.execArbitraryPlatformNeutralSql(SingleCommand.Trim());
                        }
                    }
                }
            }//foreach PL/SQL block in CAF.sql


            //create the database link, after cleaning up an old one if it exists
            _CswNbtResources.execArbitraryPlatformNeutralSql(@"
              begin
                execute immediate 'drop database link caflink';
                exception when others then null;
              end;
            ");

            _CswNbtResources.execArbitraryPlatformNeutralSql("create database link caflink connect to " + CAFSchema + " identified by " + CAFPassword + " using '" + CAFDatabase + "'");



            //Create custom NodeTypeProps from CAF Properties collections and set up bindings for them
            CreateAllCAFProps(_CswNbtResources, SetupMode);

            // Enable the CAFImport rule
            CswTableUpdate TableUpdate = _CswNbtResources.makeCswTableUpdate("enableCafImportRule", "scheduledrules");
            DataTable      DataTable   = TableUpdate.getTable("where rulename = '" + CswEnumNbtScheduleRuleNames.CAFImport + "'");

            if (DataTable.Rows.Count > 0)
            {
                DataTable.Rows[0]["disabled"] = CswConvert.ToDbVal(false);
                TableUpdate.update(DataTable);
            }


            //create a connection to the schedule service
            WSHttpBinding   Binding  = new WSHttpBinding();
            EndpointAddress Endpoint = new EndpointAddress(CswResources.SetupVbls["SchedServiceUri"]);
            CswSchedSvcAdminEndPointClient SchedSvcRef = new CswSchedSvcAdminEndPointClient(Binding, Endpoint);


            //fetch the CAFImport rule from ScheduleService
            CswSchedSvcParams CswSchedSvcParams = new CswSchedSvcParams();

            CswSchedSvcParams.CustomerId = _CswNbtResources.AccessId;
            CswSchedSvcParams.RuleName   = CswEnumNbtScheduleRuleNames.CAFImport;
            CswSchedSvcReturn CAFRuleResponse;

            try
            {
                CAFRuleResponse = SchedSvcRef.getRules(CswSchedSvcParams);
            }
            catch (Exception e)
            {
                throw new CswDniException(CswEnumErrorType.Error, "Could not connect to schedule service", e.Message);
            }


            //take the rule that was returned from the last request, set disabled to false, then send it back as an update
            CswScheduleLogicDetail CAFImport = CAFRuleResponse.Data[0];

            CAFImport.Disabled             = false;
            CswSchedSvcParams.LogicDetails = new Collection <CswScheduleLogicDetail>();
            CswSchedSvcParams.LogicDetails.Add(CAFImport);

            CswSchedSvcReturn svcReturn = SchedSvcRef.updateScheduledRules(CswSchedSvcParams);

            if (false == svcReturn.Status.Success)
            {
                throw new CswDniException(svcReturn.Status.Errors[0].Message);
            }
        }//startCAFImport
Beispiel #14
0
        static void Main(string[] args)
        {
            //URI 统一资源标识
            //唯一地标识一个网络资源的同时也表示资源所处的位置及访问的方式。URI具有如下的结构:
            //传输协议://主机名:端口号/资源路径
            //典型传输协议:
            //Http Https
            //Net.Tcp  net.tcp://localhost:808/service
            //Net.Pipe  net.pipe://localhost/service
            //Net Msmq net.msmq://lhl.com/service

            //EndPointAddress
            //public class ServiceEndpoint
            //{
            //    public EndpointAddress Address { get; set; }
            //    public Binding Binding { get; set; }
            //    public ContractDescription Contract { get; set; }
            //}

            //public class EndpointAddress
            //{
            //    public Uri Uri { get; }
            //    public AddressHeaderCollection Headers { get; }
            //    public EndpointIdentity Identity { get; }
            //}
            //EndPointAddress的属性Uri既作为服务的为标识,也作为服务的地址。这个地址可是服务的物理地址,也可以是逻辑地址。
            //Headers是一个AddressHeader的集合,存放一些寻址信息。
            //Identity属性标识服务的身份,被客户端用于认证服务。

            ////ServiceHostBase
            //public abstract class ServiceHostBase {
            //    public virtual void AddServiceEndpoint(ServiceEndpoint endpoint);
            //    public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address);
            //    public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address);
            //    public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address, Uri listenUri);
            //    public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address, Uri listenUri);
            //}
            //listenUri表示服务的监听地址

            //基地址和相对地址
            //除了以绝对路径的方式指定某个服务的终结点外,还可以通过基地址+相对地址的方式对其进行设置。

            //ServiceHost
            //public ServiceHost(object singletonInstance, params Uri[] baseAddresses);
            //public ServiceHost(Type serviceType, params Uri[] baseAddresses);
            //在指定了基地址后,具体添加终结点的时候,只需要指定基于基地址的相对地址即可。
            Uri[] baseAddr = new Uri[2];
            baseAddr[0] = new Uri("http://127.0.0.1/myservices");
            baseAddr[1] = new Uri("net.tcp://127.0.0.1/myservices");
            using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddr)){
                serviceHost.AddServiceEndpoint(typeof(ICalculator), new BasicHttpBinding(), "calculatorservice");
                serviceHost.AddServiceEndpoint(typeof(ICalculator), new NetTcpBinding(), "calculatorservice");
                serviceHost.Open();
            }

            //得到两个地址,分别为  http://127.0.0.1/myservices/calculatorservice
            //net.tcp://127.0.0.1/myservices/calculatorservice
            //一个传输协议只能指定一个基地址,指定过个会报错。
            //基地址和相对地址可以通过配置的方式进行设置,

            //地址跨终结点共享
            //一个服务实现两个不同的契约接口,在为这两个契约发布地址时,这两个具有相同地址的终结点实际上共享同一个绑定对象。
            using (ServiceHost serivceHost = new ServiceHost(typeof(InstrumentationService)))
            {
                WSHttpBinding binding = new WSHttpBinding();
                serivceHost.AddServiceEndpoint(typeof(IEventLogWriter), binding, "http://localhost:3721/instrumentationService");
                serivceHost.AddServiceEndpoint(typeof(IPerformanceCounterWriter), binding, "http://localhost:3721/instrumentationService");

                serivceHost.Open();
            }
            //客户端终结点地址
            //ClientBase<TChannel>
            //public abstract class ClientBase<TChannel> {
            //    protected ClientBase();
            //    protected ClientBase(InstanceContext callbackInstance);
            //    protected ClientBase(ServiceEndpoint endpoint);
            //    protected ClientBase(string endpointConfigurationName);
            //    protected ClientBase(Binding binding, EndpointAddress remoteAddress);
            //    protected ClientBase(string endpointConfigurationName, EndpointAddress remoteAddress);
            //    protected TChannel Channel { get; }
            //    public ChannelFactory<TChannel> ChannelFactory { get; }
            //    public void Close();
            //    public void Dispose();
            //}
            //定义在CalculatorClient中的Add是通过从基类继承的Channel属性的同名方法实现的。
            //该属性是通过属性 ChannelFactory 返回的ChannelFactory<TChannel>对象创建的。

            //地址报头  AddressHeaderCollection
            //WCF建立在消息交换机制上,支持多种消息。消息格式可以使XML,也可是非XML,比如JSON
            //使用最多的XML消息是SOAP,一个完整的SOAP由消息主体和一组消息报头组成。主体一般是对业务数据的封装,
            //而报头用于保存一些控制信息。
            //对客户端来说,终结点地址上的AddressHeader最终会被添加到请求消息的报头集合中。
            //对服务端来说,会提取出相应的报头信息和本地终结点的地址报头进行比较以选择出于请求匹配的终结点。

            //创建AddressHeader
            //public abstract class AddressHeader{

            //    public static AddressHeader CreateAddressHeader(object value);
            //    public static AddressHeader CreateAddressHeader(object value, System.Runtime.Serialization.XmlObjectSerializer serializer);
            //    public static AddressHeader CreateAddressHeader(string name, string ns, object value);
            //    public static AddressHeader CreateAddressHeader(string name, string ns, object value, System.Runtime.Serialization.XmlObjectSerializer serializer);
            //}
            //AddressHeader将指定的对象序列化后存放在地址报头中。默认序列化器为DataContractSerializer。
            //AddressHeader最终需要转换为SOAP消息的报头,而SOAP报头具有自己的名称和命名空间。
            //消息报头通过MessageHeader表示。
            //通过AddHeadersTo(Message message)将AddressHeaderCollection添加到一个代表消息的Message对象的报头。

            //终结点地址报头指定
            //using (ServiceHost serivceHost = new ServiceHost(typeof(InstrumentationService)))
            //{
            //    Uri uri = new Uri("http://localhost:3721/instrumentationService");
            //    AddressHeader header = AddressHeader.CreateAddressHeader("Licensed User", "LHL", "UserType");
            //    EndpointAddress address = new EndpointAddress(uri, header);
            //    Binding binding = new WSHttpBinding();
            //    ContractDescription contract = ContractDescription.GetContract(typeof(IEventLogWriter));
            //    ServiceEndpoint endpoint = new ServiceEndpoint(contract, binding, address);
            //    serivceHost.AddServiceEndpoint(endpoint);
            //    serivceHost.Open();
            //}
            //通过配置方式指定报头
            //  <system.serviceModel>
            //  <services>
            //    <service name="Service.InstrumentationService" >
            //      <endpoint address="http://localhost:3721/instrumentationService" binding="wsHttpBinding" contract="Service.IEventLogWriter">
            //        <headers>
            //          <UserType xmlns="lhl" > Licensed User </UserType> //AddressHeader序列化后的内容
            //        </headers>
            //      </endpoint>
            //      <endpoint address="http://localhost:3721/instrumentationService" binding="wsHttpBinding" contract="Service.IPerformanceCounterWriter"></endpoint>
            //    </service>
            //  </services>
            //</system.serviceModel>

            // 1.SOAP具有一个<TO>报头表示调用服务的地址,被选择的终结点地址必须具有相匹配的Uri。
            // 2.如果终结点地址具有相应的地址报头,则要求请求消息也具有相应的报头。
            // 两者同时满足,终结点才会被选择用于处理消息。
            // 直接手工方式在Message上添加相应报头,OperationContext,具有IncomingMessageHeaders和OutgoingMessageHeaders
            // 分别表示入栈消息和出栈消息,对应客户端来说,对应回复消息和请求消息,对于服务端正好相反。

            //AddressFilterMode  Prefix Exact Any  精确匹配  基于前缀  任意匹配

            //端口共享

            //逻辑地址和物理地址
            //EndpointAddress对象的Uri属性仅仅代表服务的逻辑地址,而物理地址对于服务端来说是监听地址,
            //对于客户端来说是消息真正发送的目标地址。默认是统一的,在网络环境限制时,逻辑地址和物理地址实现分离。

            //物理地址接受消息 逻辑地址发送消息 ?
            //客户端监听端口8888,终结点端口9999,那么客户端会将消息发往8888端口,而请求的消息报头<To/>地址中端口为9999
            //逻辑地址和物理地址的分离反映在客户端就意味着请求消息的<To>报头的地址(逻辑地址)和消息真正发送的地址(物理地址)可以不一致。
            //而对于服务端来说,意味着服务的监听地址(物理地址)和接受到的消息的<To>报头的地址(逻辑地址)可以不一样。
            //对于服务端来说,物理地址是真正用来请求监听的地址

            //监听地址和监听模式

            //信道分发器 ChannelDispacher  信道监听器 ChannelListener 终结点分发器 EndpointDispacher

            //消息筛选器 MessageFilter
            //ActionMessageFilter
            //EndpointAddressMessageFilter
            //XPathMessageFilter
            //PrefixEndpointAddressMessageFilter
            //MatchAllMessageFilter
            //MatchNoneMessageFilter
            //EndpointDispatcher
            //ServiceHost生成信道分发器,每个信道分发器有自己的信道监听器,
            //每个信道分发器会生成并拥有自己的终结点分发器。
            //当信道监听器监听到有请求进来,会根据消息自身携带的信息与之相匹配的终结点分发器。
            //根据消息进行终结点分发器的选择称为消息筛选。
        }
Beispiel #15
0
        public string WindowsFormConnect(Variables windowsForm)
        {
            WSHttpBinding binding = new WSHttpBinding();

            binding.OpenTimeout    = new TimeSpan(2, 0, 0);
            binding.CloseTimeout   = new TimeSpan(2, 0, 0);
            binding.SendTimeout    = new TimeSpan(2, 0, 0);
            binding.ReceiveTimeout = new TimeSpan(2, 0, 0);



            string runWcf = DateTime.Now.ToString("HH.mm.ss.ffffff");

            //method encrypt
            try
            {
                #region information with number method
                //windwos form and WCF
                //0 Clear group
                //1 MD5
                //2 RSA
                //3 AES
                //4 DES
                //5 Triple DES
                //6 RC4


                // algorithm in database MS SQL
                //0 Clear group
                //1 MD4
                //2 MD5
                //3 SHA
                //4 SHA1
                //5 SHA2_256
                //6 SHA2_512


                #endregion

                EncryptDecrypt method             = new EncryptDecrypt();
                string         nameMethodWcf      = "";
                string         nameMethodWinForms = "";
                string         nameMethodMsSQL    = "";
                string         codeHashCommand    = "";
                string         sizeInput          = "";
                byte[]         EncryptByte;

                switch (windowsForm.Size)
                {
                case 0:
                    sizeInput = "String 20 char";
                    break;

                case 1:
                    sizeInput = "Picture.jpg";
                    break;

                case 2:
                    sizeInput = "File.txt";
                    break;
                }

                switch (windowsForm.Option)
                {
                case -1:
                    option = "normal - single shot";
                    break;

                case 0:
                    option = "All Encrypt - Decrypt (PROG)";
                    break;

                case 1:
                    option = "All Encrypt (DATA)";
                    break;

                case 2:
                    option = "All Encrypt (PROG)";
                    break;
                }



                delay  = windowsForm.Delay.ToString();
                repeat = windowsForm.Repeat.ToString();



                if (windowsForm.Option == 1)
                {
                    delay = "not available in ALL method SQL";
                    for (int i = 0; i < windowsForm.Repeat; i++)
                    {
                        nameMethodMsSQL = "Clear group";
                        codeHashCommand = "'" + windowsForm.Encrypt + "'";
                        string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                        string requestInstertInTable =
                            @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";
                        ConMsSQL conMsSQL = new ConMsSQL();

                        conMsSQL.sqlcommand(requestInstertInTable);
                    }
                    for (int i = 0; i < windowsForm.Repeat; i++)
                    {
                        nameMethodMsSQL = "MD4";
                        codeHashCommand = "HASHBYTES('MD4', '" + windowsForm.Encrypt + "')";
                        string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                        string requestInstertInTable =
                            @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";
                        ConMsSQL conMsSQL = new ConMsSQL();

                        conMsSQL.sqlcommand(requestInstertInTable);
                    }
                    for (int i = 0; i < windowsForm.Repeat; i++)
                    {
                        nameMethodMsSQL = "MD5";
                        codeHashCommand = "HASHBYTES('MD5', '" + windowsForm.Encrypt + "')";
                        string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                        string requestInstertInTable =
                            @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";
                        ConMsSQL conMsSQL = new ConMsSQL();

                        conMsSQL.sqlcommand(requestInstertInTable);
                    }
                    for (int i = 0; i < windowsForm.Repeat; i++)
                    {
                        nameMethodMsSQL = "SHA";
                        codeHashCommand = "HASHBYTES('SHA', '" + windowsForm.Encrypt + "')";
                        string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                        string requestInstertInTable =
                            @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";
                        ConMsSQL conMsSQL = new ConMsSQL();

                        conMsSQL.sqlcommand(requestInstertInTable);
                    }
                    for (int i = 0; i < windowsForm.Repeat; i++)
                    {
                        nameMethodMsSQL = "SHA1";
                        codeHashCommand = "HASHBYTES('SHA1', '" + windowsForm.Encrypt + "')";
                        string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                        string requestInstertInTable =
                            @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";
                        ConMsSQL conMsSQL = new ConMsSQL();

                        conMsSQL.sqlcommand(requestInstertInTable);
                    }
                    for (int i = 0; i < windowsForm.Repeat; i++)
                    {
                        nameMethodMsSQL = "SHA2_256";
                        codeHashCommand = "HASHBYTES('SHA2_256', '" + windowsForm.Encrypt + "')";
                        string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                        string requestInstertInTable =
                            @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";
                        ConMsSQL conMsSQL = new ConMsSQL();

                        conMsSQL.sqlcommand(requestInstertInTable);
                    }
                    for (int i = 0; i < windowsForm.Repeat; i++)
                    {
                        nameMethodMsSQL = "SHA2_512";
                        codeHashCommand = "HASHBYTES('SHA2_512', '" + windowsForm.Encrypt + "')";
                        string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                        string requestInstertInTable =
                            @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";

                        ConMsSQL conMsSQL = new ConMsSQL();
                        conMsSQL.sqlcommand(requestInstertInTable);
                    }
                }
                if (windowsForm.Option == -1 || windowsForm.Option == 0 || windowsForm.Option == 2)
                {
                    switch (windowsForm.NumberMethodWinForms)
                    {
                    case 0:
                        nameMethodWinForms = "Clear group";
                        break;

                    case 1:
                        nameMethodWinForms = "MD5";
                        break;

                    case 2:
                        nameMethodWinForms = "RSA";
                        byte[] encryptByte = method.RsaDectryptByte(windowsForm.EncryptByte);
                        windowsForm.Encrypt = Encoding.UTF8.GetString(encryptByte);
                        break;

                    case 3:
                        nameMethodWinForms  = "AES";
                        windowsForm.Encrypt = method.AesDecryptString(windowsForm.EncryptByte);
                        break;

                    case 4:
                        nameMethodWinForms  = "DES";
                        windowsForm.Encrypt = method.DesDecrypt(windowsForm.Encrypt);
                        break;

                    case 5:
                        nameMethodWinForms  = "Triple DES";
                        windowsForm.Encrypt = method.TripleDesDecrypt(windowsForm.EncryptByte);
                        break;

                    case 6:
                        nameMethodWinForms  = "RC4";
                        windowsForm.Encrypt = method.Rc4DecryptString(windowsForm.Encrypt);
                        break;
                    }

                    switch (windowsForm.NumberMethodWCF)
                    {
                    case 0:
                        nameMethodWcf = "Clear group";
                        break;

                    case 1:
                        nameMethodWcf       = "MD5";
                        windowsForm.Encrypt = method.GetMd5Hash(windowsForm.Encrypt);
                        break;

                    case 2:
                        nameMethodWcf       = "RSA";
                        EncryptByte         = method.RsaEncryptByte(windowsForm.Encrypt);
                        windowsForm.Encrypt = Convert.ToBase64String(EncryptByte);
                        break;

                    case 3:
                        nameMethodWcf       = "AES";
                        EncryptByte         = method.AesEncryptByte(windowsForm.Encrypt);
                        windowsForm.Encrypt = Convert.ToBase64String(EncryptByte);
                        break;

                    case 4:
                        nameMethodWcf       = "DES";
                        windowsForm.Encrypt = method.DesEncryptString(windowsForm.Encrypt);
                        break;

                    case 5:
                        nameMethodWcf       = "Triple DES";
                        EncryptByte         = method.TripleDesEncrypt(windowsForm.Encrypt);
                        windowsForm.Encrypt = Convert.ToBase64String(EncryptByte);
                        break;

                    case 6:
                        nameMethodWcf       = "RC4";
                        windowsForm.Encrypt = method.Rc4EncryptString(windowsForm.Encrypt);
                        break;
                    }

                    switch (windowsForm.NumberMethodMsSQL)
                    {
                    case 0:
                        nameMethodMsSQL = "Clear group";
                        codeHashCommand = "'" + windowsForm.Encrypt + "'";
                        break;

                    case 1:
                        nameMethodMsSQL = "MD4";
                        codeHashCommand = "HASHBYTES('MD4', '" + windowsForm.Encrypt + "')";
                        break;

                    case 2:
                        nameMethodMsSQL = "MD5";
                        codeHashCommand = "HASHBYTES('MD5', '" + windowsForm.Encrypt + "')";
                        break;

                    case 3:
                        nameMethodMsSQL = "SHA";
                        codeHashCommand = "HASHBYTES('SHA', '" + windowsForm.Encrypt + "')";
                        break;

                    case 4:
                        nameMethodMsSQL = "SHA1";
                        codeHashCommand = "HASHBYTES('SHA1', '" + windowsForm.Encrypt + "')";
                        break;

                    case 5:
                        nameMethodMsSQL = "SHA2_256";
                        codeHashCommand = "HASHBYTES('SHA2_256', '" + windowsForm.Encrypt + "')";
                        break;

                    case 6:
                        nameMethodMsSQL = "SHA2_512";
                        codeHashCommand = "HASHBYTES('SHA2_512', '" + windowsForm.Encrypt + "')";
                        break;
                    }

                    string stopWcf = DateTime.Now.ToString("yyyy-MM-dd  HH:mm:ss.ffffff");
                    string requestInstertInTable =
                        @"Insert into[BazaTestowa].[dbo].[TestMethodAlgorithms]
                    ([WinStart]
                    ,[WinStop]
                    ,[WcfStart]
                    ,[WcfStop]
                    ,[NameMethodWcf]
                    ,[NameBaseMethod]
                    ,[ContentCrypt]
                    ,[Type]
                    ,[BaseStop]
                    ,[NameMethodWinForms]
                    ,[Option]
                    ,[Repeat]
                    ,[Delay])
                     Values('" + windowsForm.StartWinForms + "', '" + windowsForm.StopWinforms + "', '" + runWcf + "', '" + stopWcf + "', '" + nameMethodWcf + "', '" + nameMethodMsSQL + "', " + codeHashCommand + ",'" + sizeInput + "', GETDATE(), '" + nameMethodWinForms + "','" + option + "','" + repeat + "','" + delay + "')";
                    ConMsSQL conMsSQL = new ConMsSQL();

                    conMsSQL.sqlcommand(requestInstertInTable);
                }
            }
            catch
            {
                return(string.Format("Can't connect to Ms SQL or Error WCF"));
            }


            return(string.Format("OK - request in WCF and MS SQL - Successful"));
        }
Beispiel #16
0
 private void SetModeViaConstructor()
 {
     //<snippet4>
     WSHttpBinding b = new WSHttpBinding(SecurityMode.Message);
     //</snippet4>
 }
Beispiel #17
0
        /// <summary>
        /// 创建传输协议
        /// </summary>
        /// <param name="binding">传输协议名称</param>
        /// <returns></returns>
        private static Binding CreateBinding(string binding)
        {
            Binding bindinginstance = null;

            if (binding.ToLower() == "basichttpbinding")
            {
                var ws = new BasicHttpBinding
                {
                    MaxBufferSize          = 2147483647,
                    MaxBufferPoolSize      = 2147483647,
                    MaxReceivedMessageSize = 2147483647,
                    ReaderQuotas           = { MaxStringContentLength = 2147483647 },
                    CloseTimeout           = new TimeSpan(0, 10, 0),
                    OpenTimeout            = new TimeSpan(0, 10, 0),
                    ReceiveTimeout         = new TimeSpan(0, 10, 0),
                    SendTimeout            = new TimeSpan(0, 10, 0)
                };

                bindinginstance = ws;
            }
            else if (binding.ToLower() == "netnamedpipebinding")
            {
                var ws = new NetNamedPipeBinding {
                    MaxReceivedMessageSize = 65535000
                };
                bindinginstance = ws;
            }
            else if (binding.ToLower() == "netpeertcpbinding")
            {
                var ws = new NetPeerTcpBinding {
                    MaxReceivedMessageSize = 65535000
                };
                bindinginstance = ws;
            }
            else if (binding.ToLower() == "nettcpbinding")
            {
                var ws = new NetTcpBinding {
                    MaxReceivedMessageSize = 65535000, Security = { Mode = SecurityMode.None }
                };
                bindinginstance = ws;
            }
            else if (binding.ToLower() == "wsdualhttpbinding")
            {
                var ws = new WSDualHttpBinding {
                    MaxReceivedMessageSize = 65535000
                };

                bindinginstance = ws;
            }
            else if (binding.ToLower() == "webhttpbinding")
            {
                var ws = new WebHttpBinding {
                    MaxReceivedMessageSize = 65535000
                };
                bindinginstance = ws;
            }
            else if (binding.ToLower() == "wsfederationhttpbinding")
            {
                var ws = new WSFederationHttpBinding {
                    MaxReceivedMessageSize = 65535000
                };
                bindinginstance = ws;
            }
            else if (binding.ToLower() == "wshttpbinding")
            {
                var ws = new WSHttpBinding(SecurityMode.None)
                {
                    MaxReceivedMessageSize = 65535000
                };
                ws.Security.Message.ClientCredentialType   = System.ServiceModel.MessageCredentialType.Windows;
                ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                bindinginstance = ws;
            }
            return(bindinginstance);
        }
Beispiel #18
0
        public void MessageSecurityNoSecureConversation()
        {
            WSHttpBinding b = new WSHttpBinding();

            b.Security.Message.EstablishSecurityContext = false;
            SymmetricSecurityBindingElement sbe = b.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();

            Assert.IsNotNull(sbe, "#0");

            Assert.AreEqual(
                typeof(SspiSecurityTokenParameters),
                sbe.ProtectionTokenParameters.GetType(), "#1");
            // no worthy to check SSPI security as we never support it.

            b.Security.Message.ClientCredentialType = MessageCredentialType.None;
            sbe = b.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();
            SslSecurityTokenParameters ssltp =
                sbe.ProtectionTokenParameters
                as SslSecurityTokenParameters;

            Assert.IsNotNull(ssltp, "#2-1");
            Assert.AreEqual(true, ssltp.RequireCancellation, "#2-2");
            Assert.AreEqual(false, ssltp.RequireClientCertificate, "#2-3");

            b.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            sbe   = b.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();
            ssltp = sbe.ProtectionTokenParameters as SslSecurityTokenParameters;
            Assert.IsNotNull(ssltp, "#3-1");

            // No NegotiateServiceCredential modes ...

            b.Security.Message.NegotiateServiceCredential = false;
            b.Security.Message.ClientCredentialType       = MessageCredentialType.Windows;
            sbe = b.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();
            KerberosSecurityTokenParameters ktp =
                sbe.ProtectionTokenParameters
                as KerberosSecurityTokenParameters;

            Assert.IsNotNull(ktp, "#4-1");
            // no worthy of testing windows-only Kerberos stuff

            b.Security.Message.ClientCredentialType = MessageCredentialType.None;
            sbe = b.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();
            X509SecurityTokenParameters x509tp =
                sbe.ProtectionTokenParameters
                as X509SecurityTokenParameters;

            Assert.IsNotNull(x509tp, "#5-1");
            Assert.AreEqual(X509KeyIdentifierClauseType.Thumbprint, x509tp.X509ReferenceStyle, "#5-2");
            Assert.AreEqual(SecurityTokenInclusionMode.Never, x509tp.InclusionMode, "#5-3");

            b.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
            sbe = b.CreateBindingElements().Find <SymmetricSecurityBindingElement> ();
            Assert.AreEqual(1, sbe.EndpointSupportingTokenParameters.Endorsing.Count, "#6-0");
            x509tp = sbe.EndpointSupportingTokenParameters.Endorsing [0] as X509SecurityTokenParameters;
            Assert.IsNotNull(x509tp, "#6-1");
            Assert.AreEqual(X509KeyIdentifierClauseType.Thumbprint, x509tp.X509ReferenceStyle, "#6-2");
            Assert.AreEqual(SecurityTokenInclusionMode.AlwaysToRecipient, x509tp.InclusionMode, "#6-3");
            Assert.AreEqual(false, x509tp.RequireDerivedKeys, "#6-4");
            x509tp = sbe.ProtectionTokenParameters as X509SecurityTokenParameters;
            Assert.IsNotNull(x509tp, "#7-1");
            Assert.AreEqual(X509KeyIdentifierClauseType.Thumbprint, x509tp.X509ReferenceStyle, "#7-2");
            Assert.AreEqual(SecurityTokenInclusionMode.Never, x509tp.InclusionMode, "#7-3");
            Assert.AreEqual(true, x509tp.RequireDerivedKeys, "#7-4");
            Assert.AreEqual(true, sbe.RequireSignatureConfirmation, "#8");
        }
Beispiel #19
0
        /// <summary>
        /// 生成Binding对象
        /// <code>
        /// WCFMateHelper.BindingFactory(config, e)
        /// </code>
        /// </summary>
        /// <param name="config"></param>
        /// <param name="chanelEndpoint"></param>
        /// <returns></returns>
        public static Binding BindingFactory(System.Configuration.Configuration config, ChannelEndpointElement chanelEndpoint)
        {
            BindingsSection bindings = config.GetSection("system.serviceModel/bindings") as BindingsSection;

            BindingCollectionElement bc = bindings[chanelEndpoint.Binding];

            //chanelEndpoint.
            if (chanelEndpoint.Binding != "")
            {
                switch (chanelEndpoint.Binding.ToLower())
                {
                case "nettcpbinding":
                {
                    NetTcpBinding        ntb = new NetTcpBinding();
                    NetTcpBindingElement bce = bc.ConfiguredBindings.FirstOrDefault(o => o.Name == chanelEndpoint.BindingConfiguration) as NetTcpBindingElement;
                    if (bce != null)
                    {
                        ntb.CloseTimeout                        = bce.CloseTimeout;
                        ntb.OpenTimeout                         = bce.OpenTimeout;
                        ntb.ReceiveTimeout                      = bce.ReceiveTimeout;
                        ntb.SendTimeout                         = bce.SendTimeout;
                        ntb.MaxBufferPoolSize                   = bce.MaxBufferPoolSize;
                        ntb.HostNameComparisonMode              = bce.HostNameComparisonMode;
                        ntb.ListenBacklog                       = (bce.ListenBacklog != 0 ? bce.ListenBacklog : ntb.ListenBacklog);
                        ntb.MaxBufferSize                       = bce.MaxBufferSize;
                        ntb.MaxConnections                      = (bce.MaxConnections == 0 ? ntb.MaxConnections : bce.MaxConnections);
                        ntb.MaxReceivedMessageSize              = bce.MaxReceivedMessageSize;
                        ntb.PortSharingEnabled                  = bce.PortSharingEnabled;
                        ntb.ReaderQuotas.MaxArrayLength         = (bce.ReaderQuotas.MaxArrayLength != 0 ? bce.ReaderQuotas.MaxArrayLength : ntb.ReaderQuotas.MaxArrayLength);
                        ntb.ReaderQuotas.MaxDepth               = (bce.ReaderQuotas.MaxDepth != 0 ? bce.ReaderQuotas.MaxDepth : ntb.ReaderQuotas.MaxDepth);
                        ntb.ReaderQuotas.MaxBytesPerRead        = (bce.ReaderQuotas.MaxBytesPerRead != 0 ? bce.ReaderQuotas.MaxBytesPerRead : ntb.ReaderQuotas.MaxBytesPerRead);
                        ntb.ReaderQuotas.MaxNameTableCharCount  = (bce.ReaderQuotas.MaxNameTableCharCount != 0 ? bce.ReaderQuotas.MaxNameTableCharCount : ntb.ReaderQuotas.MaxNameTableCharCount);
                        ntb.ReaderQuotas.MaxStringContentLength = (bce.ReaderQuotas.MaxStringContentLength != 0 ? bce.ReaderQuotas.MaxStringContentLength : ntb.ReaderQuotas.MaxStringContentLength);
                        ntb.ReliableSession                     = new OptionalReliableSession()
                        {
                            Enabled = bce.ReliableSession.Enabled, InactivityTimeout = bce.ReliableSession.InactivityTimeout, Ordered = bce.ReliableSession.Ordered
                        };
                        ntb.Security = new NetTcpSecurity()
                        {
                            Mode = SecurityMode.None
                        };
                        ntb.TransactionFlow     = bce.TransactionFlow;
                        ntb.TransactionProtocol = bce.TransactionProtocol;
                        ntb.TransferMode        = bce.TransferMode;
                    }
                    return(ntb);
                }

                case "basichttpbinding":
                {
                    BasicHttpBinding        bhb = new BasicHttpBinding(BasicHttpSecurityMode.None);
                    BasicHttpBindingElement bce = bc.ConfiguredBindings.FirstOrDefault(o => o.Name == chanelEndpoint.BindingConfiguration) as BasicHttpBindingElement;
                    if (bce != null)
                    {
                        bhb.AllowCookies                        = bce.AllowCookies;
                        bhb.BypassProxyOnLocal                  = bce.BypassProxyOnLocal;
                        bhb.CloseTimeout                        = bce.CloseTimeout;
                        bhb.HostNameComparisonMode              = bce.HostNameComparisonMode;
                        bhb.MaxBufferPoolSize                   = bce.MaxBufferPoolSize;
                        bhb.MaxBufferSize                       = bce.MaxBufferSize;
                        bhb.MaxReceivedMessageSize              = bce.MaxReceivedMessageSize;
                        bhb.MessageEncoding                     = bce.MessageEncoding;
                        bhb.OpenTimeout                         = bce.OpenTimeout;
                        bhb.ProxyAddress                        = bce.ProxyAddress;
                        bhb.ReaderQuotas.MaxArrayLength         = (bce.ReaderQuotas.MaxArrayLength != 0 ? bce.ReaderQuotas.MaxArrayLength : bhb.ReaderQuotas.MaxArrayLength);
                        bhb.ReaderQuotas.MaxDepth               = (bce.ReaderQuotas.MaxDepth != 0 ? bce.ReaderQuotas.MaxDepth : bhb.ReaderQuotas.MaxDepth);
                        bhb.ReaderQuotas.MaxBytesPerRead        = (bce.ReaderQuotas.MaxBytesPerRead != 0 ? bce.ReaderQuotas.MaxBytesPerRead : bhb.ReaderQuotas.MaxBytesPerRead);
                        bhb.ReaderQuotas.MaxNameTableCharCount  = (bce.ReaderQuotas.MaxNameTableCharCount != 0 ? bce.ReaderQuotas.MaxNameTableCharCount : bhb.ReaderQuotas.MaxNameTableCharCount);
                        bhb.ReaderQuotas.MaxStringContentLength = (bce.ReaderQuotas.MaxStringContentLength != 0 ? bce.ReaderQuotas.MaxStringContentLength : bhb.ReaderQuotas.MaxStringContentLength);
                        bhb.ReceiveTimeout                      = bce.ReceiveTimeout;
                        bhb.SendTimeout                         = bce.SendTimeout;
                        bhb.TextEncoding                        = bce.TextEncoding;
                        bhb.TransferMode                        = bce.TransferMode;
                        bhb.UseDefaultWebProxy                  = bce.UseDefaultWebProxy;
                    }
                    return(bhb);
                }

                case "wshttpbinding":
                {
                    WSHttpBinding        bhb = new WSHttpBinding(SecurityMode.None);
                    WSHttpBindingElement bce = bc.ConfiguredBindings.FirstOrDefault(o => o.Name == chanelEndpoint.BindingConfiguration) as WSHttpBindingElement;
                    if (bce != null)
                    {
                        bhb.AllowCookies                        = bce.AllowCookies;
                        bhb.BypassProxyOnLocal                  = bce.BypassProxyOnLocal;
                        bhb.CloseTimeout                        = bce.CloseTimeout;
                        bhb.HostNameComparisonMode              = bce.HostNameComparisonMode;
                        bhb.MaxBufferPoolSize                   = bce.MaxBufferPoolSize;
                        bhb.MaxReceivedMessageSize              = bce.MaxReceivedMessageSize;
                        bhb.MessageEncoding                     = bce.MessageEncoding;
                        bhb.OpenTimeout                         = bce.OpenTimeout;
                        bhb.ProxyAddress                        = bce.ProxyAddress;
                        bhb.ReaderQuotas.MaxArrayLength         = (bce.ReaderQuotas.MaxArrayLength != 0 ? bce.ReaderQuotas.MaxArrayLength : bhb.ReaderQuotas.MaxArrayLength);
                        bhb.ReaderQuotas.MaxDepth               = (bce.ReaderQuotas.MaxDepth != 0 ? bce.ReaderQuotas.MaxDepth : bhb.ReaderQuotas.MaxDepth);
                        bhb.ReaderQuotas.MaxBytesPerRead        = (bce.ReaderQuotas.MaxBytesPerRead != 0 ? bce.ReaderQuotas.MaxBytesPerRead : bhb.ReaderQuotas.MaxBytesPerRead);
                        bhb.ReaderQuotas.MaxNameTableCharCount  = (bce.ReaderQuotas.MaxNameTableCharCount != 0 ? bce.ReaderQuotas.MaxNameTableCharCount : bhb.ReaderQuotas.MaxNameTableCharCount);
                        bhb.ReaderQuotas.MaxStringContentLength = (bce.ReaderQuotas.MaxStringContentLength != 0 ? bce.ReaderQuotas.MaxStringContentLength : bhb.ReaderQuotas.MaxStringContentLength);
                        bhb.ReceiveTimeout                      = bce.ReceiveTimeout;
                        bhb.SendTimeout                         = bce.SendTimeout;
                        bhb.TextEncoding                        = bce.TextEncoding;
                        bhb.TransactionFlow                     = bce.TransactionFlow;
                        bhb.UseDefaultWebProxy                  = bce.UseDefaultWebProxy;
                    }
                    return(bhb);
                }
                }
            }

            throw new BindingNotFoundException(Resources.BindingNotFoundException);
        }
        internal static void DemandTransactionPermissions(ServiceEndpoint endpoint, string operationName)
        {
            bool transactionFlow   = false;
            bool flowOptionAllowed = false;

            if (endpoint.Binding is NetMsmqBinding)
            {
                NetMsmqBinding msmqBinding = endpoint.Binding as NetMsmqBinding;
                if (msmqBinding.Durable)
                {
                    transactionFlow = true;
                    if (Transaction.Current != null)
                    {
                        flowOptionAllowed = true;
                    }
                }
            }

            if (endpoint.Binding is NetTcpBinding)
            {
                NetTcpBinding tcpBinding = endpoint.Binding as NetTcpBinding;
                transactionFlow = tcpBinding.TransactionFlow;
            }
            if (endpoint.Binding is NetNamedPipeBinding)
            {
                NetNamedPipeBinding ipcBinding = endpoint.Binding as NetNamedPipeBinding;
                transactionFlow = ipcBinding.TransactionFlow;
            }
            if (endpoint.Binding is WSHttpBinding)
            {
                WSHttpBinding wsBinding = endpoint.Binding as WSHttpBinding;
                transactionFlow = wsBinding.TransactionFlow;
            }
            if (endpoint.Binding is WSDualHttpBinding)
            {
                WSDualHttpBinding wsDualBinding = endpoint.Binding as WSDualHttpBinding;
                transactionFlow = wsDualBinding.TransactionFlow;
            }
            if (transactionFlow)
            {
                if (Transaction.Current != null)
                {
                    //If operationName is null, then at least one operation needs to allow flow
                    foreach (OperationDescription operation in endpoint.Contract.Operations)
                    {
                        string name = operationName ?? operation.Name;
                        if (name != operation.Name)
                        {
                            continue;
                        }
                        TransactionFlowAttribute attribute = operation.Behaviors.Find <TransactionFlowAttribute>();
                        if (attribute == null)
                        {
                            continue;
                        }
                        if (attribute.Transactions != TransactionFlowOption.NotAllowed)
                        {
                            flowOptionAllowed = true;
                            break;
                        }
                    }
                    if (flowOptionAllowed)
                    {
                        IPermission distributedTransactionPermission = new DistributedTransactionPermission(PermissionState.Unrestricted);
                        distributedTransactionPermission.Demand();
                    }
                }
            }
        }
Beispiel #21
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="serviceUrl">服务地址</param>
 /// <param name="openSecurity">是否开启安全校验</param>
 /// <param name="wsHttpBinding">自定义绑定</param>
 public WcfHost(string serviceUrl = "http://127.0.0.1:14725", bool openSecurity = false, WSHttpBinding wsHttpBinding = null)
 {
     _serviceUrl  = serviceUrl;
     OpenSecurity = openSecurity;
     if (wsHttpBinding == null)
     {
         _wsHttpBinding = OpenSecurity ? WcfHelper.GetDefaultBinding(true) : WcfHelper.GetDefaultBinding(false);
     }
     else
     {
         _wsHttpBinding = wsHttpBinding;
     }
     InitService();
 }
        static bool IsAnonymous(ServiceEndpoint endpoint)
        {
            if (SecurityEnabled(endpoint) == false)
            {
                return(true);
            }
            bool anonymous = false;

            if (endpoint.Binding is NetTcpBinding)
            {
                NetTcpBinding binding = endpoint.Binding as NetTcpBinding;
                if (binding.Security.Mode == SecurityMode.Message)
                {
                    anonymous = binding.Security.Message.ClientCredentialType == MessageCredentialType.None;
                }
                if (binding.Security.Mode == SecurityMode.Transport)
                {
                    anonymous = binding.Security.Transport.ClientCredentialType == TcpClientCredentialType.None;
                }
            }
            if (endpoint.Binding is NetMsmqBinding)
            {
                NetMsmqBinding binding = endpoint.Binding as NetMsmqBinding;
                if (binding.Security.Mode == NetMsmqSecurityMode.Message)
                {
                    anonymous = binding.Security.Message.ClientCredentialType == MessageCredentialType.None;
                }
                if (binding.Security.Mode == NetMsmqSecurityMode.Transport)
                {
                    anonymous = binding.Security.Transport.MsmqAuthenticationMode == MsmqAuthenticationMode.None;
                }
            }
            if (endpoint.Binding is BasicHttpBinding)
            {
                BasicHttpBinding binding = endpoint.Binding as BasicHttpBinding;
                if (binding.Security.Mode == BasicHttpSecurityMode.Transport)
                {
                    anonymous = binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.None;
                }
            }
            if (endpoint.Binding is WSHttpBinding)
            {
                WSHttpBinding binding = endpoint.Binding as WSHttpBinding;
                if (binding.Security.Mode == SecurityMode.Message)
                {
                    anonymous = binding.Security.Message.ClientCredentialType == MessageCredentialType.None;
                }
                if (binding.Security.Mode == SecurityMode.Transport)
                {
                    anonymous = binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.None;
                }
            }
            if (endpoint.Binding is WSDualHttpBinding)
            {
                WSDualHttpBinding binding = endpoint.Binding as WSDualHttpBinding;
                if (binding.Security.Mode == WSDualHttpSecurityMode.Message)
                {
                    anonymous = binding.Security.Message.ClientCredentialType == MessageCredentialType.None;
                }
            }
            if (endpoint.Binding is WebHttpBinding)
            {
                WebHttpBinding binding = endpoint.Binding as WebHttpBinding;
                anonymous = binding.Security.Transport.ClientCredentialType == HttpClientCredentialType.None;
            }
            return(anonymous);
        }
        static private Binding GetBinding <TServiceInterfaceType>(HostBindingType bindingType)
        {
            object[] contractObjects          = typeof(TServiceInterfaceType).GetCustomAttributes(typeof(ServiceContractAttribute), false);
            string   serviceConfigurationName = null;

            if (contractObjects.Length > 0)
            {
                serviceConfigurationName = ((ServiceContractAttribute)contractObjects[0]).ConfigurationName;
            }

            if (String.IsNullOrEmpty(serviceConfigurationName))
            {
                serviceConfigurationName = typeof(TServiceInterfaceType).Name;
            }

            Binding binding;

            if (bindingType == HostBindingType.NetTcp)
            {
                string configurationName = String.Format("{0}_{1}", typeof(NetTcpBinding).Name, serviceConfigurationName);
                try
                {
                    binding = new NetTcpBinding(configurationName);
                }
                catch
                {
                    Platform.Log(LogLevel.Info, String.Format("unable to load binding configuration {0}; using default binding configuration", configurationName));
                    binding = new NetTcpBinding();
                }

                ((NetTcpBinding)binding).PortSharingEnabled = true;
            }
            else if (bindingType == HostBindingType.NamedPipes)
            {
                string configurationName = String.Format("{0}_{1}", typeof(NetNamedPipeBinding).Name, serviceConfigurationName);
                try
                {
                    binding = new NetNamedPipeBinding(configurationName);
                }
                catch
                {
                    Platform.Log(LogLevel.Info, "unable to load binding configuration {0}; using default binding configuration", configurationName);
                    binding = new NetNamedPipeBinding();
                }
            }
            else if (bindingType == HostBindingType.WSDualHttp)
            {
                string configurationName = String.Format("{0}_{1}", typeof(WSDualHttpBinding).Name, serviceConfigurationName);
                try
                {
                    binding = new WSDualHttpBinding(configurationName);
                }
                catch
                {
                    Platform.Log(LogLevel.Info, "unable to load binding configuration {0}; using default binding configuration", configurationName);
                    binding = new WSDualHttpBinding();
                }
            }
            else if (bindingType == HostBindingType.WSHttp)
            {
                string configurationName = String.Format("{0}_{1}", typeof(WSHttpBinding).Name, serviceConfigurationName);
                try
                {
                    binding = new WSHttpBinding(configurationName);
                }
                catch
                {
                    Platform.Log(LogLevel.Info, "unable to load binding configuration {0}; using default binding configuration", configurationName);
                    binding = new WSHttpBinding();
                }
            }
            else
            {
                string configurationName = String.Format("{0}_{1}", typeof(BasicHttpBinding).Name, serviceConfigurationName);
                try
                {
                    binding = new BasicHttpBinding(configurationName);
                }
                catch
                {
                    Platform.Log(LogLevel.Info, "unable to load binding configuration {0}; using default binding configuration", configurationName);
                    binding = new BasicHttpBinding();
                }
            }

            return(binding);
        }
        public TClient CreateServiceClient()
        {
            if (_config == null)
            {
                throw new ConfigurationException("No configuration value was informed.");
            }

            if (_config.EndpointUri == null)
            {
                throw new ConfigurationException("The remote service Uri was not present in the configuration provided.");
            }

            DisposeExistingServiceClientIfRequired();

            ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)((obj, certificate, chain, errors) => true);
            EndpointAddress endpointAddress;

            if (_config.BindingType == BindingType.BasicHttpBinding)
            {
                //applying heuristics to identify the correct endpoint
                if (_config.EndpointUri.ToString().EndsWith(".svc"))
                {
                    endpointAddress = new EndpointAddress(_config.EndpointUri + "/bhb");
                }
                else
                {
                    endpointAddress = new EndpointAddress(_config.EndpointUri);
                }


                BasicHttpBinding basicHttpBinding1 = new BasicHttpBinding();
                basicHttpBinding1.MaxBufferPoolSize      = int.MaxValue;
                basicHttpBinding1.MaxReceivedMessageSize = int.MaxValue;
                basicHttpBinding1.ReaderQuotas           = new XmlDictionaryReaderQuotas()
                {
                    MaxArrayLength         = int.MaxValue,
                    MaxBytesPerRead        = int.MaxValue,
                    MaxDepth               = 32,
                    MaxNameTableCharCount  = int.MaxValue,
                    MaxStringContentLength = int.MaxValue
                };
                basicHttpBinding1.MaxBufferSize      = int.MaxValue;
                basicHttpBinding1.UseDefaultWebProxy = true;
                basicHttpBinding1.OpenTimeout        = TimeSpan.FromSeconds(100);
                basicHttpBinding1.ReceiveTimeout     = TimeSpan.FromSeconds(100);
                basicHttpBinding1.SendTimeout        = TimeSpan.FromSeconds(100);
                basicHttpBinding1.CloseTimeout       = TimeSpan.FromSeconds(100);
                //Specifying Ntlm credential mode. Otherwise client will connect as Anonymous.
                basicHttpBinding1.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
                basicHttpBinding1.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
                basicHttpBinding1.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;



                _serviceClient = (TClient)Activator.CreateInstance(typeof(TClient), new object[] { basicHttpBinding1, endpointAddress });
            }
            if (_config.BindingType == BindingType.WSHttpBinding)
            {
                endpointAddress = new EndpointAddress(_config.EndpointUri);

                WSHttpBinding wsHttpBinding = new WSHttpBinding();
                wsHttpBinding.MaxBufferPoolSize      = int.MaxValue;
                wsHttpBinding.MaxReceivedMessageSize = int.MaxValue;
                wsHttpBinding.OpenTimeout            = TimeSpan.FromSeconds(100);
                wsHttpBinding.ReceiveTimeout         = TimeSpan.FromSeconds(100);
                wsHttpBinding.SendTimeout            = TimeSpan.FromSeconds(100);
                wsHttpBinding.CloseTimeout           = TimeSpan.FromSeconds(100);
                wsHttpBinding.ReaderQuotas           = new XmlDictionaryReaderQuotas()
                {
                    MaxArrayLength         = int.MaxValue,
                    MaxBytesPerRead        = int.MaxValue,
                    MaxDepth               = 32,
                    MaxNameTableCharCount  = int.MaxValue,
                    MaxStringContentLength = int.MaxValue
                };

                //Specifying Ntlm credential mode. Otherwise client will connect as Anonymous.
                wsHttpBinding.Security.Mode = SecurityMode.Message;
                wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
                wsHttpBinding.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;

                _serviceClient = (TClient)Activator.CreateInstance(typeof(TClient), new object[] { wsHttpBinding, endpointAddress });
            }

            if (string.IsNullOrEmpty(_config.Password) || string.IsNullOrEmpty(_config.Domain) || string.IsNullOrEmpty(_config.UserName))
            {
                throw new ArgumentException("Make sure the configuration provided contains Domain, Username and Password.");
            }

            _serviceClient.ClientCredentials.Windows.ClientCredential = new NetworkCredential(_config.UserName, _config.Password, _config.Domain);


            //if (!string.IsNullOrEmpty(_config.EndPointName))
            //   _serviceClient.Endpoint.Name = _config.EndPointName;

            //if (!string.IsNullOrEmpty(_config.Domain))
            //    this._serviceClient.ClientCredentials.Windows.ClientCredential.Domain = _config.Domain;
            //if (!string.IsNullOrEmpty(_config.UserName))
            //{
            //this._serviceClient.ClientCredentials.Windows.ClientCredential.UserName = _config.UserName;
            //this._serviceClient.ClientCredentials.UserName.UserName = !string.IsNullOrEmpty(_config.Domain) ? _config.Domain + "\\" + _config.UserName : _config.UserName;
            //}

            //_serviceClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            //this._serviceClient.ClientCredentials.UserName.Password = _config.Password;

            foreach (OperationDescription operationDescription in _serviceClient.Endpoint.Contract.Operations)
            {
                operationDescription.Behaviors.Find <DataContractSerializerOperationBehavior>().MaxItemsInObjectGraph = int.MaxValue;
            }
            _serviceClient.InnerChannel.OperationTimeout = TimeSpan.FromSeconds(100);
            return(_serviceClient);
        }
Beispiel #25
0
    static Binding GetBinding()
    {
        var result = new WSHttpBinding(SecurityMode.None);

        return(result);
    }
Beispiel #26
0
        public static List <WSHttpBinding> GetWsHttpBindings(string exeConfigPath)
        {
            if (string.IsNullOrWhiteSpace(exeConfigPath))
            {
                return(null);
            }

            var svcSection = Read.Config.ExeConfig.GetServiceModelSection(exeConfigPath);

            var configs = new List <WSHttpBinding>();

            foreach (
                var section in
                svcSection.Bindings.WSHttpBinding.ConfiguredBindings
                .Cast <WSHttpBindingElement>())
            {
                var df      = new WSHttpBinding();
                var binding = new WSHttpBinding
                {
                    Name = section.Name,

                    MaxBufferPoolSize      = section.MaxBufferPoolSize > 0 ? section.MaxBufferPoolSize : df.MaxBufferPoolSize,
                    MaxReceivedMessageSize = section.MaxReceivedMessageSize > 0 ? section.MaxReceivedMessageSize : df.MaxReceivedMessageSize,
                    CloseTimeout           = section.CloseTimeout != TimeSpan.Zero ? section.CloseTimeout : df.CloseTimeout,
                    OpenTimeout            = section.OpenTimeout != TimeSpan.Zero ? section.OpenTimeout : df.OpenTimeout,
                    SendTimeout            = section.SendTimeout != TimeSpan.Zero ? section.SendTimeout : df.SendTimeout,
                    ReceiveTimeout         =
                        section.ReceiveTimeout != TimeSpan.Zero ? section.ReceiveTimeout : df.ReceiveTimeout,

                    TextEncoding = section.TextEncoding ?? df.TextEncoding,

                    MessageEncoding        = section.MessageEncoding,
                    AllowCookies           = section.AllowCookies,
                    BypassProxyOnLocal     = section.BypassProxyOnLocal,
                    TransactionFlow        = section.TransactionFlow,
                    HostNameComparisonMode = section.HostNameComparisonMode,
                    UseDefaultWebProxy     = section.UseDefaultWebProxy,
                };

                var readerQuotasSection = section.ReaderQuotas;
                var readerQuotas        = new System.Xml.XmlDictionaryReaderQuotas();
                if (readerQuotasSection != null && readerQuotasSection.MaxDepth > 0)
                {
                    readerQuotas.MaxDepth = readerQuotasSection.MaxDepth;
                    readerQuotas.MaxStringContentLength = readerQuotasSection.MaxStringContentLength;
                    readerQuotas.MaxArrayLength         = readerQuotasSection.MaxArrayLength;
                    readerQuotas.MaxBytesPerRead        = readerQuotasSection.MaxBytesPerRead;
                    readerQuotas.MaxNameTableCharCount  = readerQuotasSection.MaxNameTableCharCount;
                }
                else
                {
                    readerQuotas = null;
                }

                var reliableSessionSection = section.ReliableSession;
                var dfRss           = new OptionalReliableSession();
                var reliableSession = new OptionalReliableSession
                {
                    Enabled           = reliableSessionSection.Enabled,
                    Ordered           = reliableSessionSection.Ordered,
                    InactivityTimeout =
                        reliableSessionSection.InactivityTimeout != TimeSpan.Zero
                            ? reliableSessionSection.InactivityTimeout
                            : dfRss.InactivityTimeout,
                };

                var messageSection = section.Security.Message;
                var message        = new NonDualMessageSecurityOverHttp
                {
                    EstablishSecurityContext   = messageSection.EstablishSecurityContext,
                    ClientCredentialType       = messageSection.ClientCredentialType,
                    NegotiateServiceCredential = messageSection.NegotiateServiceCredential,
                    AlgorithmSuite             = messageSection.AlgorithmSuite
                };

                var transportSection = section.Security.Transport;
                var transport        = new HttpTransportSecurity
                {
                    ClientCredentialType = transportSection.ClientCredentialType,
                    ProxyCredentialType  = transportSection.ProxyCredentialType
                };

                var wsHttpSecuritySection = section.Security;
                var wsHttpSecurity        = new WSHttpSecurity
                {
                    Mode      = wsHttpSecuritySection.Mode,
                    Transport = transport,
                    Message   = message
                };
                ;
                binding.Security = wsHttpSecurity;
                if (readerQuotas != null)
                {
                    binding.ReaderQuotas = readerQuotas;
                }
                binding.ReliableSession = reliableSession;

                configs.Add(binding);
            }
            return(configs);
        }
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        string[] urlTokens = baseAddresses[0].AbsolutePath.Split('/');
        string   version   = urlTokens[1].ToUpper();

        Type[] contractInterfaces = serviceType.GetInterfaces().Where(i => i.GetCustomAttributes(true).Where(a => a.GetType() == typeof(System.ServiceModel.ServiceContractAttribute)).Any()).ToArray();
        Type   contractType       = contractInterfaces.Where(i => i.Namespace.ToUpper().Contains(version)).Single();

        ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);

        WSHttpBinding wsHttpBinding = new WSHttpBinding();

        wsHttpBinding.SendTimeout            = new TimeSpan(0, 5, 0);
        wsHttpBinding.MaxReceivedMessageSize = Int32.MaxValue;
        wsHttpBinding.BypassProxyOnLocal     = true;
        wsHttpBinding.Security.Mode          = SecurityMode.None;
        //wsHttpBinding.TransactionFlow = true;
        //wsHttpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

        //ServiceEndpoint endpoint = host.AddServiceEndpoint(contractType, wsHttpBinding, "");

        WebHttpBinding webHttpBinding = new WebHttpBinding();

        webHttpBinding.Security.Mode = WebHttpSecurityMode.None;
        webHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
        webHttpBinding.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;
        webHttpBinding.BypassProxyOnLocal = true;

        ServiceEndpoint endpoint = host.AddServiceEndpoint(contractType, webHttpBinding, "");

        WebHttpBehavior webHttpBehavior = new WebHttpBehavior();

        webHttpBehavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
        //behavior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
        webHttpBehavior.DefaultBodyStyle      = WebMessageBodyStyle.Wrapped;
        webHttpBehavior.FaultExceptionEnabled = true;

        endpoint.Behaviors.Add(webHttpBehavior);

        ServiceMetadataBehavior metadataBehaviour;

        if ((host.Description.Behaviors.Contains(typeof(ServiceMetadataBehavior))))
        {
            metadataBehaviour = (ServiceMetadataBehavior)host.Description.Behaviors[typeof(ServiceMetadataBehavior)];
        }
        else
        {
            metadataBehaviour = new ServiceMetadataBehavior();
            host.Description.Behaviors.Add(metadataBehaviour);
        }
        metadataBehaviour.HttpGetEnabled = true;

        ServiceDebugBehavior debugBehaviour;

        if (host.Description.Behaviors.Contains(typeof(ServiceDebugBehavior)))
        {
            debugBehaviour = (ServiceDebugBehavior)host.Description.Behaviors[typeof(ServiceDebugBehavior)];
        }
        else
        {
            debugBehaviour = new ServiceDebugBehavior();
            host.Description.Behaviors.Add(debugBehaviour);
        }
        debugBehaviour.IncludeExceptionDetailInFaults = true;

        return(host);
    }
Beispiel #28
0
        /// <summary>
        /// 创建传输协议
        /// </summary>
        /// <param name="binding">传输协议名称</param>
        private static Binding CreateBinding(string binding)
        {
            Binding bindInstance = null;

            switch (binding.ToLower())
            {
            case "basichttpbinding":
            {
                var bind = new BasicHttpBinding
                {
                    CloseTimeout           = TimeSpan.MaxValue,
                    OpenTimeout            = TimeSpan.MaxValue,
                    ReceiveTimeout         = TimeSpan.MaxValue,
                    SendTimeout            = TimeSpan.MaxValue,
                    Security               = { Mode = BasicHttpSecurityMode.None },
                    MaxBufferPoolSize      = 2147483647,
                    MaxBufferSize          = 2147483647,
                    MaxReceivedMessageSize = 2147483647,
                    ReaderQuotas           = new System.Xml.XmlDictionaryReaderQuotas()
                    {
                        MaxStringContentLength = 655360000,
                        MaxArrayLength         = 163840,
                        MaxDepth              = 320,
                        MaxBytesPerRead       = 40960,
                        MaxNameTableCharCount = 163840
                    }
                };

                bindInstance = bind;
            }
            break;

            case "netnamedpipebinding":
            {
                var bind = new NetNamedPipeBinding {
                    MaxReceivedMessageSize = 65535000
                };
                bindInstance = bind;
            }
            break;

            case "nettcpbinding":
            {
                var bind = new NetTcpBinding
                {
                    CloseTimeout           = TimeSpan.MaxValue,
                    OpenTimeout            = TimeSpan.MaxValue,
                    ReceiveTimeout         = TimeSpan.MaxValue,
                    SendTimeout            = TimeSpan.MaxValue,
                    MaxBufferPoolSize      = 2147483647,
                    MaxBufferSize          = 2147483647,
                    MaxConnections         = 10,
                    MaxReceivedMessageSize = 2147483647,
                    ListenBacklog          = 100,
                    ReaderQuotas           = new System.Xml.XmlDictionaryReaderQuotas()
                    {
                        MaxStringContentLength = 655360000,
                        MaxArrayLength         = 163840,
                        MaxDepth              = 320,
                        MaxBytesPerRead       = 40960,
                        MaxNameTableCharCount = 163840
                    },
                    Security = { Mode = SecurityMode.None }
                };

                bindInstance = bind;
            }
            break;

            case "wsfederationhttpbinding":
            {
                var bind = new WSFederationHttpBinding {
                    MaxReceivedMessageSize = 65535000
                };
                bindInstance = bind;
            }
            break;

            case "wshttpbinding":
            {
                var ws = new WSHttpBinding(SecurityMode.None)
                {
                    MaxReceivedMessageSize = 65535000
                };
                ws.Security.Message.ClientCredentialType   = MessageCredentialType.Windows;
                ws.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                bindInstance = ws;
            }
            break;
            }
            return(bindInstance);
        }
        private Binding SetWSHttpBinding(WSHttpBinding binding)
        {
            binding.MaxReceivedMessageSize = 2147483647;

            return(binding);
        }
Beispiel #30
0
 public virtual CoreWCF.Channels.Binding ChangeBinding(WSHttpBinding wsBInding)
 {
     return(wsBInding);
 }
        internal static void ConfigureNone(IEnumerable <ServiceEndpoint> endpoints)
        {
            foreach (ServiceEndpoint endpoint in endpoints)
            {
                Binding binding = endpoint.Binding;

                if (binding is BasicHttpBinding)
                {
                    BasicHttpBinding basicBinding = (BasicHttpBinding)binding;
                    basicBinding.Security.Mode = BasicHttpSecurityMode.None;
                    continue;
                }
                if (binding is NetTcpBinding)
                {
                    NetTcpBinding tcpBinding = (NetTcpBinding)binding;
                    tcpBinding.Security.Mode = SecurityMode.None;
                    continue;
                }
                if (binding is NetPeerTcpBinding)
                {
                    NetPeerTcpBinding peerBinding = (NetPeerTcpBinding)binding;
                    peerBinding.Security.Mode = SecurityMode.None;
                    continue;
                }
                if (binding is NetNamedPipeBinding)
                {
                    NetNamedPipeBinding pipeBinding = (NetNamedPipeBinding)binding;
                    pipeBinding.Security.Mode = NetNamedPipeSecurityMode.None;
                    continue;
                }
                if (binding is WSHttpBinding)
                {
                    WSHttpBinding wsBinding = (WSHttpBinding)binding;
                    wsBinding.Security.Mode = SecurityMode.None;
                    continue;
                }
                if (binding is WSDualHttpBinding)
                {
                    WSDualHttpBinding wsDualBinding = (WSDualHttpBinding)binding;
                    wsDualBinding.Security.Mode = WSDualHttpSecurityMode.None;
                    continue;
                }
                if (binding is NetMsmqBinding)
                {
                    NetMsmqBinding msmqBinding = (NetMsmqBinding)binding;
                    msmqBinding.Security.Mode = NetMsmqSecurityMode.None;
                    continue;
                }
                if (endpoint.Contract.ContractType == typeof(IMetadataExchange))
                {
                    Trace.WriteLine("No declarative security for MEX endpoint");
                    continue;
                }
                if (endpoint is DiscoveryEndpoint)
                {
                    Trace.WriteLine("No declarative security for discovery endpoint");
                    continue;
                }
                throw new InvalidOperationException(binding.GetType() + " is unsupported with ServiceSecurity.None");
            }
        }
Beispiel #32
0
        private static bool IsBindingSupported(Binding binding)
        {
            s_bindingValidationErrors.Clear();

            if (!(binding is BasicHttpBinding || binding is NetHttpBinding || binding is WSHttpBinding || binding is NetTcpBinding || binding is CustomBinding))
            {
                s_bindingValidationErrors.Add(string.Format(SR.BindingTypeNotSupportedFormat, binding.GetType().FullName,
                                                            typeof(BasicHttpBinding).FullName, typeof(NetHttpBinding).FullName, typeof(WSHttpBinding).FullName, typeof(NetTcpBinding).FullName, typeof(CustomBinding).FullName));
            }
            else
            {
                WSHttpBinding wsHttpBinding = binding as WSHttpBinding;
                if (wsHttpBinding != null)
                {
                    if (wsHttpBinding.TransactionFlow)
                    {
                        s_bindingValidationErrors.Add(SR.BindingTransactionFlowNotSupported);
                    }
                    if (wsHttpBinding.Security.Mode == SecurityMode.Message)
                    {
                        s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", wsHttpBinding.Security.Mode));
                    }
                }
                else
                {
                    NetTcpBinding netTcpBinding = binding as NetTcpBinding;
                    if (netTcpBinding != null)
                    {
                        if (netTcpBinding.TransactionFlow)
                        {
                            s_bindingValidationErrors.Add(SR.BindingTransactionFlowNotSupported);
                        }
                        if (netTcpBinding.Security.Mode == SecurityMode.Message)
                        {
                            s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", netTcpBinding.Security.Mode));
                        }
                    }
                    else
                    {
                        NetHttpBinding netHttpBinding = binding as NetHttpBinding;
                        if (netHttpBinding != null)
                        {
                            if (netHttpBinding.Security.Mode == BasicHttpSecurityMode.Message)
                            {
                                s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", netHttpBinding.Security.Mode));
                            }
                        }
                        else
                        {
                            BasicHttpBinding basicHttpBinding = binding as BasicHttpBinding;
                            if (basicHttpBinding != null && basicHttpBinding.Security.Mode == BasicHttpSecurityMode.Message)
                            {
                                s_bindingValidationErrors.Add(string.Format(SRServiceModel.UnsupportedSecuritySetting, "Mode", basicHttpBinding.Security.Mode));
                            }
                        }
                    }
                }

                ValidateBindingElements(binding);
            }

            return(s_bindingValidationErrors.Count == 0);
        }
Beispiel #33
0
        /// <summary>
        /// 绑定的协议
        /// </summary>
        /// <param name="strBindingName">strBindingName</param>
        /// <returns>Binding</returns>
        public static Binding WCfBindingName(string strBindingName)
        {
            switch (strBindingName.ToUpper())
            {
            case "WSHTTPBINDING":
                WSHttpBinding wsbinding = new WSHttpBinding();
                wsbinding.MaxReceivedMessageSize = 4048000;
                wsbinding.MaxBufferPoolSize      = 1048576;
                wsbinding.ReaderQuotas.MaxStringContentLength = 4048000;
                wsbinding.ReaderQuotas.MaxArrayLength         = 4048000;
                wsbinding.ReaderQuotas.MaxBytesPerRead        = 4048000;
                wsbinding.SendTimeout = new TimeSpan(0, 3, 0);
                return(wsbinding);

            case "WSDUALHTTPBINDING":
                WSDualHttpBinding wsdbinding = new WSDualHttpBinding();
                wsdbinding.MaxReceivedMessageSize = 4048000;
                wsdbinding.MaxBufferPoolSize      = 1048576;
                wsdbinding.ReaderQuotas.MaxStringContentLength = 4048000;
                wsdbinding.ReaderQuotas.MaxArrayLength         = 4048000;
                wsdbinding.ReaderQuotas.MaxBytesPerRead        = 4048000;
                wsdbinding.SendTimeout = new TimeSpan(0, 3, 0);
                return(wsdbinding);

            case "WSFEDERATIONHTTPBINDING":
                WSFederationHttpBinding wsfe = new WSFederationHttpBinding();
                wsfe.MaxReceivedMessageSize = 4048000;
                wsfe.MaxBufferPoolSize      = 1048576;
                wsfe.ReaderQuotas.MaxStringContentLength = 4048000;
                wsfe.ReaderQuotas.MaxArrayLength         = 4048000;
                wsfe.ReaderQuotas.MaxBytesPerRead        = 4048000;
                wsfe.SendTimeout = new TimeSpan(0, 3, 0);
                return(wsfe);

            case "NETTCPBINDING":
                NetTcpBinding netTcpBinding = new NetTcpBinding();
                netTcpBinding.MaxReceivedMessageSize = 4048000;
                netTcpBinding.MaxBufferPoolSize      = 1048576;
                netTcpBinding.ReaderQuotas.MaxStringContentLength = 4048000;
                return(netTcpBinding);

            case "NETNAMEDPIPEBINDING":

                NetNamedPipeBinding netNamePipeBinding = new NetNamedPipeBinding();
                netNamePipeBinding.MaxReceivedMessageSize = 4048000;
                netNamePipeBinding.MaxBufferPoolSize      = 1048576;
                netNamePipeBinding.ReaderQuotas.MaxStringContentLength = 4048000;
                return(netNamePipeBinding);

            case "NETMSMQBINDING":
                return(new NetMsmqBinding());

            case "NETPEERTCPBINDING":
                return(new NetPeerTcpBinding());

            case "CUSTOMBINDING":
                BinaryMessageEncodingBindingElement encodingBindingElement = new BinaryMessageEncodingBindingElement();
                encodingBindingElement.ReaderQuotas.MaxStringContentLength = 4048000;
                HttpTransportBindingElement transportBindingElement = new HttpTransportBindingElement();
                transportBindingElement.MaxReceivedMessageSize = 4048000;
                transportBindingElement.MaxBufferSize          = 4048000;
                transportBindingElement.MaxBufferPoolSize      = 4048000;
                CustomBinding customBinding = new CustomBinding(encodingBindingElement, transportBindingElement);
                customBinding.SendTimeout = new TimeSpan(0, 3, 0);
                return(customBinding);

            default:
                BasicHttpBinding binding = new BasicHttpBinding();
                binding.MaxReceivedMessageSize = 4048000;
                binding.MaxBufferSize          = 4048000;
                binding.MaxBufferPoolSize      = 1048576;
                binding.ReaderQuotas.MaxStringContentLength = 4048000;
                binding.ReaderQuotas.MaxArrayLength         = 4048000;
                binding.ReaderQuotas.MaxBytesPerRead        = 4048000;
                binding.SendTimeout = new TimeSpan(0, 3, 0);
                return(binding);
            }
        }