Пример #1
1
        public static BasicHttpBinding CreateBasicBinding(Uri uri)
        {

            BasicHttpBinding binding = new BasicHttpBinding()
                {
                    CloseTimeout = TimeSpan.FromMinutes(1),
                    ReceiveTimeout = TimeSpan.FromMinutes(10),
                    SendTimeout = TimeSpan.FromMinutes(5),
                    AllowCookies = false,
                    BypassProxyOnLocal = false,
                    HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
                    MaxBufferSize = int.MaxValue,
                    MaxBufferPoolSize = 524288,
                    MaxReceivedMessageSize = int.MaxValue,
                    MessageEncoding = WSMessageEncoding.Text,
                    TextEncoding = Encoding.UTF8,
                    TransferMode = TransferMode.Buffered,
                    UseDefaultWebProxy = true
                };


            var quotas = binding.ReaderQuotas;
            quotas.MaxArrayLength =
                quotas.MaxBytesPerRead =
                quotas.MaxDepth =
                quotas.MaxNameTableCharCount =
                quotas.MaxStringContentLength = int.MaxValue;

            binding.Security.Mode = string.Equals(uri.Scheme, "https", StringComparison.OrdinalIgnoreCase) ? 
                BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly;

            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
            return binding;
        }
        public TimetableServiceConfiguration()
        {
            BasicHttpBinding httpBinding = new BasicHttpBinding();

            TimetableServiceClient =
                new TimetableServiceClient(httpBinding, EndPoints.TimetableService);
        }
        void MainPageLoaded(object sender, RoutedEventArgs e)
        {
            // Simple Version
            var basicHttpBinding = new BasicHttpBinding();
            var endpointAddress = new EndpointAddress("http://localhost:50738/UserGroupEvent.svc");
            var userGroupEventService = new ChannelFactory<IAsyncUserGroupEventService>(basicHttpBinding, endpointAddress).CreateChannel();

            AsyncCallback asyncCallBack = delegate(IAsyncResult result)
            {
                var response = ((IAsyncUserGroupEventService)result.AsyncState).EndGetUserGroupEvent(result);
                Dispatcher.BeginInvoke(() => SetUserGroupEventData(response));
            };
            userGroupEventService.BeginGetUserGroupEvent("123", asyncCallBack, userGroupEventService);

            // Deluxe Variante mit eigenem Proxy
            var channel = new UserGroupEventServiceProxy("BasicHttpBinding_IAsyncUserGroupEventService").Channel;
            channel.BeginGetUserGroupEvent("123", ProcessResult, channel);

            // Variante mit Faulthandler
            using (var scope = new OperationContextScope((IContextChannel)channel))
            {
                var messageHeadersElement = OperationContext.Current.OutgoingMessageHeaders;
                messageHeadersElement.Add(MessageHeader.CreateHeader("DoesNotHandleFault", "", true));
                channel.BeginGetUserGroupEventWithFault("123", ProcessResultWithFault, channel);
            }
        }
        public FileTransferServiceProxy()
        {
            this.m_BasicHttpBinding = new BasicHttpBinding();
            this.m_EndpointAddress = new EndpointAddress(EndpointAddressUrl);

            this.m_BasicHttpBinding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
            this.m_BasicHttpBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            this.m_BasicHttpBinding.MaxReceivedMessageSize = 2147483647;

            XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
            readerQuotas.MaxArrayLength = 25 * 208000;
            readerQuotas.MaxStringContentLength = 25 * 208000;
            this.m_BasicHttpBinding.ReaderQuotas = readerQuotas;

            this.m_ChannelFactory = new ChannelFactory<Contract.IFileTransferService>(this.m_BasicHttpBinding, this.m_EndpointAddress);
            this.m_ChannelFactory.Credentials.UserName.UserName = YellowstonePathology.YpiConnect.Contract.Identity.GuestWebServiceAccount.UserName;
            this.m_ChannelFactory.Credentials.UserName.Password = YellowstonePathology.YpiConnect.Contract.Identity.GuestWebServiceAccount.Password;

            foreach (System.ServiceModel.Description.OperationDescription op in this.m_ChannelFactory.Endpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            this.m_FileTransferServiceChannel = this.m_ChannelFactory.CreateChannel();
        }
Пример #5
0
        static void Main(string[] args)
        {
            Console.Title = "CLIENT";

            // Указание, где ожидать входящие сообщения.
            Uri address = new Uri("http://localhost:4000/IContract");

            // Указание, как обмениваться сообщениями.
            BasicHttpBinding binding = new BasicHttpBinding();

            // Создание Конечной Точки. 
            EndpointAddress endpoint = new EndpointAddress(address);

            // Создание фабрики каналов.
            ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, endpoint);

            // Использование factory для создания канала (прокси).
            IContract channel = factory.CreateChannel();
            
            // Использование канала для отправки сообщения получателю и приема ответа.
            string response = channel.Say("Hello WCF!");

            Console.WriteLine(response);

            // Задержка.
            Console.ReadKey();
        }
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            try
            {
                String factoryClass = this.GetType().Name;
                String endpointName =
                    String.Format("{0}HttpEndpoint",
                            factoryClass.Substring(0, factoryClass.IndexOf("ServiceHostFactory")));
                String externalEndpointAddress =
                    string.Format("http://{0}/{1}.svc",
                    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[endpointName].IPEndpoint,
                    serviceType.Name);

                var host = new ServiceHost(serviceType, new Uri(externalEndpointAddress));

                var basicBinding = new BasicHttpBinding(String.Format("{0}Binding", serviceType.Name));
                foreach (var intf in serviceType.GetInterfaces())
                    host.AddServiceEndpoint(intf, basicBinding, String.Empty);

                return host;
            }
            catch (Exception e)
            {
                Trace.TraceError("ServiceFactory: {0}{4}Exception: {1}{4}Message: {2}{4}Trace: {3}",
                               this.GetType().Name,
                               e.GetType(),
                               e.Message,
                               e.StackTrace,
                               Environment.NewLine);
                throw new SystemException(String.Format("Unable to activate service: {0}", serviceType.FullName), e);
            }
        }
        public CoreServiceProvider()
        {
            var binding = new BasicHttpBinding
            {
                MaxReceivedMessageSize = 10485760,
                ReaderQuotas = new XmlDictionaryReaderQuotas
                {
                    MaxStringContentLength = 10485760,
                    MaxArrayLength = 10485760
                },
                Security = new BasicHttpSecurity
                {
                    Mode = BasicHttpSecurityMode.TransportCredentialOnly,
                    Transport = new HttpTransportSecurity
                    {
                        ClientCredentialType = HttpClientCredentialType.Windows
                    }
                }
            };

            string coreServiceUrl = ConfigurationManager.AppSettings[Constants.TRIDION_CME_URL] + "/webservices/CoreService2013.svc/basicHttp";
            Console.WriteLine("Connect to CoreService " + coreServiceUrl);

            EndpointAddress endpoint = new EndpointAddress(coreServiceUrl);
            factory = new ChannelFactory<ICoreService>(binding, endpoint);

            string userName = ConfigurationManager.AppSettings[Constants.USER_NAME];
            string password = ConfigurationManager.AppSettings[Constants.PASSWORD];
            factory.Credentials.Windows.ClientCredential = new NetworkCredential(userName, password);

            Client = factory.CreateChannel();

            UserData user = Client.GetCurrentUser();
            Console.WriteLine("Connected as {0} ({1})", user.Description, user.Title);
        }
Пример #8
0
        static void Main(string[] args)
        {
            Console.Title = "CLIENT";

            // Указание, где ожидать входящие сообщения.
            Uri address = new Uri("http://localhost:4000/IContract");  // ADDRESS.   (A)

            // Указание, как обмениваться сообщениями.
            BasicHttpBinding binding = new BasicHttpBinding();         // BINDING.   (B)

            // Создание Конечной Точки.
            EndpointAddress endpoint = new EndpointAddress(address);

            // Создание фабрики каналов.
            ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, endpoint);  // CONTRACT.  (C) 

            // Использование factory для создания канала (прокси).
            IContract channel = factory.CreateChannel();
            
            // Использование канала для отправки сообщения получателю.
            channel.Say("Hello WCF!");// сложный механизм

            // Задержка.
            Console.ReadKey();
        }
Пример #9
0
        public ActionResult Unrecordingvoters()
        {
            var unrecordingCitizens = new List<NufusMudurluguService.Citizen>();
            var myBinding = new BasicHttpBinding();
            var myEndpoint = new EndpointAddress("http://192.168.1.222:9999/TCNufusMudurlugu/GetCitizens");
            var myChannelFactory = new ChannelFactory<IService1>(myBinding, myEndpoint);

            NufusMudurluguService.IService1 client = null;
            try
            {
                client = myChannelFactory.CreateChannel();
                var citizens = client.GetCitizens();
                foreach (var citizen in citizens)
                {
                    if (!m_internetDc.Voters.Any(f => f.IdentityNo == citizen.IdentityNo))
                    {
                        unrecordingCitizens.Add(citizen);
                    }
                }
                ViewData["Unrecording"] = unrecordingCitizens;
            }
            catch (Exception exp)
            {
            }
            return View();
        }
Пример #10
0
		public WebHttpSecurity ()
		{
			// there is no public constructor for transport ...
#if !NET_2_1
			Transport = new BasicHttpBinding ().Security.Transport;
#endif
		}
        private static bool FindUserServiceServer()
        {
            string[] serviceRootUrls = ConfigurationManager.AppSettings["LicenseHost"].Split(';');
            foreach (string serviceRootUrl in serviceRootUrls)
            {
                string serviceUrl = serviceRootUrl + "/Services/UserService.svc";
                System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None);

                binding.MaxReceivedMessageSize = 10485760; //1Gig

                System.ServiceModel.EndpointAddress endPointAddress = new System.ServiceModel.EndpointAddress(serviceUrl);

                BitSite.UserServiceReference.UserServiceClient client = new BitSite.UserServiceReference.UserServiceClient(binding, endPointAddress);
                try
                {
                    client.HandShake();
                    userServiceClient = client;
                    return(true);
                }
                catch
                {
                }
            }
            return(false);
        }
        public static PrimeSuiteServiceClient GetServiceClient(string IP)
        {
            string sMethodFullName = "Services." + System.Reflection.MethodBase.GetCurrentMethod().Name;

            try
            {

                string sIP = IP;
                string sServiceURL = "http://" + sIP + "/PrimeSuiteAPI/APIv1.0/PrimeSuiteAPI.svc";
                System.ServiceModel.EndpointAddress oEndpointAddress = new System.ServiceModel.EndpointAddress(sServiceURL);
                System.ServiceModel.BasicHttpBinding oBasicBinding = new System.ServiceModel.BasicHttpBinding();

                    oBasicBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
                    //"5242880" = 5MB
                    oBasicBinding.ReaderQuotas.MaxDepth = 2147483647;
                    oBasicBinding.ReaderQuotas.MaxArrayLength = 2147483647;
                    oBasicBinding.ReaderQuotas.MaxBytesPerRead = 2147483647;
                    oBasicBinding.ReaderQuotas.MaxNameTableCharCount = 2147483647;
                    oBasicBinding.MaxBufferSize = 2147483647;
                    oBasicBinding.MaxReceivedMessageSize = 2147483647;

                PrimeSuiteServiceClient client = new PrimeSuiteServiceClient(oBasicBinding, oEndpointAddress);
                ModifyDataContractSerializerBehavior(client.Endpoint);
                return (client);
            }
            catch (Exception ex)
            {
                //Throw New Exception("Error in " & sMethodFullName & ":" & vbNewLine & ex.Message & vbNewLine)
                throw ex;
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8773/BasicService");

            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Name = "Basic_Binding";
            binding.HostNameComparisonMode = HostNameComparisonMode.WeakWildcard;
            binding.Security.Mode = BasicHttpSecurityMode.None;

            using (ServiceHost host = new ServiceHost(typeof(BasicService), baseAddress))
            {
                host.AddServiceEndpoint(typeof(IBasicService), binding, "http://localhost:8773/BasicService/mex");
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
Пример #14
0
        private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
        {
            switch (endpointConfiguration)
            {
            case EndpointConfiguration.ReportExecutionServiceSoap:
            {
                System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
                result.MaxBufferSize          = 2147483647;
                result.ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
                result.MaxReceivedMessageSize = 2147483647L;
                result.AllowCookies           = true;
                return(result);
            }

            case EndpointConfiguration.ReportExecutionServiceSoap12:
            {
                System.ServiceModel.Channels.CustomBinding result2 = new System.ServiceModel.Channels.CustomBinding();
                System.ServiceModel.Channels.TextMessageEncodingBindingElement textBindingElement = new System.ServiceModel.Channels.TextMessageEncodingBindingElement();
                textBindingElement.MessageVersion = System.ServiceModel.Channels.MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, System.ServiceModel.Channels.AddressingVersion.None);
                result2.Elements.Add(textBindingElement);
                System.ServiceModel.Channels.HttpTransportBindingElement httpBindingElement = new System.ServiceModel.Channels.HttpTransportBindingElement();
                httpBindingElement.AllowCookies           = true;
                httpBindingElement.MaxBufferSize          = 2147483647;
                httpBindingElement.MaxReceivedMessageSize = 2147483647L;
                httpBindingElement.AuthenticationScheme   = System.Net.AuthenticationSchemes.Ntlm;
                result2.Elements.Add(httpBindingElement);
                return(result2);
            }

            default:
                throw new System.InvalidOperationException($"Could not find endpoint with name '{endpointConfiguration}'.");
            }
        }
Пример #15
0
 public Client(String URL)
 {
     BasicHttpBinding myBinding = new BasicHttpBinding();
     EndpointAddress  myEndpoint = new EndpointAddress(URL);
     myChannelFactory = new ChannelFactory<Server.IServerService>(myBinding, myEndpoint);
     comInterface = myChannelFactory.CreateChannel();
 }
Пример #16
0
		static void Main()
		{
			// только не null, ибо возникнет исключение
			//var baseAddress = new Uri("http://localhost:8002/MyService");
			var host = new ServiceHost(typeof(MyContractClient));//, baseAddress);

			host.Open();

			//var otherBaseAddress = new Uri("http://localhost:8001/");
			var otherHost = new ServiceHost(typeof(MyOtherContractClient));//, otherBaseAddress);
			var wsBinding = new BasicHttpBinding();
			var tcpBinding = new NetTcpBinding();
			otherHost.AddServiceEndpoint(typeof(IMyOtherContract), wsBinding, "http://localhost:8001/MyOtherService");
			otherHost.AddServiceEndpoint(typeof(IMyOtherContract), tcpBinding, "net.tcp://localhost:8003/MyOtherService");

			//AddHttpGetMetadata(otherHost);
			AddMexEndpointMetadata(otherHost);

			otherHost.Open();


			// you can access http://localhost:8002/MyService
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new Host());

			otherHost.Close();

			host.Close();

			// you can not access http://localhost:8002/MyService
		}
Пример #17
0
 public ServiceClientWrapper()
 {
     this.EndpointUri = UriProvider.GetNextUri();
     // var binding = new BasicHttpBinding("BasicHttpBinding_IRemoteWorkerService");
     var binding = new BasicHttpBinding();
     this.client = new WSClient.RemoteWorkerServiceClient(binding, new EndpointAddress(this.EndpointUri));
 }
        private ChannelFactory<ISharedTextEditorC2S> GetChannelFactory(string host)
        {
            var binding = new BasicHttpBinding();
            var endpoint = new EndpointAddress(host);

            return new ChannelFactory<ISharedTextEditorC2S>(binding, endpoint);
        }
Пример #19
0
    public static void BasicAuthentication_RoundTrips_Echo()
    {
        StringBuilder errorBuilder = new StringBuilder();

        try
        {
            BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

            ChannelFactory<IWcfCustomUserNameService> factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, new EndpointAddress(Endpoints.Https_BasicAuth_Address));
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";

            IWcfCustomUserNameService serviceProxy = factory.CreateChannel();

            string testString = "I am a test";
            string result = serviceProxy.Echo(testString);
            bool success = string.Equals(result, testString);

            if (!success)
            {
                errorBuilder.AppendLine(string.Format("Basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", "BasicAuthentication_RoundTrips_Echo", Endpoints.Https_BasicAuth_Address));
                errorBuilder.AppendLine(String.Format("    Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
            }
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(string.Format("Basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", "BasicAuthentication_RoundTrips_Echo", Endpoints.Https_BasicAuth_Address));
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
        }

        Assert.True(errorBuilder.Length == 0, String.Format("Test Case: BasicAuthentication FAILED with the following errors: {0}", errorBuilder));
    }
Пример #20
0
 public void Wait_120000()
 {
     try
     {
         output.WriteLine("Hello World!");
         System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
         binding.MaxBufferSize          = int.MaxValue;
         binding.ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
         binding.MaxReceivedMessageSize = int.MaxValue;
         binding.SendTimeout            = new TimeSpan(0, 5, 0);
         binding.OpenTimeout            = new TimeSpan(0, 5, 0);
         binding.CloseTimeout           = new TimeSpan(0, 5, 0);
         binding.ReceiveTimeout         = new TimeSpan(0, 5, 0);
         binding.AllowCookies           = true;
         binding.TransferMode           = TransferMode.StreamedResponse;
         EndpointAddress addressEndpoint =
             new EndpointAddress("http://localhost:50703/SayHelloService.svc");
         SayHelloServiceClient client = new SayHelloServiceClient(binding, addressEndpoint);
         client.OpenAsync().GetAwaiter().GetResult();
         var channel = client.InnerChannel;
         client.InnerChannel.OperationTimeout = TimeSpan.FromMinutes(10);
         var result = client.ServiceAsyncMethodAsync("hi").Result;
         output.WriteLine(result);
     }
     catch (Exception ex)
     {
         output.WriteLine(ex.Message);
     }
 }
Пример #21
0
        /// <summary>
        ///     Starts a <see cref="ServiceHost" /> for each found service. Defaults to <see cref="BasicHttpBinding" /> if
        ///     no user specified binding is found
        /// </summary>
        public void Startup(Unicast.UnicastBus bus)
        {
            Bus = bus;
            var conventions = bus.Builder.Build<Conventions>();
            var components = bus.Builder.Build<IConfigureComponents>();

            foreach (var serviceType in bus.Settings.GetAvailableTypes().Where(t => !t.IsAbstract && IsWcfService(t, conventions)))
            {
                var host = new WcfServiceHost(serviceType);

                Binding binding = new BasicHttpBinding();

                if (components.HasComponent<Binding>())
                {
                    binding = bus.Builder.Build<Binding>();
                }

                host.AddDefaultEndpoint(GetContractType(serviceType),
                    binding
                    , String.Empty);

                hosts.Add(host);

                logger.Debug("Going to host the WCF service: " + serviceType.AssemblyQualifiedName);
                host.Open();
            }
        }
Пример #22
0
 private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
 {
     if ((endpointConfiguration == EndpointConfiguration.KPSPublicSoap))
     {
         System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
         result.MaxBufferSize          = int.MaxValue;
         result.ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
         result.MaxReceivedMessageSize = int.MaxValue;
         result.AllowCookies           = true;
         result.Security.Mode          = System.ServiceModel.BasicHttpSecurityMode.Transport;
         return(result);
     }
     if ((endpointConfiguration == EndpointConfiguration.KPSPublicSoap12))
     {
         System.ServiceModel.Channels.CustomBinding result = new System.ServiceModel.Channels.CustomBinding();
         System.ServiceModel.Channels.TextMessageEncodingBindingElement textBindingElement = new System.ServiceModel.Channels.TextMessageEncodingBindingElement();
         textBindingElement.MessageVersion = System.ServiceModel.Channels.MessageVersion.CreateVersion(System.ServiceModel.EnvelopeVersion.Soap12, System.ServiceModel.Channels.AddressingVersion.None);
         result.Elements.Add(textBindingElement);
         System.ServiceModel.Channels.HttpsTransportBindingElement httpsBindingElement = new System.ServiceModel.Channels.HttpsTransportBindingElement();
         httpsBindingElement.AllowCookies           = true;
         httpsBindingElement.MaxBufferSize          = int.MaxValue;
         httpsBindingElement.MaxReceivedMessageSize = int.MaxValue;
         result.Elements.Add(httpsBindingElement);
         return(result);
     }
     throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
 }
Пример #23
0
        private static BlogServiceClient CreateBlogServiceClient(string username, string password)
        {
            BlogServiceClient blogServiceClient = null;

            System.ServiceModel.BasicHttpBinding basicHttpbinding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None);
            basicHttpbinding.Name = "BasicHttpBinding_IBlogService";
            basicHttpbinding.MaxReceivedMessageSize = 2147483646;
            basicHttpbinding.MaxBufferSize          = 2147483646;
            basicHttpbinding.MaxBufferPoolSize      = 2147483646;

            basicHttpbinding.ReaderQuotas.MaxArrayLength         = 2147483646;
            basicHttpbinding.ReaderQuotas.MaxStringContentLength = 5242880;
            basicHttpbinding.SendTimeout  = new TimeSpan(0, 5, 0);
            basicHttpbinding.CloseTimeout = new TimeSpan(0, 5, 0);

            basicHttpbinding.Security.Mode = BasicHttpSecurityMode.None;
            basicHttpbinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

            System.ServiceModel.EndpointAddress endpointAddress = new System.ServiceModel.EndpointAddress(hostURI);

            blogServiceClient = new BlogServiceClient(basicHttpbinding, endpointAddress);

            blogServiceClient.ChannelFactory.Endpoint.Behaviors.Add(new AuthenticationInspectorBehavior());
            ClientAuthenticationHeaderContext.HeaderInformation.Username = username;
            ClientAuthenticationHeaderContext.HeaderInformation.Password = password;

            return(blogServiceClient);
        }
Пример #24
0
 public static MixObjectsSoapClient CreateServiceClient()
 {
     var endpointAddr = new EndpointAddress(new Uri(Application.Current.Host.Source, Page.ServiceUrl));
     var binding = new BasicHttpBinding();
     var ctor = typeof(MixObjectsSoapClient).GetConstructor(new Type[] { typeof(Binding), typeof(EndpointAddress) });
     return (MixObjectsSoapClient)ctor.Invoke(new object[] { binding, endpointAddr });
 }
Пример #25
0
    public static void TextMessageEncoder_WrongContentTypeResponse_Throws_ProtocolException()
    {
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        string testContentType = "text/blah";
        Binding binding = null;

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            Assert.Throws<ProtocolException>(() => { serviceProxy.ReturnContentType(testContentType); });

            // *** VALIDATE *** \\

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Пример #26
0
    public static void UnexpectedException_Throws_FaultException()
    {
        string faultMsg = "This is a test fault msg";
        BasicHttpBinding binding = null;
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        EndpointAddress endpointAddress = null;

        FaultException<ExceptionDetail> exception = Assert.Throws<FaultException<ExceptionDetail>>(() =>
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding();
            endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic);
            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            try
            {
                serviceProxy.ThrowInvalidOperationException(faultMsg);
            }
            finally
            {
                // *** ENSURE CLEANUP *** \\
                ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
            }
        });

        // *** ADDITIONAL VALIDATION *** \\
        Assert.True(String.Equals(exception.Detail.Message, faultMsg), String.Format("Expected Fault Message: {0}, actual: {1}", faultMsg, exception.Detail.Message));
    }
		public void DefaultValueSecurityModeMessage ()
		{
			BasicHttpBinding b = new BasicHttpBinding (BasicHttpSecurityMode.Message);
			b.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
			DefaultValues (b);

			// BasicHttpSecurity
			BasicHttpSecurity sec = b.Security;
			Assert.IsNotNull (sec, "#2-1");
			Assert.AreEqual (BasicHttpSecurityMode.Message, sec.Mode, "#2-2");
			BasicHttpMessageSecurity msg = sec.Message;
			Assert.IsNotNull (msg, "#2-3-1");
			Assert.AreEqual (SecurityAlgorithmSuite.Default, msg.AlgorithmSuite, "#2-3-2");
			Assert.AreEqual (BasicHttpMessageCredentialType.Certificate, msg.ClientCredentialType, "#2-3-3");
			HttpTransportSecurity trans = sec.Transport;
			Assert.IsNotNull (trans, "#2-4-1");
			Assert.AreEqual (HttpClientCredentialType.None, trans.ClientCredentialType, "#2-4-2");
			Assert.AreEqual (HttpProxyCredentialType.None, trans.ProxyCredentialType, "#2-4-3");
			Assert.AreEqual ("", trans.Realm, "#2-4-4");

			// Binding elements
			BindingElementCollection bec = b.CreateBindingElements ();
			Assert.AreEqual (3, bec.Count, "#5-1");
			Assert.AreEqual (typeof (AsymmetricSecurityBindingElement),
				bec [0].GetType (), "#5-2");
			Assert.AreEqual (typeof (TextMessageEncodingBindingElement),
				bec [1].GetType (), "#5-3");
			Assert.AreEqual (typeof (HttpTransportBindingElement),
				bec [2].GetType (), "#5-4");
		}
Пример #28
0
        private SSRS2005ExecSvc.ReportExecutionServiceSoapClient getSSRS2005ExecClient()
        {
            var ssrsSettings = _config.GetSection("SSRS");

            //For http urls. If using https, use BasicHttpSecurityMode.Transport
            BasicHttpBinding ssrsBinding = new System.ServiceModel.BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
            //sizing of message settings to accomodate large report files.
            int maxReportSize = Convert.ToInt32(ssrsSettings["MaxReportBytes"]);

            ssrsBinding.MaxReceivedMessageSize = maxReportSize;
            ssrsBinding.MaxBufferSize          = maxReportSize;
            ssrsBinding.MaxBufferPoolSize      = Int32.MaxValue;
            ssrsBinding.ReaderQuotas.MaxDepth  = Int32.MaxValue;
            ssrsBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            ssrsBinding.ReaderQuotas.MaxArrayLength         = Int32.MaxValue;
            ssrsBinding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            ssrsBinding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;


            //Build URL of report

            string address = string.Format("{0}/{1}", ssrsSettings["ServerURL"].TrimEnd('/'), "ReportExecution2005.asmx");

            EndpointAddress ssrsAddress = new EndpointAddress(address);

            SSRS2005ExecSvc.ReportExecutionServiceSoapClient ssrsClient = new SSRS2005ExecSvc.ReportExecutionServiceSoapClient(ssrsBinding, ssrsAddress);

            ssrsClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            ssrsClient.ClientCredentials.Windows.ClientCredential          = System.Net.CredentialCache.DefaultNetworkCredentials;

            return(ssrsClient);
        }
 public void CreateChannel()
 {
   Binding binding;
   EndpointAddress endpointAddress;
   bool useAuth = !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password);
   if (IsLocal(ServerName))
   {
     endpointAddress = new EndpointAddress("net.pipe://localhost/MPExtended/TVAccessService");
     binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 10000000 };
   }
   else
   {
     endpointAddress = new EndpointAddress(string.Format("http://{0}:4322/MPExtended/TVAccessService", ServerName));
     BasicHttpBinding basicBinding = new BasicHttpBinding { MaxReceivedMessageSize = 10000000 };
     if (useAuth)
     {
       basicBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
       basicBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
     }
     basicBinding.ReaderQuotas.MaxStringContentLength = 5*1024*1024; // 5 MB
     binding = basicBinding;
   }
   binding.OpenTimeout = TimeSpan.FromSeconds(5);
   ChannelFactory<ITVAccessService> factory = new ChannelFactory<ITVAccessService>(binding);
   if (factory.Credentials != null && useAuth)
   {
     factory.Credentials.UserName.UserName = Username;
     factory.Credentials.UserName.Password = Password;
   }
   TvServer = factory.CreateChannel(endpointAddress);
 }
Пример #30
0
        public RightNowService(IGlobalContext _gContext)
        {
            // Set up SOAP API request to retrieve Endpoint Configuration -
            // Get the SOAP API url of current site as SOAP Web Service endpoint
            EndpointAddress endPointAddr = new EndpointAddress(_gContext.GetInterfaceServiceUrl(ConnectServiceType.Soap));

            // Minimum required
            BasicHttpBinding binding2 = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
            binding2.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

            // Optional depending upon use cases
            binding2.MaxReceivedMessageSize = 5 * 1024 * 1024;
            binding2.MaxBufferSize = 5 * 1024 * 1024;
            binding2.MessageEncoding = WSMessageEncoding.Mtom;

            // Create client proxy class
            _rnowClient = new RightNowSyncPortClient(binding2, endPointAddr);
            BindingElementCollection elements = _rnowClient.Endpoint.Binding.CreateBindingElements();
            elements.Find<SecurityBindingElement>().IncludeTimestamp = false;
            _rnowClient.Endpoint.Binding = new CustomBinding(elements);

            // Add SOAP msg inspector behavior
            //_rnowClient.Endpoint.Behaviors.Add(new LogMsgBehavior());

            // Ask the Add-In framework the handle the session logic
            _gContext.PrepareConnectSession(_rnowClient.ChannelFactory);

            // Set up query and set request
            _rnowClientInfoHeader = new ClientInfoHeader();
            _rnowClientInfoHeader.AppID = "Case Management Accelerator Services";
        }
Пример #31
0
        public static ProductManagerClient CreateProductManager()
        {
            BasicHttpBinding wsd = new BasicHttpBinding();
              wsd.Name = "WSHttpBinding_IProductManager";

              wsd.SendTimeout = new TimeSpan(0,5,0);
              wsd.MessageEncoding = WSMessageEncoding.Mtom;
              wsd.AllowCookies = false;
              wsd.BypassProxyOnLocal = false;
              wsd.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
              wsd.TextEncoding = Encoding.UTF8;
              wsd.TransferMode = TransferMode.Buffered;
              wsd.UseDefaultWebProxy = true;
              wsd.MaxReceivedMessageSize = 1048576 * 30; // 30 mb
              wsd.MaxBufferSize = 1048576 * 30;
              wsd.Security.Mode = BasicHttpSecurityMode.None;
              wsd.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
              wsd.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Default;
              wsd.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
              wsd.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
              wsd.Security.Transport.Realm = string.Empty;

              Uri baseAddress = new Uri("http://www.halan.se/service/ProductManager.svc/mtom");
              EndpointAddress ea = new EndpointAddress(baseAddress); // EndpointIdentity.CreateDnsIdentity("localhost"));

              return new ProductManagerClient(wsd, ea); //new ProductManagerClient("BasicHttpBinding_IProductManager");
        }
        private Binding GetHttpBinding()
        {
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;

            return binding;
        }
Пример #33
0
    public static void BasicAuthenticationInvalidPwd_throw_MessageSecurityException()
    {
        StringBuilder errorBuilder = new StringBuilder();
        // Will need to use localized string once it is available
        // On Native retail, the message is stripped to 'HttpAuthorizationForbidden, Basic'
        // On Debug or .Net Core, the entire message is "The HTTP request was forbidden with client authentication scheme 'Basic'."
        // Thus we will only check message contains "forbidden"
        string message = "forbidden";

        MessageSecurityException exception = Assert.Throws<MessageSecurityException>(() =>
        {
            BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

            ChannelFactory<IWcfCustomUserNameService> factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, new EndpointAddress(Endpoints.Https_BasicAuth_Address));
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";

            IWcfCustomUserNameService serviceProxy = factory.CreateChannel();

            string testString = "I am a test";
            string result = serviceProxy.Echo(testString);
        });
      
        Assert.True(exception.Message.ToLower().Contains(message), string.Format("Expected exception message to contain: '{0}', actual message is: '{1}'", message, exception.Message));
    }
    public static void DefaultSettings_Echo_RoundTrips_String()
    {
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        string testString = "Hello";
        Binding binding = null;

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

            // *** VALIDATE *** \\
            Assert.True(result == testString, String.Format("Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
        static void Main(string[] args)
        {
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            binding.Name = "binding";
            binding.MaxReceivedMessageSize = 500000;
            binding.AllowCookies = true;

            var client = new SyncReplyClient(binding, new EndpointAddress("https://platform.gaelenlighten.com/api/soap11"));

            using (new OperationContextScope(client.InnerChannel))
            {
                var requestMessage = new HttpRequestMessageProperty();
                requestMessage.Headers["Tenant"] = "tenant.gaelenlighten.com"; // Add your tenant
                var token = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("username:password")); // Add your username and password here
                requestMessage.Headers["Authorization"] = token;
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;

                var response = client.GetReports(new GetReports
                {
                    //// Specify filters
                    ReportStatus = ReportStatus.New,
                    Take = 100,
                    Skip = 0
                });

                var reportList = response.Reports;
                foreach (var report in reportList)
                {
                    ////Example of iterating through the report list
                }
                response.PrintDump();

                Console.ReadLine();
            }
        }
 public Binding Create(Endpoint serviceInterface)
 {
     if (Utilities.Utilities.GetDisableCertificateValidation().EqualsCaseInsensitive("true"))
         System.Net.ServicePointManager.ServerCertificateValidationCallback =
             ((sender, certificate, chain, sslPolicyErrors) => true);
     var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
     {
         Name = serviceInterface.EndpointName,
         AllowCookies = false,
         HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard),
         MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize,
         MaxReceivedMessageSize = serviceInterface.MaxReceivedSize,
         MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Text),
         TextEncoding = Encoding.UTF8,
         ReaderQuotas = XmlDictionaryReaderQuotas.Max,
         BypassProxyOnLocal = true,
         UseDefaultWebProxy = false
     };
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true")
     {
         binding.BypassProxyOnLocal = false;
         binding.UseDefaultWebProxy = true;
     }
     binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
     return binding;
 }
Пример #37
0
        private T GetProxy <T>()
        {
            System.ServiceModel.BasicHttpBinding httpBinding = ClientHelper.GetBufferedModeBinding();
            ChannelFactory <T> channelFactory = new ChannelFactory <T>(httpBinding, new System.ServiceModel.EndpointAddress(new Uri("http://localhost:8080/BasicWcfService/StreamingInputOutputService.svc")));
            T proxy = channelFactory.CreateChannel();

            return(proxy);
        }
Пример #38
0
 public RoleStore()
 {
     //to use unity
     var binding      = new System.ServiceModel.BasicHttpBinding();
     var endpoint     = new EndpointAddress("http://localhost:8081/user/");
     var factory      = new ChannelFactory <IRoleService>(binding, endpoint);
     var _RoleService = factory.CreateChannel();
 }
Пример #39
0
        public RoleWebService()
        {
            var binding  = new System.ServiceModel.BasicHttpBinding();
            var endpoint = new EndpointAddress("http://localhost:8081/roleservice/");
            var factory  = new ChannelFactory <IRoleService>(binding, endpoint);

            _RoleService = factory.CreateChannel();
        }
Пример #40
0
        public UserWebService()
        {
            var binding  = new System.ServiceModel.BasicHttpBinding();
            var endpoint = new EndpointAddress("http://localhost:8081/user/");
            var factory  = new ChannelFactory <IUserService>(binding, endpoint);

            _iuserService = factory.CreateChannel();
            //  _iuserService = new UserServiceClient();
        }
Пример #41
0
        private static UkPostalCodeService.LookupSoapClient CreateUkServiceClient()
        {
            var binding = new System.ServiceModel.BasicHttpBinding();
            var address = new System.ServiceModel.EndpointAddress("http://ws1.postcodesoftware.co.uk/lookup.asmx");

            var client = new UkPostalCodeService.LookupSoapClient(binding, address);

            return(client);
        }
Пример #42
0
        public DinerwareProvider()
        {
            ConfigurationHelper conFigHelper = new ConfigurationHelper();
            var endPointAddress = new System.ServiceModel.EndpointAddress(conFigHelper.URL_VIRTUALCLIENT);
            var binding         = new System.ServiceModel.BasicHttpBinding();

            binding.Security.Mode  = BasicHttpSecurityMode.None;
            virtualDinerwareClient = new VirtualClientClient(binding, endPointAddress);
        }
Пример #43
0
 public static System.ServiceModel.Channels.Binding GetBindingForEndpoint()
 {
     System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
     result.MaxBufferSize          = int.MaxValue;
     result.ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
     result.MaxReceivedMessageSize = int.MaxValue;
     result.AllowCookies           = true;
     return(result);
 }
Пример #44
0
        private static System.ServiceModel.BasicHttpBinding Binding()
        {
            var bing = new System.ServiceModel.BasicHttpBinding();

            bing.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
            bing.ReaderQuotas.MaxArrayLength         = 999999999;
            bing.ReaderQuotas.MaxStringContentLength = 999999999;
            bing.MaxReceivedMessageSize = 999999999;
            return(bing);
        }
Пример #45
0
 public Form1()
 {
     InitializeComponent();
     Pbar.Visible             = false;
     CPUlevel.SelectedIndex   = 0;
     dgvTopResults.DataSource = resultList;
     System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
     System.ServiceModel.EndpointAddress  address = new System.ServiceModel.EndpointAddress("http://fascinatinginformation.com/ADFGXService/Service.svc");
     client = new ServiceClient(binding, address);
 }
Пример #46
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();



            var             remoteAddress = new System.ServiceModel.EndpointAddress(SapiUrl);
            HttpBindingBase binding;

            if (remoteAddress.Uri.Scheme == "https")
            {
                binding = new System.ServiceModel.BasicHttpsBinding();
            }
            else
            {
                binding = new System.ServiceModel.BasicHttpBinding();
            }
            SapiClients.client = new SapiClient(binding, remoteAddress);
            var behaviour = new CustomAuthenticationBehaviour();

            SapiClients.client.Endpoint.EndpointBehaviors.Add(behaviour);

            pscConnectOptions pscOptions = new pscConnectOptions
            {
                base64     = Base64,
                authServer = Server,
                user       = User,
                password   = Password
            };

            if (PortSet)
            {
                pscOptions.portSpecified = true;
                pscOptions.port          = PortValue;
            }

            var loginResult = SapiClients.client.login(pscOptions);

            behaviour.ApplyAuthenticationToken(loginResult.token);
            var actionTask = SapiClients.client.connectAsync();

            var result      = Progress("Connect", actionTask);
            var finalResult = new SapiConnectResult(result);

            // For Interval in Seconds
            // This Scheduler will start after 0 hour and 15 minutes call after every 15 minutes
            // IntervalInSeconds(start_hour, start_minute, seconds)
            MyScheduler.IntervalInMinutes(0, 15, 15,
                                          () =>
            {
                SapiClients.client.keepalive();
            });
            WriteObject(finalResult); // This is what actually "returns" output.
        }
Пример #47
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="endPointAddress">The specific end point address</param>
 /// <param name="binding">Contains the binding elements that specify the protocols,
 /// transports, and message encoders used for communication between clients and services.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(string endPointAddress, System.ServiceModel.BasicHttpBinding binding,
               string username                                   = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(endPointAddress), binding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }
Пример #48
0
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="binding">Contains the binding elements that specify the protocols,
 /// transports, and message encoders used for communication between clients and services.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(System.ServiceModel.BasicHttpBinding binding, string username = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(Nequeo.Management.ServiceModel.Properties.Settings.Default.ServiceAddress),
         binding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }
 private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration)
 {
     if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IDBService))
     {
         System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding();
         result.MaxBufferSize          = int.MaxValue;
         result.ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
         result.MaxReceivedMessageSize = int.MaxValue;
         result.AllowCookies           = true;
         return(result);
     }
     throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
 }
Пример #50
0
        /// <summary>
        /// Kiểm tra kết nối tới một dịch vụ trên Server
        /// </summary>
        /// <param name="serverIp"></param>
        /// <param name="serverPort"></param>
        /// <param name="serviceEndpoint"></param>
        /// <returns></returns>
        public static void IsServiceAvailable(string serverIp, string serverPort, string serviceEndpoint)
        {
            //bool isAvailable = true;
            try
            {
                string address = "http://" + serverIp + ":" + serverPort + "/" + serviceEndpoint + ".svc?wsdl";
                //MetadataExchangeClient _mexClient = null;
                //_mexClient = new MetadataExchangeClient(new Uri(address), MetadataExchangeClientMode.HttpGet);
                //MetadataSet _metadataSet = _mexClient.GetMetadata();
                //isAvailable = true;

                System.ServiceModel.BasicHttpBinding _binding = getBasicHttpBinding(serviceEndpoint);
                _binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                _binding.MaxReceivedMessageSize = 52428800;
                System.Xml.XmlDictionaryReaderQuotas xmlDictionaryReaderQuotas = new XmlDictionaryReaderQuotas();
                xmlDictionaryReaderQuotas.MaxNameTableCharCount = 2147483647;
                _binding.ReaderQuotas = xmlDictionaryReaderQuotas;

                MetadataExchangeClient __mexClient = null;

                MetadataSet __metadataSet = null;

                if (_binding != null)
                {
                    __mexClient = new MetadataExchangeClient(_binding);
                    __mexClient.MaximumResolvedReferences = 1000;
                    __metadataSet = __mexClient.GetMetadata(new Uri(address), MetadataExchangeClientMode.HttpGet);
                }

                else
                {
                    //Import metadata
                    __mexClient = new MetadataExchangeClient(new Uri(address), MetadataExchangeClientMode.HttpGet);
                    __mexClient.MaximumResolvedReferences = 1000;
                    __metadataSet = __mexClient.GetMetadata();
                }
            }
            catch (Exception ex)
            {
                LLogging.WriteLog(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), LLogging.LogType.ERR, ex);
                throw new CustomException("M.ResponseMessage.Common.ServiceIsNotAvailable", null);
            }
            //return isAvailable;
        }
Пример #51
0
        public async Task <EnviarItemVirtualResponse> EnviarItemVirtual(EnviarItemVirtualRequest request)
        {
            var response = new EnviarItemVirtualResponse();

            try
            {
                var binding = new System.ServiceModel.BasicHttpBinding();
                binding.MaxBufferSize          = int.MaxValue;
                binding.ReaderQuotas           = System.Xml.XmlDictionaryReaderQuotas.Max;
                binding.MaxReceivedMessageSize = int.MaxValue;
                binding.AllowCookies           = true;

                var endpointAddress = new EndpointAddress(_dadosErp.EndpointErp + _dadosErp.RotaItemVirtual);

                var clientWs = new ItemVirtualClient(binding, endpointAddress);

                var responseWs = await clientWs.IncluirIVEAsync(new ItemVirtualEntradaDTO()
                {
                    GerencialId      = request.ItemVirtual.GerencialId,
                    IdUnidadeNegocio = request.ItemVirtual.IdUnidadeNegocio,
                    Sequencial       = request.ItemVirtual.Sequencial,
                    Usuario          = request.ItemVirtual.Usuario
                });

                if (responseWs.Mensagens != null && responseWs.Mensagens.Length > 0)
                {
                    foreach (var msg in responseWs.Mensagens)
                    {
                        response.AdicionarMensagemErro(TipoMensagem.ErroAplicacao, msg);
                    }
                }

                response.Valido = !responseWs.Erro;
            }
            catch (Exception ex)
            {
                response.AdicionarMensagemErro(TipoMensagem.ErroAplicacao, ex.Message);
                response.Valido = false;
            }

            return(response);
        }
Пример #52
0
        /// <summary>
        /// Thiết lập thông số dịch vụ kết nối giữa client và server
        /// </summary>
        /// <returns></returns>
        public static BasicHttpBinding getBasicHttpBinding(string bindingName)
        {
            System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();

            System.ServiceModel.ServiceBehaviorAttribute behavior = new System.ServiceModel.ServiceBehaviorAttribute();

            behavior.MaxItemsInObjectGraph = 2147483647;

            binding.Name = bindingName;

            //binding.CloseTimeout = new TimeSpan(0, 1, 0);
            binding.CloseTimeout = new TimeSpan(0, 30, 0);
            //binding.OpenTimeout = new TimeSpan(0, 1, 0);
            binding.OpenTimeout    = new TimeSpan(0, 30, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 30, 0);
            //binding.SendTimeout = new TimeSpan(0, 1, 0);
            binding.SendTimeout            = new TimeSpan(0, 30, 0);
            binding.AllowCookies           = true;
            binding.BypassProxyOnLocal     = true;
            binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
            binding.MaxBufferSize          = 2147483647;
            binding.MaxBufferPoolSize      = 2147483647;
            binding.MaxReceivedMessageSize = 2147483647;
            binding.MessageEncoding        = System.ServiceModel.WSMessageEncoding.Text;
            binding.TextEncoding           = System.Text.Encoding.UTF8;
            binding.TransferMode           = System.ServiceModel.TransferMode.Streamed;
            binding.UseDefaultWebProxy     = false;

            binding.ReaderQuotas.MaxDepth = 2147483647;
            binding.ReaderQuotas.MaxStringContentLength = 2147483647;
            binding.ReaderQuotas.MaxArrayLength         = 2147483647;
            binding.ReaderQuotas.MaxBytesPerRead        = 2147483647;
            binding.ReaderQuotas.MaxNameTableCharCount  = 2147483647;

            binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.None;
            binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
            binding.Security.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
            binding.Security.Message.ClientCredentialType   = System.ServiceModel.BasicHttpMessageCredentialType.UserName;
            binding.Security.Message.AlgorithmSuite         = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;

            return(binding);
        }
        public static AutorisationClient GetClient()
        {
            string serviceRootUrl = ConfigurationManager.AppSettings["LicenseHost"];
            string serviceUrl     = serviceRootUrl + "/Autorisation.svc";

            System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None);
            //binding.MaxBufferPoolSize = 2073741824; //2Gig //Int32.MaxValue;
            //binding.MaxBufferSize = 2073741824; //2Gig //Int32.MaxValue;
            //binding.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max;
            binding.MaxReceivedMessageSize = 10485760; //1Gig

            //TEST EMIEL
            //binding.UseDefaultWebProxy = false;
            //binding.TransferMode = TransferMode.Buffered;

            System.ServiceModel.EndpointAddress endPointAddress = new System.ServiceModel.EndpointAddress(serviceUrl);

            BitSite.BitAutorisationService.AutorisationClient client = new BitSite.BitAutorisationService.AutorisationClient(binding, endPointAddress);

            return(client);
        }
Пример #54
0
        //Listing 18-7. Screen Code to Send an E-mail via a Web Service Call
        partial void SendEmail_Execute()
        {
            Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() =>
            {
                Uri serverUrl = System.Windows.Application.Current.Host.Source;

                this.Details.Dispatcher.BeginInvoke(() =>
                {
                    //serverUrl.AbsoluteUri returns a URL like this:
                    //    http://localhost:49715/DesktopClient/Web/HelpDesk.Client.xap
                    string rootUrl =
                        serverUrl.AbsoluteUri.Substring(
                            0, serverUrl.AbsoluteUri.IndexOf("/DesktopClient/Web/"));

                    var binding = new System.ServiceModel.BasicHttpBinding();

                    //example endPoint url:
                    //   http://localhost:49715/MailService.svc/MailService.svc
                    var endPoint =
                        new EndpointAddress(rootUrl + "/MailService.svc/soap");

                    MailService.MailServiceClient proxy =
                        new MailService.MailServiceClient(binding, endPoint);

                    proxy.SendMailRESTCompleted +=
                        (object sender, MailService.SendMailRESTCompletedEventArgs e) =>
                    {
                        this.Details.Dispatcher.BeginInvoke(() =>
                        {
                            this.ShowMessageBox(e.Result.ToString());
                        });
                    };

                    proxy.SendMailRESTAsync(Recipient,
                                            "(Email Subject) Issue Detail",
                                            "(Email Body)" + Issue.ProblemDescription);
                });
            }
                                                                         );
        }
Пример #55
0
        public static T GetInstance()
        {
            T      local          = default(T);
            Type   type           = typeof(T);
            string serviceAddress = GetServiceAddress(type.Name.Replace("Client", ""));

            if (string.IsNullOrEmpty(serviceAddress))
            {
                return(default(T));
            }
            object[] parameters = new object[2];
            System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None)
            {
                MaxBufferSize          = 0x7fffffff,
                MaxReceivedMessageSize = 0x7fffffffL,
                SendTimeout            = new TimeSpan(0, 5, 0),
                ReceiveTimeout         = new TimeSpan(0, 5, 0),
                OpenTimeout            = new TimeSpan(0, 1, 0),
                CloseTimeout           = new TimeSpan(0, 1, 0)
            };
            System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress(new Uri(serviceAddress, UriKind.Absolute), new System.ServiceModel.Channels.AddressHeader[0]);
            parameters[0] = binding;
            parameters[1] = address;
            ConstructorInfo constructor = null;

            try
            {
                Type[] types = new Type[] { typeof(System.ServiceModel.Channels.Binding), typeof(System.ServiceModel.EndpointAddress) };
                constructor = typeof(T).GetConstructor(types);
            }
            catch (Exception)
            {
                return(default(T));
            }
            if (constructor != null)
            {
                local = (T)constructor.Invoke(parameters);
            }
            return(local);
        }
Пример #56
0
        public UserStore()
        {
            var binding = new System.ServiceModel.BasicHttpBinding();

            binding.Name = "BasicHttpBinding_IUserService";
            //binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            //binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
            binding.TransferMode           = TransferMode.Streamed;
            binding.MaxBufferPoolSize      = int.MaxValue;
            binding.MaxBufferSize          = int.MaxValue;
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.ReceiveTimeout         = TimeSpan.MaxValue;
            binding.OpenTimeout            = TimeSpan.MaxValue;
            binding.SendTimeout            = TimeSpan.MaxValue;



            var endpoint = new EndpointAddress("http://localhost:8081/user/");
            var factory  = new ChannelFactory <IUserService>(binding, endpoint);

            _userservice = factory.CreateChannel();
        }
        /// <summary>
        /// 设置BasicHttpBinding对象的配置信息
        /// </summary>
        /// <param name="BINDING">BasicHttpBinding对象</param>
        /// <param name="bindingName">bindingName</param>
        public static void ReadBindingConfig(System.ServiceModel.BasicHttpBinding BINDING, string bindingName)
        {
            XmlDocument xml = new XmlDocument();

            xml.Load(SoapClientConfig.ConfigFile);

            string  xpath;
            XmlNode node;

            xpath = "configuration/system.serviceModel/bindings/basicHttpBinding/binding[@name='" + bindingName + "']";
            node  = xml.SelectSingleNode(xpath);

            BINDING.MaxBufferSize          = Int32.Parse(node.Attributes["maxBufferSize"].Value);
            BINDING.MaxBufferPoolSize      = Int32.Parse(node.Attributes["maxBufferPoolSize"].Value);
            BINDING.MaxReceivedMessageSize = Int32.Parse(node.Attributes["maxReceivedMessageSize"].Value);

            xpath = "configuration/system.serviceModel/bindings/basicHttpBinding/binding[@name='" + bindingName + "']/readerQuotas";
            node  = xml.SelectSingleNode(xpath);
            BINDING.ReaderQuotas.MaxDepth = Int32.Parse(node.Attributes["maxDepth"].Value);
            BINDING.ReaderQuotas.MaxStringContentLength = Int32.Parse(node.Attributes["maxStringContentLength"].Value);
            BINDING.ReaderQuotas.MaxArrayLength         = Int32.Parse(node.Attributes["maxArrayLength"].Value);
            BINDING.ReaderQuotas.MaxBytesPerRead        = Int32.Parse(node.Attributes["maxBytesPerRead"].Value);
            BINDING.ReaderQuotas.MaxNameTableCharCount  = Int32.Parse(node.Attributes["maxNameTableCharCount"].Value);
        }
Пример #58
0
        private static BlogServiceClient CreateBlogServiceClient()
        {
            BlogServiceClient blogServiceClient = null;

            System.ServiceModel.BasicHttpBinding basicHttpbinding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.None);
            basicHttpbinding.Name = "BasicHttpBinding_IBlogService";
            basicHttpbinding.MaxReceivedMessageSize = 2147483646;
            basicHttpbinding.MaxBufferSize          = 2147483646;
            basicHttpbinding.MaxBufferPoolSize      = 2147483646;

            basicHttpbinding.ReaderQuotas.MaxArrayLength         = 2147483646;
            basicHttpbinding.ReaderQuotas.MaxStringContentLength = 5242880;
            basicHttpbinding.SendTimeout  = new TimeSpan(0, 5, 0);
            basicHttpbinding.CloseTimeout = new TimeSpan(0, 5, 0);

            basicHttpbinding.Security.Mode = BasicHttpSecurityMode.None;
            basicHttpbinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

            System.ServiceModel.EndpointAddress endpointAddress = new System.ServiceModel.EndpointAddress(hostURI);

            blogServiceClient = new BlogServiceClient(basicHttpbinding, endpointAddress);

            return(blogServiceClient);
        }
Пример #59
0
        public SurveyManagerServiceV3.ManagerServiceV3Client GetClient()
        {
            SurveyManagerServiceV3.ManagerServiceV3Client client;
            Configuration config = Configuration.GetNewInstance();

            if (config.Settings.WebServiceAuthMode == 1) // Windows Authentication
            {
                System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
                binding.Name                   = "BasicHttpBinding";
                binding.CloseTimeout           = new TimeSpan(0, 1, 0);
                binding.OpenTimeout            = new TimeSpan(0, 1, 0);
                binding.ReceiveTimeout         = new TimeSpan(0, 10, 0);
                binding.SendTimeout            = new TimeSpan(0, 1, 0);
                binding.AllowCookies           = false;
                binding.BypassProxyOnLocal     = false;
                binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
                binding.MaxBufferPoolSize      = config.Settings.WebServiceMaxBufferPoolSize;
                binding.MaxReceivedMessageSize = config.Settings.WebServiceMaxReceivedMessageSize;
                binding.MessageEncoding        = System.ServiceModel.WSMessageEncoding.Text;
                binding.TextEncoding           = System.Text.Encoding.UTF8;
                binding.TransferMode           = System.ServiceModel.TransferMode.Buffered;
                binding.UseDefaultWebProxy     = true;
                binding.ReaderQuotas.MaxDepth  = config.Settings.WebServiceReaderMaxDepth;
                binding.ReaderQuotas.MaxStringContentLength = config.Settings.WebServiceReaderMaxStringContentLength;
                binding.ReaderQuotas.MaxArrayLength         = config.Settings.WebServiceReaderMaxArrayLength;
                binding.ReaderQuotas.MaxBytesPerRead        = config.Settings.WebServiceReaderMaxBytesPerRead;
                binding.ReaderQuotas.MaxNameTableCharCount  = config.Settings.WebServiceReaderMaxNameTableCharCount;

                binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
                binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                binding.Security.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
                binding.Security.Transport.Realm = string.Empty;

                binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;

                System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(config.Settings.WebServiceEndpointAddress);

                client = new SurveyManagerServiceV3.ManagerServiceV3Client(binding, endpoint);

                client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                client.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                if (config.Settings.WebServiceBindingMode.Equals("wshttp", StringComparison.OrdinalIgnoreCase))
                {
                    System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();
                    binding.Name                   = "WSHttpBinding";
                    binding.CloseTimeout           = new TimeSpan(0, 1, 0);
                    binding.OpenTimeout            = new TimeSpan(0, 1, 0);
                    binding.ReceiveTimeout         = new TimeSpan(0, 10, 0);
                    binding.SendTimeout            = new TimeSpan(0, 1, 0);
                    binding.BypassProxyOnLocal     = false;
                    binding.TransactionFlow        = false;
                    binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
                    binding.MaxBufferPoolSize      = config.Settings.WebServiceMaxBufferPoolSize;
                    binding.MaxReceivedMessageSize = config.Settings.WebServiceMaxReceivedMessageSize;
                    binding.MessageEncoding        = System.ServiceModel.WSMessageEncoding.Text;
                    binding.TextEncoding           = System.Text.Encoding.UTF8;
                    binding.UseDefaultWebProxy     = true;
                    binding.AllowCookies           = false;

                    binding.ReaderQuotas.MaxDepth = config.Settings.WebServiceReaderMaxDepth;
                    binding.ReaderQuotas.MaxStringContentLength = config.Settings.WebServiceReaderMaxStringContentLength;
                    binding.ReaderQuotas.MaxArrayLength         = config.Settings.WebServiceReaderMaxArrayLength;
                    binding.ReaderQuotas.MaxBytesPerRead        = config.Settings.WebServiceReaderMaxBytesPerRead;
                    binding.ReaderQuotas.MaxNameTableCharCount  = config.Settings.WebServiceReaderMaxNameTableCharCount;

                    binding.ReliableSession.Ordered           = true;
                    binding.ReliableSession.InactivityTimeout = new TimeSpan(0, 10, 0);
                    binding.ReliableSession.Enabled           = false;

                    binding.Security.Mode = System.ServiceModel.SecurityMode.Message;
                    binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                    binding.Security.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
                    binding.Security.Transport.Realm = string.Empty;
                    binding.Security.Message.ClientCredentialType       = System.ServiceModel.MessageCredentialType.Windows;
                    binding.Security.Message.NegotiateServiceCredential = true;

                    System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(config.Settings.WebServiceEndpointAddress);

                    client = new SurveyManagerServiceV3.ManagerServiceV3Client(binding, endpoint);
                }
                else
                {
                    System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
                    binding.Name                   = "BasicHttpBinding";
                    binding.CloseTimeout           = new TimeSpan(0, 1, 0);
                    binding.OpenTimeout            = new TimeSpan(0, 1, 0);
                    binding.ReceiveTimeout         = new TimeSpan(0, 10, 0);
                    binding.SendTimeout            = new TimeSpan(0, 1, 0);
                    binding.AllowCookies           = false;
                    binding.BypassProxyOnLocal     = false;
                    binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
                    binding.MaxBufferPoolSize      = config.Settings.WebServiceMaxBufferPoolSize;
                    binding.MaxReceivedMessageSize = config.Settings.WebServiceMaxReceivedMessageSize;
                    binding.MessageEncoding        = System.ServiceModel.WSMessageEncoding.Text;
                    binding.TextEncoding           = System.Text.Encoding.UTF8;
                    binding.TransferMode           = System.ServiceModel.TransferMode.Buffered;
                    binding.UseDefaultWebProxy     = true;
                    binding.ReaderQuotas.MaxDepth  = config.Settings.WebServiceReaderMaxDepth;
                    binding.ReaderQuotas.MaxStringContentLength = config.Settings.WebServiceReaderMaxStringContentLength;
                    binding.ReaderQuotas.MaxArrayLength         = config.Settings.WebServiceReaderMaxArrayLength;
                    binding.ReaderQuotas.MaxBytesPerRead        = config.Settings.WebServiceReaderMaxBytesPerRead;
                    binding.ReaderQuotas.MaxNameTableCharCount  = config.Settings.WebServiceReaderMaxNameTableCharCount;


                    binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
                    binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                    binding.Security.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
                    binding.Security.Transport.Realm = string.Empty;

                    System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(config.Settings.WebServiceEndpointAddress);

                    client = new SurveyManagerServiceV3.ManagerServiceV3Client(binding, endpoint);
                }
            }

            return(client);
        }
        public static EWEManagerService.EWEManagerServiceClient GetClient(string pEndPointAddress, bool pIsAuthenticated, bool pIsWsHttpBinding = true)
        {
            EWEManagerService.EWEManagerServiceClient result = null;
            try
            {
                if (pIsAuthenticated) // Windows Authentication
                {
                    System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
                    binding.Name                   = "BasicHttpBinding";
                    binding.CloseTimeout           = new TimeSpan(0, 1, 0);
                    binding.OpenTimeout            = new TimeSpan(0, 1, 0);
                    binding.ReceiveTimeout         = new TimeSpan(0, 10, 0);
                    binding.SendTimeout            = new TimeSpan(0, 1, 0);
                    binding.AllowCookies           = false;
                    binding.BypassProxyOnLocal     = false;
                    binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
                    binding.MaxBufferPoolSize      = long.Parse(ConfigurationManager.AppSettings["MaxBufferPoolSize"]);//524288;
                    binding.MaxReceivedMessageSize = long.Parse(ConfigurationManager.AppSettings["MaxReceivedMessageSize"]);
                    binding.MessageEncoding        = System.ServiceModel.WSMessageEncoding.Text;
                    binding.TextEncoding           = System.Text.Encoding.UTF8;
                    binding.TransferMode           = System.ServiceModel.TransferMode.Buffered;
                    binding.UseDefaultWebProxy     = true;
                    binding.ReaderQuotas.MaxDepth  = int.Parse(ConfigurationManager.AppSettings["MaxDepth"]);                            //32;
                    binding.ReaderQuotas.MaxStringContentLength = int.Parse(ConfigurationManager.AppSettings["MaxStringContentLength"]); //8192;
                    binding.ReaderQuotas.MaxArrayLength         = int.Parse(ConfigurationManager.AppSettings["MaxArrayLength"]);         //16384;
                    binding.ReaderQuotas.MaxBytesPerRead        = int.Parse(ConfigurationManager.AppSettings["MaxBytesPerRead"]);        //4096;
                    binding.ReaderQuotas.MaxNameTableCharCount  = int.Parse(ConfigurationManager.AppSettings["MaxNameTableCharCount"]);  //16384;

                    binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
                    binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                    binding.Security.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
                    binding.Security.Transport.Realm = string.Empty;

                    binding.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;

                    System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(pEndPointAddress);

                    result = new EWEManagerService.EWEManagerServiceClient(binding, endpoint);
                    result.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                    result.ChannelFactory.Credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    if (pIsWsHttpBinding)
                    {
                        System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();
                        binding.Name                   = "WSHttpBinding";
                        binding.CloseTimeout           = new TimeSpan(0, 1, 0);
                        binding.OpenTimeout            = new TimeSpan(0, 1, 0);
                        binding.ReceiveTimeout         = new TimeSpan(0, 10, 0);
                        binding.SendTimeout            = new TimeSpan(0, 1, 0);
                        binding.BypassProxyOnLocal     = false;
                        binding.TransactionFlow        = false;
                        binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
                        binding.MaxBufferPoolSize      = long.Parse(ConfigurationManager.AppSettings["MaxBufferPoolSize"]);//524288;
                        binding.MaxReceivedMessageSize = long.Parse(ConfigurationManager.AppSettings["MaxReceivedMessageSize"]);
                        binding.MessageEncoding        = System.ServiceModel.WSMessageEncoding.Text;
                        binding.TextEncoding           = System.Text.Encoding.UTF8;
                        binding.UseDefaultWebProxy     = true;
                        binding.AllowCookies           = false;

                        binding.ReaderQuotas.MaxDepth = int.Parse(ConfigurationManager.AppSettings["MaxDepth"]);                             //32;
                        binding.ReaderQuotas.MaxStringContentLength = int.Parse(ConfigurationManager.AppSettings["MaxStringContentLength"]); //8192;
                        binding.ReaderQuotas.MaxArrayLength         = int.Parse(ConfigurationManager.AppSettings["MaxArrayLength"]);         //16384;
                        binding.ReaderQuotas.MaxBytesPerRead        = int.Parse(ConfigurationManager.AppSettings["MaxBytesPerRead"]);        //4096;
                        binding.ReaderQuotas.MaxNameTableCharCount  = int.Parse(ConfigurationManager.AppSettings["MaxNameTableCharCount"]);  //16384;

                        binding.ReliableSession.Ordered           = true;
                        binding.ReliableSession.InactivityTimeout = new TimeSpan(0, 10, 0);
                        binding.ReliableSession.Enabled           = false;

                        binding.Security.Mode = System.ServiceModel.SecurityMode.Message;
                        binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                        binding.Security.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
                        binding.Security.Transport.Realm = string.Empty;
                        binding.Security.Message.ClientCredentialType       = System.ServiceModel.MessageCredentialType.Windows;
                        binding.Security.Message.NegotiateServiceCredential = true;

                        System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(pEndPointAddress);

                        result = new EWEManagerService.EWEManagerServiceClient(binding, endpoint);
                    }
                    else
                    {
                        System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();
                        binding.Name                   = "BasicHttpBinding";
                        binding.CloseTimeout           = new TimeSpan(0, 1, 0);
                        binding.OpenTimeout            = new TimeSpan(0, 1, 0);
                        binding.ReceiveTimeout         = new TimeSpan(0, 10, 0);
                        binding.SendTimeout            = new TimeSpan(0, 1, 0);
                        binding.AllowCookies           = false;
                        binding.BypassProxyOnLocal     = false;
                        binding.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
                        binding.MaxBufferPoolSize      = long.Parse(ConfigurationManager.AppSettings["MaxBufferPoolSize"]);//524288;
                        binding.MaxReceivedMessageSize = long.Parse(ConfigurationManager.AppSettings["MaxReceivedMessageSize"]);
                        binding.MessageEncoding        = System.ServiceModel.WSMessageEncoding.Text;
                        binding.TextEncoding           = System.Text.Encoding.UTF8;
                        binding.TransferMode           = System.ServiceModel.TransferMode.Buffered;
                        binding.UseDefaultWebProxy     = true;
                        binding.ReaderQuotas.MaxDepth  = int.Parse(ConfigurationManager.AppSettings["MaxDepth"]);                            //32;
                        binding.ReaderQuotas.MaxStringContentLength = int.Parse(ConfigurationManager.AppSettings["MaxStringContentLength"]); //8192;
                        binding.ReaderQuotas.MaxArrayLength         = int.Parse(ConfigurationManager.AppSettings["MaxArrayLength"]);         //16384;
                        binding.ReaderQuotas.MaxBytesPerRead        = int.Parse(ConfigurationManager.AppSettings["MaxBytesPerRead"]);        //4096;
                        binding.ReaderQuotas.MaxNameTableCharCount  = int.Parse(ConfigurationManager.AppSettings["MaxNameTableCharCount"]);  //16384;

                        binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
                        binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                        binding.Security.Transport.ProxyCredentialType  = System.ServiceModel.HttpProxyCredentialType.None;
                        binding.Security.Transport.Realm = string.Empty;

                        System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(pEndPointAddress);

                        result = new EWEManagerService.EWEManagerServiceClient(binding, endpoint);
                    }
                }
            }
            catch (FaultException <CustomFaultException> cfe)
            {
                throw cfe;
            }
            catch (FaultException fe)
            {
                throw fe;
            }
            catch (SecurityNegotiationException sne)
            {
                throw sne;
            }
            catch (CommunicationException ce)
            {
                throw ce;
            }
            catch (TimeoutException te)
            {
                throw te;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }