public void GetValueMissing()
        {
            CustomBinding binding = new CustomBinding("p1");

            HttpActionContext ctx = new HttpActionContext();

            var result = binding.GetValue(ctx);

            Assert.Null(result);
        }
Exemple #2
0
		public void CustomBindingThrowsInvalidCast ()
		{
			var target = new Rectangle ();
			var property = Rectangle.WidthProperty;
			var binding = new CustomBinding ();

			Assert.Throws<InvalidCastException> (() =>
				BindingOperations.SetBinding (target, property, binding)
			, "#1");
		}
        public void GetValue_Returns_Set()
        {
            CustomBinding binding = new CustomBinding("p1");

            HttpActionContext ctx = new HttpActionContext();

            // Act
            object result = "abc";
            binding.SetValue(ctx, result);
            var result2 = binding.GetValue(ctx);

            // Assert
            Assert.Same(result, result2);
        }
        public void Set_Modifies_Dictionary()
        {
            string name = "p1";
            CustomBinding binding = new CustomBinding(name);

            HttpActionContext ctx = new HttpActionContext();

            // Act
            object result = "abc";
            binding.SetValue(ctx, result);
            var result2 = ctx.ActionArguments[name];

            // Assert
            Assert.Same(result, result2);
        }
        public void Can_Set_Null()
        {
            // It's legal to set a parameter to null. Test against spurious null checks.
            CustomBinding binding = new CustomBinding("p1");

            HttpActionContext ctx = new HttpActionContext();

            // Act            
            binding.SetValue(ctx, null);

            var resultFinal = binding.GetValue(ctx);

            // Assert
            Assert.Null(resultFinal);
        }
        public void Call_Set_Multiple_Times()
        {
            // Make sure a binding can set the argument multiple times and that we get the latest. 
            // This is interesting with composite bindings that chain to an inner binding. 
            CustomBinding binding = new CustomBinding("p1");

            HttpActionContext ctx = new HttpActionContext();

            // Act
            object result1 = "abc";
            binding.SetValue(ctx, result1);

            object result2 = 123;
            binding.SetValue(ctx, result2);

            var resultFinal = binding.GetValue(ctx);

            // Assert
            Assert.Same(result2, resultFinal);
        }
Exemple #7
0
        public static eHtalkMessage GetResponseSync(eHtalkMessage msg, X509Certificate2 extInterfaCertificate, string esbEndpoint, string relyingParty, string identityProviderURL, X509Certificate2 userCertificate, string wsaddressingTo, Stopwatch stopw)
        {
#if !CC
            IssuedSecurityTokenProvider provider = new IssuedSecurityTokenProvider();
            provider.SecurityTokenSerializer = new WSSecurityTokenSerializer();
            provider.TargetAddress           = new EndpointAddress(new Uri(relyingParty), new AddressHeader[0]);
            provider.IssuerAddress           = new EndpointAddress(new Uri(identityProviderURL), new AddressHeader[0]);
            provider.SecurityAlgorithmSuite  = SecurityAlgorithmSuite.Basic256;
            provider.MessageSecurityVersion  = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
            ClientCredentials credentials = new ClientCredentials
            {
                ClientCertificate = { Certificate = userCertificate }
            };
            provider.IssuerChannelBehaviors.Add(credentials);

            HttpsTransportBindingElement tbe = new HttpsTransportBindingElement
            {
                AuthenticationScheme     = AuthenticationSchemes.Digest,
                RequireClientCertificate = true,
                KeepAliveEnabled         = false
            };
            CustomBinding stsBinding = new CustomBinding(new BindingElement[] { tbe });
            provider.IssuerBinding = stsBinding;

            provider.Open();
            var token = provider.GetToken(TimeSpan.FromSeconds(30.0)) as GenericXmlSecurityToken;
#endif
#if CC
            var cc    = new EhealthCryptoController();
            var token = cc.GetSamlTokenForHealthProfessional(relyingParty);
#endif
            if (token == null)
            {
                throw new ApplicationException("No AT token received");
            }
            Console.WriteLine(string.Format("Ziskany AT token in {0}", stopw.ElapsedMilliseconds));



            CustomBinding          binding = new CustomBinding();
            SecurityBindingElement sbe     = SecurityBindingElement.CreateIssuedTokenForCertificateBindingElement(new IssuedSecurityTokenParameters()
            {
                RequireDerivedKeys = true, KeyType = SecurityKeyType.SymmetricKey
            });

            sbe.MessageSecurityVersion =
                MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
            sbe.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
            sbe.IncludeTimestamp     = true;
            //sbe.AllowInsecureTransport = true;
            sbe.SetKeyDerivation(true);
            sbe.KeyEntropyMode = SecurityKeyEntropyMode.ClientEntropy;
            binding.Elements.Add(sbe);
            binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, System.Text.Encoding.UTF8));
            binding.Elements.Add(new HttpsTransportBindingElement()
            {
                RequireClientCertificate = true, KeepAliveEnabled = true
            });
            var regEx          = new Regex(@"https?://([^/]+)");
            var dnsIdentity    = regEx.Match(wsaddressingTo).Groups[1].Captures[0].Value;
            var channelFactory = new ChannelFactory <IeHealthSyncService>(binding,
                                                                          new EndpointAddress(
                                                                              new Uri(wsaddressingTo),
                                                                              new DnsEndpointIdentity(dnsIdentity),
                                                                              new AddressHeader[] { }));
            channelFactory.Credentials.SupportInteractive                    = false;
            channelFactory.Credentials.ClientCertificate.Certificate         = userCertificate;
            channelFactory.Credentials.ServiceCertificate.DefaultCertificate = extInterfaCertificate;

            channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode =
                X509CertificateValidationMode.None;
            channelFactory.ConfigureChannelFactory <IeHealthSyncService>();
            channelFactory.Endpoint.Behaviors.Add(new ClientViaBehavior(new Uri(esbEndpoint)));
            var channel = channelFactory.CreateChannelWithIssuedToken(token);
            Console.WriteLine(string.Format("vytvoreny kanal: {0}", stopw.ElapsedMilliseconds));
            var stopw1 = new Stopwatch();

            eHtalkMessage data = null;
            int           wait = 1;
            for (int i = 0; i < 20; i++)
            {
                stopw1.Reset();
                stopw1.Start();
                msg.Header.MessageInfo.MessageID = Guid.NewGuid().ToString("D");
                Debug.WriteLine("Start calling", "MyCustom");
                try
                {
                    data = channel.GetData(msg);
                }
                catch (CommunicationException ex)
                {
                    data = channel.GetData(msg);
                }
                Console.WriteLine(string.Format("po {1} sekundach: {0}", stopw1.ElapsedMilliseconds, wait));
                Thread.Sleep(wait * 1000);
                wait = wait * 2;
            }

            return(data);
        }
        private void Send(NLogEvents events, IEnumerable <AsyncLogEventInfo> asyncContinuations)
        {
            if (!this.OnSend(events, asyncContinuations))
            {
                return;
            }

#if WCF_SUPPORTED
            WcfLogReceiverClient client;

            if (string.IsNullOrEmpty(this.EndpointConfigurationName))
            {
                // endpoint not specified - use BasicHttpBinding
                Binding binding;

#if !SILVERLIGHT2
                if (this.UseBinaryEncoding)
                {
                    binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
                }
                else
#endif
                {
                    binding = new BasicHttpBinding();
                }

                client = new WcfLogReceiverClient(binding, new EndpointAddress(this.EndpointAddress));
            }
            else
            {
                client = new WcfLogReceiverClient(this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress));
            }

            client.ProcessLogMessagesCompleted += (sender, e) =>
            {
                // report error to the callers
                foreach (var ev in asyncContinuations)
                {
                    ev.Continuation(e.Error);
                }

                // send any buffered events
                this.SendBufferedEvents();
            };

            this.inCall = true;
#if SILVERLIGHT
            if (!Deployment.Current.Dispatcher.CheckAccess())
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
            }
            else
            {
                client.ProcessLogMessagesAsync(events);
            }
#else
            client.ProcessLogMessagesAsync(events);
#endif
#else
            var client = new SoapLogReceiverClient(this.EndpointAddress);
            this.inCall = true;
            client.BeginProcessLogMessages(
                events,
                result =>
            {
                Exception exception = null;

                try
                {
                    client.EndProcessLogMessages(result);
                }
                catch (Exception ex)
                {
                    if (ex.MustBeRethrown())
                    {
                        throw;
                    }

                    exception = ex;
                }

                // report error to the callers
                foreach (var ev in asyncContinuations)
                {
                    ev.Continuation(exception);
                }

                // send any buffered events
                this.SendBufferedEvents();
            },
                null);
#endif
        }
Exemple #9
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="requestMessage">RequestMessage object containing the request.</param>
        /// <returns>ReplyMessage containing the reply.</returns>
        public static ReplyMessage RunTransaction(
            Configuration config, RequestMessage requestMessage)
        {
            Logger logger = null;
            TransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, requestMessage);
                SetVersionInformation(requestMessage);
                logger = PrepareLog(config);
                SetConnectionLimit(config);


                CustomBinding currentBinding = getWCFCustomBinding();


                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new TransactionProcessorClient(currentBinding, endpointAddress)){
                    //Set protection level to sign only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;

                    //add certificate credentials
                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = new X509Certificate2Collection();
                    collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    foreach (X509Certificate2 cert1 in collection)
                    {
                        if (cert1.Subject.Contains(config.MerchantID))
                        {
                            proc.ClientCredentials.ClientCertificate.Certificate         = cert1;
                            proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert1;
                            break;
                        }
                    }

                    // send request now
                    // Changes for NGT-3035
                    XmlNode req = SerializeObjectToXmlNode(requestMessage);
                    if (logger != null)
                    {
                        logger.LogRequest(req, config.Demo);
                    }

                    ReplyMessage reply = proc.runTransaction(requestMessage);
                    XmlNode      rep   = SerializeObjectToXmlNode(reply);
                    if (logger != null)
                    {
                        logger.LogReply(rep, config.Demo);
                    }

                    return(reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Exemple #10
0
        protected override void OnStart(string[] args)
        {
            string logfile = Properties.Settings.Default.Log;

            TextWriterTraceListener[] listeners = new TextWriterTraceListener[] {
                new TextWriterTraceListener(logfile),
                new TextWriterTraceListener(Console.Out)
            };
            Debug.AutoFlush = true;

            Debug.Listeners.AddRange(listeners);

            try
            {
                Lookups.connection = new TSocketConnection(IMBModelName, IMBModelID, "", IMBHub);
                Lookups.connection.onDisconnect += handle_disconnect;
                Lookups.connection.onException  += handle_exception;
                var baseAddresses = new List <Uri>();
                foreach (var url in WebSocketUrl.Split('|'))
                {
                    baseAddresses.Add(new Uri(url));
                }
                Lookups.host = new ServiceHost(typeof(WebSocketsServer), baseAddresses.ToArray());

                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                Lookups.host.Description.Behaviors.Add(smb);

                CustomBinding binding = new CustomBinding();
                // http://www.rauch.io/2015/06/25/all-wcf-timeouts-explained/
                // https://msdn.microsoft.com/en-us/library/hh924831(v=vs.110).aspx
                binding.ReceiveTimeout = new TimeSpan(3, 0, 0);
                binding.SendTimeout    = new TimeSpan(3, 0, 0);
                binding.Elements.Add(new ByteStreamMessageEncodingBindingElement());

                HttpTransportBindingElement transport = new HttpTransportBindingElement();
                transport.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;
                transport.WebSocketSettings.CreateNotificationOnConnection = true;
                transport.WebSocketSettings.KeepAliveInterval = new TimeSpan(3, 0, 0);
                transport.KeepAliveEnabled = true; // default true?
                binding.Elements.Add(transport);

                var endPoint = Lookups.host.AddServiceEndpoint(typeof(IWebSocketsServer), binding, "");
                endPoint.EndpointBehaviors.Add(new ClientTrackerEndpointBehavior());

                try
                {
                    CustomBinding bindingSSL = new CustomBinding();
                    // http://www.rauch.io/2015/06/25/all-wcf-timeouts-explained/
                    // https://msdn.microsoft.com/en-us/library/hh924831(v=vs.110).aspx
                    bindingSSL.ReceiveTimeout = new TimeSpan(3, 0, 0);
                    bindingSSL.SendTimeout    = new TimeSpan(3, 0, 0);
                    bindingSSL.Elements.Add(new ByteStreamMessageEncodingBindingElement());

                    HttpsTransportBindingElement transportSSL = new HttpsTransportBindingElement();
                    transportSSL.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;
                    transportSSL.WebSocketSettings.CreateNotificationOnConnection = true;
                    transportSSL.WebSocketSettings.KeepAliveInterval = new TimeSpan(3, 0, 0);
                    transportSSL.KeepAliveEnabled = true;
                    bindingSSL.Elements.Add(transportSSL);

                    var endPointSSL = Lookups.host.AddServiceEndpoint(typeof(IWebSocketsServer), bindingSSL, "");
                    endPointSSL.EndpointBehaviors.Add(new ClientTrackerEndpointBehavior());
                }
                catch (Exception e)
                {
                    Debug.WriteLine(DateTime.Now + ": >> Could not bind SSL endpoint: " + e.Message);
                }


                Lookups.host.Open();
                //var dispatcher = Lookups.host.ChannelDispatchers[0] as ChannelDispatcher;
                Debug.WriteLine(DateTime.Now + ": Started WS2IMB service");
            }
            catch (Exception e)
            {
                Debug.WriteLine(DateTime.Now + ": ## Exception Starting WS2IMB service: " + e.Message);
            }
        }
Exemple #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ip_address_or_host_name"></param>
        /// <param name="binding_name">wcf 바인딩 명칭 (ex)net.tcp</param>
        /// <param name="service_port">wcf접속시 연결 할 port번호</param>
        public void Start(string ip_address_or_host_name, string binding_name, int service_port)
        {
            lock (SyncRoot)
            {
                Binding _binding;
                var     _address = String.Format("://{0}:{1}/{2}", ip_address_or_host_name, service_port, ServiceName);

                if (binding_name.ToLower() == "WSHttpBinding".ToLower())
                {
                    _address = "http" + _address;

                    WSHttpBinding _binding2 = new WSHttpBinding();
                    {
                        _binding2.TransactionFlow = false;

                        _binding2.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                        _binding2.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;
                        _binding2.Security.Mode = SecurityMode.None;

                        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        _binding2.MaxBufferPoolSize      *= MaxBufferPoolSize;

                        _binding2.ReaderQuotas = ReaderQuotas;
                    }

                    _binding = _binding2;
                }
                else if (binding_name.ToLower() == "WSDualHttpBinding".ToLower())
                {
                    _address = "http" + _address;

                    WSDualHttpBinding _binding2 = new WSDualHttpBinding();
                    {
                        _binding2.TransactionFlow = false;

                        _binding2.Security.Message.ClientCredentialType = MessageCredentialType.None;
                        _binding2.Security.Mode = WSDualHttpSecurityMode.None;

                        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        _binding2.MaxBufferPoolSize      *= MaxBufferPoolSize;

                        _binding2.ReaderQuotas = ReaderQuotas;
                    }

                    _binding = _binding2;
                }
                else if (binding_name.ToLower() == "NetMsmqBinding".ToLower())
                {
                    _address = String.Format("net.msmq://{0}/private/{1}", ip_address_or_host_name, ServiceName);

                    NetMsmqBinding _binding2 = new NetMsmqBinding();
                    {
                        _binding2.Security.Transport.MsmqAuthenticationMode = MsmqAuthenticationMode.None;
                        _binding2.Security.Transport.MsmqProtectionLevel    = System.Net.Security.ProtectionLevel.None;

                        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        _binding2.MaxBufferPoolSize      *= MaxBufferPoolSize;

                        _binding2.SendTimeout    = SendTimeout;
                        _binding2.ReceiveTimeout = ReceiveTimeout;

                        _binding2.ReaderQuotas = ReaderQuotas;
                    }

                    _binding = _binding2;
                }
                else if (binding_name.ToLower() == "NetNamedPipeBinding".ToLower())
                {
                    _address = "net.pipe" + _address;

                    NetNamedPipeBinding _binding2 = new NetNamedPipeBinding();
                    {
                        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        _binding2.MaxBufferPoolSize      *= MaxBufferPoolSize;

                        _binding2.SendTimeout    = SendTimeout;
                        _binding2.ReceiveTimeout = ReceiveTimeout;

                        _binding2.ReaderQuotas = ReaderQuotas;
                    }

                    _binding = _binding2;
                }
                //else if (_binding_name.ToLower() == "NetPeerTcpBinding".ToLower())
                //{
                //    _address = "net.peer" + _address;

                //    NetPeerTcpBinding _binding2 = new NetPeerTcpBinding();
                //    {
                //        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                //        _binding2.MaxBufferPoolSize *= MaxBufferPoolSize;

                //        _binding2.SendTimeout = SendTimeout;
                //        _binding2.ReceiveTimeout = ReceiveTimeout;

                //        _binding2.ReaderQuotas = ReaderQuotas;
                //    }

                //    _binding = _binding2;
                //}
                else if (binding_name.ToLower() == "net.tcp".ToLower())
                {
                    if (IsPortSharing == true)
                    {
                        service_port = SharingPort;
                    }

                    _address = String.Format("net.tcp://{0}:{1}/{2}", ip_address_or_host_name, service_port, ServiceName);

                    NetTcpBinding _binding2 = new NetTcpBinding();
                    {
                        _binding2.Security.Mode = SecurityMode.None;

                        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        _binding2.MaxBufferPoolSize      *= MaxBufferPoolSize;

                        _binding2.SendTimeout    = SendTimeout;
                        _binding2.ReceiveTimeout = ReceiveTimeout;

                        _binding2.ReaderQuotas       = ReaderQuotas;
                        _binding2.PortSharingEnabled = IsPortSharing;
                    }

                    _binding = _binding2;
                }
                else if (binding_name.ToLower() == "BasicHttpBinding".ToLower())
                {
                    _address = "http" + _address;

                    BasicHttpBinding _binding2 = new BasicHttpBinding();
                    {
                        _binding2.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;

                        _binding2.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                        _binding2.Security.Mode = BasicHttpSecurityMode.None;

                        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        _binding2.MaxBufferPoolSize      *= MaxBufferPoolSize;

                        _binding2.ReaderQuotas = ReaderQuotas;
                    }

                    _binding = _binding2;
                }
                else if (binding_name.ToLower() == "WebHttpBinding".ToLower())
                {
                    _address = "http" + _address;

                    WebHttpBinding _binding2 = new WebHttpBinding();
                    {
                        _binding2.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;

                        _binding2.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                        _binding2.Security.Mode = WebHttpSecurityMode.None;

                        _binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        _binding2.MaxBufferPoolSize      *= MaxBufferPoolSize;

                        _binding2.ReaderQuotas = ReaderQuotas;
                    }

                    _binding = _binding2;
                }
                else
                {
                    _address = "http" + _address;

                    // Create a custom binding that contains two binding elements.
                    ReliableSessionBindingElement _reliableSession = new ReliableSessionBindingElement
                    {
                        InactivityTimeout = TimeSpan.FromDays(7),
                        Ordered           = true
                    };

                    HttpTransportBindingElement _httpTransport = new HttpTransportBindingElement
                    {
                        AuthenticationScheme   = System.Net.AuthenticationSchemes.Anonymous,
                        HostNameComparisonMode = HostNameComparisonMode.StrongWildcard
                    };

                    CustomBinding _binding2 = new CustomBinding(_reliableSession, _httpTransport);
                    {
                        //_binding2.MaxReceivedMessageSize *= MaxReceivedMessageSize;
                        //_binding2.MaxBufferPoolSize *= MaxBufferPoolSize;

                        _binding2.SendTimeout    = SendTimeout;
                        _binding2.ReceiveTimeout = ReceiveTimeout;

                        //_binding2.ReaderQuotas = ReaderQuotas;
                    }

                    _binding = _binding2;
                }

                this.WcfAddress += _address + " ";
                ServerHost.AddServiceEndpoint(InterfaceType, _binding, _address);
            }
        }
Exemple #12
0
        // FIXME: if the ServiceDescription has a base address (e.g. http://localhost:8080) and HttpGetUrl is empty, it returns UnknownDestination while it is expected to return the HTTP help page.
        internal void EnsureChannelDispatcher(bool isMex, string scheme, Uri uri, WCFBinding binding)
        {
            if (isMex)
            {
                instance.WsdlUrl = uri;
            }
            else
            {
                instance.HelpUrl = uri;
            }

            if (dispatchers == null)
            {
                dispatchers = new Dictionary <Uri, ChannelDispatcher> ();
            }
            else if (dispatchers.ContainsKey(uri))
            {
                return;                 // already exists (e.g. reached here for wsdl while help is already filled on the same URI.)
            }
            if (binding == null)
            {
                switch (scheme)
                {
                case "http":
                    binding = MetadataExchangeBindings.CreateMexHttpBinding();
                    break;

                case "https":
                    binding = MetadataExchangeBindings.CreateMexHttpsBinding();
                    break;

                case "net.tcp":
                    binding = MetadataExchangeBindings.CreateMexTcpBinding();
                    break;

                case "net.pipe":
                    binding = MetadataExchangeBindings.CreateMexNamedPipeBinding();
                    break;
                }
            }

            CustomBinding cb = new CustomBinding(binding)
            {
                Name = ServiceMetadataBehaviorHttpGetBinding
            };

            cb.Elements.Find <MessageEncodingBindingElement> ().MessageVersion = MessageVersion.None;

            ServiceEndpoint se = new ServiceEndpoint(ContractDescription.GetContract(typeof(IHttpGetHelpPageAndMetadataContract)), cb, new EndpointAddress(uri))
            {
                ListenUri = uri,
            };

            var channelDispatcher = new DispatcherBuilder(Owner).BuildChannelDispatcher(owner.Description.ServiceType, se, new BindingParameterCollection());

            channelDispatcher.MessageVersion = MessageVersion.None;             // it has no MessageVersion.
            channelDispatcher.IsMex          = true;
            channelDispatcher.Endpoints [0].DispatchRuntime.InstanceContextProvider = new SingletonInstanceContextProvider(new InstanceContext(owner, instance));

            dispatchers.Add(uri, channelDispatcher);
            owner.ChannelDispatchers.Add(channelDispatcher);
        }
Exemple #13
0
        private static List <Type> GetSupportedChannelTypes(StuffPerListenUriInfo stuff)
        {
            Binding       originalBinding = stuff.Endpoints[0].Binding;
            CustomBinding binding         = new CustomBinding(originalBinding);

            // All types are supported to start
            bool   reply                = true;
            bool   replySession         = true;
            bool   input                = true;
            bool   inputSession         = true;
            bool   duplex               = true;
            bool   duplexSession        = true;
            string sessionContractName  = null;
            string datagramContractName = null;

            // each endpoint adds constraints
            for (int i = 0; i < stuff.Endpoints.Count; ++i)
            {
                ContractDescription contract = stuff.Endpoints[i].Contract;
                if (contract.SessionMode == SessionMode.Required)
                {
                    sessionContractName = contract.Name;
                }
                if (contract.SessionMode == SessionMode.NotAllowed)
                {
                    datagramContractName = contract.Name;
                }

                System.Collections.IList endpointTypes = GetSupportedChannelTypes(contract);
                if (!endpointTypes.Contains(typeof(IReplyChannel)))
                {
                    reply = false;
                }
                if (!endpointTypes.Contains(typeof(IReplySessionChannel)))
                {
                    replySession = false;
                }
                if (!endpointTypes.Contains(typeof(IInputChannel)))
                {
                    input = false;
                }
                if (!endpointTypes.Contains(typeof(IInputSessionChannel)))
                {
                    inputSession = false;
                }
                if (!endpointTypes.Contains(typeof(IDuplexChannel)))
                {
                    duplex = false;
                }
                if (!endpointTypes.Contains(typeof(IDuplexSessionChannel)))
                {
                    duplexSession = false;
                }
            }

            if ((sessionContractName != null) && (datagramContractName != null))
            {
                string    text  = SR.Format(SR.SFxCannotRequireBothSessionAndDatagram3, datagramContractName, sessionContractName, binding.Name);
                Exception error = new InvalidOperationException(text);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
            }

            // TODO: Restrict list further based on SessionMode constraints

            var supportedChannelTypes = new List <Type>();

            if (input)
            {
                supportedChannelTypes.Add(typeof(IInputChannel));
            }
            if (inputSession)
            {
                supportedChannelTypes.Add(typeof(IInputSessionChannel));
            }
            if (reply)
            {
                supportedChannelTypes.Add(typeof(IReplyChannel));
            }
            if (replySession)
            {
                supportedChannelTypes.Add(typeof(IReplySessionChannel));
            }
            if (duplex)
            {
                supportedChannelTypes.Add(typeof(IDuplexChannel));
            }
            if (duplexSession)
            {
                supportedChannelTypes.Add(typeof(IDuplexSessionChannel));
            }

            return(supportedChannelTypes);
        }
    public static async Task MaxTransferWindowSizeApplied(ReliableMessagingVersion rmVersion, bool ordered, string endpointSuffix)
    {
        ChannelFactory <IWcfReliableService> factory = null;
        IWcfReliableService serviceProxy             = null;
        NetHttpBinding      binding    = null;
        string secondRequestHeaderName = "SecondRequest";

        try
        {
            // *** SETUP *** \\
            binding = new NetHttpBinding(BasicHttpSecurityMode.None, true);
            binding.ReliableSession.Ordered = ordered;
            var customBinding = new CustomBinding(binding);
            var reliableSessionBindingElement = customBinding.Elements.Find <ReliableSessionBindingElement>();
            reliableSessionBindingElement.MaxTransferWindowSize    = 1;
            reliableSessionBindingElement.ReliableMessagingVersion = rmVersion;
            factory = new ChannelFactory <IWcfReliableService>(customBinding, new EndpointAddress(Endpoints.ReliableSession_NetHttp + endpointSuffix));
            var  handlerFactoryBehavior = new HttpMessageHandlerBehavior();
            bool delayNextCall = false;
            bool secondRequestSent = false;
            TaskCompletionSource <object> tcs1 = null, tcs2 = new TaskCompletionSource <object>();
            handlerFactoryBehavior.OnSendingAsync = async(request, token) =>
            {
                if (request.Headers.Contains(secondRequestHeaderName))
                {
                    secondRequestSent = true;
                }

                // Once the delayNextCall latch is set, all subsequent calls will be on hold until tcs1 is completed.
                if (delayNextCall)
                {
                    if (tcs1 == null) // First delayed call
                    {
                        tcs1 = new TaskCompletionSource <object>();
                        tcs2.TrySetResult(null); // Signal main test code that first request has been attempted
                    }
                    // All calls will wait on the same TCS as trying to prevent requests progressing;
                    await tcs1.Task;
                }
                return(null);
            };
            factory.Endpoint.Behaviors.Add(handlerFactoryBehavior);
            serviceProxy = factory.CreateChannel();
            // *** EXECUTE *** \\
            ((IClientChannel)serviceProxy).Open(); // This will establish a reliable session
            delayNextCall = true;
            Stopwatch sw = Stopwatch.StartNew();
            var       resultTask1 = serviceProxy.GetNextNumberAsync();
            await tcs2.Task; // Wait for first http request to be attempted
            sw.Stop();
            Task <int> resultTask2;
            using (var scope = new OperationContextScope((IContextChannel)serviceProxy))
            {
                // Add marker to second request so we can check if it's been seen by handler
                var httpRequestMessageProperty = new HttpRequestMessageProperty();
                httpRequestMessageProperty.Headers.Add(secondRequestHeaderName, secondRequestHeaderName);
                OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequestMessageProperty);
                resultTask2 = serviceProxy.GetNextNumberAsync();
            }

            // Wait 6 times the amount of time it took for the first http request to be made to ensure we've allowed
            // enough time that the second request should have happened by now.
            await Task.Delay((int)sw.ElapsedMilliseconds * 6);

            var secondRequestBlocked = !secondRequestSent;
            tcs1.TrySetResult(null); // Release first request
            int result1 = await resultTask1;
            int result2 = await resultTask2;

            // *** VALIDATE *** \\
            Assert.Equal(1, result1);
            Assert.Equal(2, result2);
            Assert.True(secondRequestBlocked); // Captured before releasing the first request
            Assert.True(secondRequestSent);    // Validate that header was seen

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
        public static FNCEWS40PortTypeClient ConfigureBinding(String user, String domain, String password, String uri)
        {
            BindingElementCollection bec = new BindingElementCollection();

            // Everything gets treated as if it is username credentials until
            //  right at the point of serialization.
            TransportSecurityBindingElement sbe = SecurityBindingElement.CreateUserNameOverTransportBindingElement();

            sbe.IncludeTimestamp       = false;
            sbe.AllowInsecureTransport = true;
            bec.Add(sbe);

            if (uri.IndexOf("SOAP") != -1)
            {
                // using the SOAP endpoint
                TextMessageEncodingBindingElement tme = new TextMessageEncodingBindingElement();
                tme.MessageVersion        = MessageVersion.Soap11;
                tme.ReaderQuotas.MaxDepth = 1024;
                tme.ReaderQuotas.MaxStringContentLength = 1024 * 1024;
                bec.Add(tme);
            }
            else
            {
                MtomMessageEncodingBindingElement mme = new MtomMessageEncodingBindingElement();
                mme.MessageVersion        = MessageVersion.Soap12;
                mme.ReaderQuotas.MaxDepth = 1024;
                mme.ReaderQuotas.MaxStringContentLength = 1024 * 1024;
                mme.MaxBufferSize = 2147483647;
                bec.Add(mme);
            }

            if (uri.IndexOf("https") != -1)
            {
                HttpsTransportBindingElement tbe = new HttpsTransportBindingElement();
                tbe.MaxReceivedMessageSize = 2147483647;
                tbe.MaxBufferSize          = 2147483647;
                bec.Add(tbe);
            }
            else
            {
                HttpTransportBindingElement httptbe = new HttpTransportBindingElement();
                httptbe.MaxReceivedMessageSize = 2147483647;
                httptbe.MaxBufferSize          = 2147483647;
                bec.Add(httptbe);
            }

            CustomBinding binding = new CustomBinding(bec);

            binding.ReceiveTimeout = new TimeSpan(TimeSpan.TicksPerDay);    // 100 nanonsecond units, make it 1 day
            binding.SendTimeout    = binding.ReceiveTimeout;

            EndpointAddress endpoint = new EndpointAddress(uri);

            _port = new FNCEWS40PortTypeClient(binding, endpoint);

            _port.ClientCredentials.UserName.UserName = user;
            _port.ClientCredentials.UserName.Password = password;

            // set up the Localization header, minus the locale. We assume
            //  the timezone cannot change between calls, but that the locale
            //  may.
            _localization          = new Localization();
            _localization.Timezone = GetTimezone();

            return(_port);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            int           port   = 8000;
            SocketsServer server = new SocketsServer(port, new CalculatorService());

            server.StartServing();
            Console.WriteLine("Started the simple server");

            CustomBinding   binding = new CustomBinding(new SizedTcpTransportBindingElement());
            EndpointAddress address = new EndpointAddress(
                SizedTcpTransportBindingElement.SizedTcpScheme + "://localhost:" + port);
            ChannelFactory <IUntypedTest> factory = new ChannelFactory <IUntypedTest>(binding, address);
            IUntypedTest proxy = factory.CreateChannel();

            string[] allInputs = new string[]
            {
                "{\"method\":\"Add\",\"params\":[5, 8],\"id\":1}",
                "{\"method\":\"Multiply\",\"params\":[5, 8],\"id\":2}",
                "{\"method\":\"Divide\",\"params\":[5, 0],\"id\":3}",
            };

            foreach (string input in allInputs)
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                Console.WriteLine("Input: {0}", input);
                Message inputMessage  = Formatting.BytesToMessage(inputBytes);
                Message outputMessage = proxy.Process(inputMessage);
                Console.WriteLine("Received output: {0}", outputMessage);
                byte[] outputBytes = Formatting.MessageToBytes(outputMessage);
                Console.WriteLine("Output bytes:");
                Debugging.PrintBytes(outputBytes);
            }

            ((IClientChannel)proxy).Close();
            factory.Close();

            Console.WriteLine();
            Console.WriteLine("Now using the typed interface");
            ChannelFactory <ITypedTest> typedFactory = new ChannelFactory <ITypedTest>(binding, address);

            typedFactory.Endpoint.Behaviors.Add(new JsonRpcEndpointBehavior());
            ITypedTest typedProxy = typedFactory.CreateChannel();

            Console.WriteLine("Calling Add");
            int result = typedProxy.Add(5, 8);

            Console.WriteLine("  ==> Result: {0}", result);
            Console.WriteLine();

            Console.WriteLine("Calling Multiply");
            result = typedProxy.Multiply(5, 8);
            Console.WriteLine("  ==> Result: {0}", result);
            Console.WriteLine();

            Console.WriteLine("Calling Divide (throws)");
            try
            {
                result = typedProxy.Divide(5, 0);
                Console.WriteLine("  ==> Result: {0}", result);
            }
            catch (JsonRpcException e)
            {
                Console.WriteLine("Error: {0}", e.JsonException);
            }

            Console.WriteLine();
            Console.WriteLine("Now using the typed asynchronous interface");
            var asyncTypedFactory = new ChannelFactory <ITypedTestAsync>(binding, address);

            asyncTypedFactory.Endpoint.Behaviors.Add(new JsonRpcEndpointBehavior());
            ITypedTestAsync asyncTypedProxy = asyncTypedFactory.CreateChannel();

            AutoResetEvent evt = new AutoResetEvent(false);

            Console.WriteLine("Calling BeginAdd");
            asyncTypedProxy.BeginAdd(5, 8, delegate(IAsyncResult ar)
            {
                result = asyncTypedProxy.EndAdd(ar);
                Console.WriteLine("  ==> Result: {0}", result);
                Console.WriteLine();
                evt.Set();
            }, null);
            evt.WaitOne();

            Console.WriteLine("Calling BeginMultiply");
            asyncTypedProxy.BeginMultiply(5, 8, delegate(IAsyncResult ar)
            {
                result = asyncTypedProxy.EndMultiply(ar);
                Console.WriteLine("  ==> Result: {0}", result);
                Console.WriteLine();
                evt.Set();
            }, null);
            evt.WaitOne();

            Console.WriteLine("Calling BeginDivide (throws)");
            asyncTypedProxy.BeginDivide(5, 0, delegate(IAsyncResult ar)
            {
                try
                {
                    result = asyncTypedProxy.EndDivide(ar);
                    Console.WriteLine("  ==> Result: {0}", result);
                }
                catch (JsonRpcException e)
                {
                    Console.WriteLine("Error: {0}", e.JsonException);
                }

                Console.WriteLine();
                evt.Set();
            }, null);
            evt.WaitOne();
        }
Exemple #17
0
        protected HistoricalTrendProviderClient CreateServiceClient()
        {
            _serviceUri = new UriBuilder("https", _Configuration.Host, _Configuration.Port, _Configuration.Path).Uri;
            _userName   = _Configuration.UserName;
            _password   = _Configuration.Password;

            EndpointAddress endpoint = new EndpointAddress(_serviceUri);

            var security = SecurityBindingElement.CreateUserNameOverTransportBindingElement();

            security.EnableUnsecuredResponse = true;
            security.IncludeTimestamp        = false;
            security.MessageSecurityVersion  = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;

            CustomBinding binding = new CustomBinding();

            var mtomBinding = new MtomMessageEncodingBindingElement();

            mtomBinding.MaxBufferSize = 2147483647;
            binding.Elements.Add(mtomBinding);

            HttpTransportBindingElement httpTransport;

            //if ("http".Equals(_serviceUri.Scheme))
            //{
            //    //"http" supports the SoapUI MockService
            //    httpTransport = new HttpTransportBindingElement();
            //}
            //else
            //{
            binding.Elements.Add(security);
            httpTransport = new HttpsTransportBindingElement()
            {
                RequireClientCertificate = false
            };
            //}

            httpTransport.ManualAddressing          = false;
            httpTransport.AllowCookies              = false;
            httpTransport.AuthenticationScheme      = AuthenticationSchemes.Anonymous;
            httpTransport.BypassProxyOnLocal        = false;
            httpTransport.DecompressionEnabled      = true;
            httpTransport.HostNameComparisonMode    = HostNameComparisonMode.StrongWildcard;
            httpTransport.KeepAliveEnabled          = false;
            httpTransport.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous;
            httpTransport.Realm        = "";
            httpTransport.TransferMode = TransferMode.Buffered;
            httpTransport.UnsafeConnectionNtlmAuthentication = false;

            // Setting UseDefaultWebProxy to true slows down the first call to the web service
            httpTransport.UseDefaultWebProxy = false; // this differs from the WCF output

            // Default for the MaxReceivedMessageSize property is 65536 - too small in testing.
            httpTransport.MaxReceivedMessageSize = 2147483647;
            binding.Elements.Add(httpTransport);

            // SendTimeout – used to initialize the OperationTimeout, which governs the
            // whole process of sending a message, including receiving a reply message for
            // a request/reply service operation. This timeout also applies when sending
            // reply messages from a callback contract method.
            // PhasorPoint currently times out after 60 seconds.
            // Wait 30 extra seconds before declaring a timeout.
            // RequestTimeout should typically be 90 seconds.
            binding.SendTimeout = TimeSpan.FromSeconds(120);

            // Use a programmatic binding
            var serviceClient = new HistoricalTrendProviderClient(binding, endpoint);

            serviceClient.ClientCredentials.UserName.UserName = _userName;
            serviceClient.ClientCredentials.UserName.Password = _password;

            // validate cert by calling a function

            serviceClient.Endpoint.Behaviors.Add(_endpointBehavior);

            return(serviceClient);
        }
    public static void ClientBaseOfT_Async_Open_Close_TimeSpan_Factory_And_Proxy_CommunicationState()
    {
        MyClientBase         client                   = null;
        IWcfServiceGenerated serviceProxy             = null;
        ChannelFactory <IWcfServiceGenerated> factory = null;
        TimeSpan timeout = ScenarioTestHelpers.TestTimeout;

        try
        {
            // *** SETUP *** \\
            CustomBinding customBinding = new CustomBinding();
            customBinding.Elements.Add(new TextMessageEncodingBindingElement());
            customBinding.Elements.Add(new HttpTransportBindingElement());

            string endpoint = Endpoints.HttpSoap12_Address;
            client  = new MyClientBase(customBinding, new EndpointAddress(endpoint));
            factory = client.ChannelFactory;

            // *** VALIDATE *** \\
            Assert.True(CommunicationState.Created == client.State,
                        String.Format("Expected client state to be Created but actual was '{0}'", client.State));

            Assert.True(CommunicationState.Created == factory.State,
                        String.Format("Expected channel factory state to be Created but actual was '{0}'", factory.State));

            // Note: both the full framework and this NET Core version open the channel factory
            // when asking for the internal channel.  Attempting to Open the ClientBase
            // after obtaining the internal channel with throw InvalidOperationException attempting
            // to reopen the channel factory.  Customers don't encounter this situation in normal use
            // because access to the internal channel is protected and cannot be acquired.  So we
            // defer asking for the internal channel in this test to allow the Open() to follow the
            // same code path as customer code.

            // *** EXECUTE *** \\
            // Explicitly async open the ClientBase to follow general WCF guidelines
            IAsyncResult ar = ((ICommunicationObject)client).BeginOpen(timeout, null, null);
            ((ICommunicationObject)client).EndOpen(ar);

            // Use the internal proxy generated by ClientBase to most resemble how svcutil-generated code works.
            // This test defers asking for it until the ClientBase is open to avoid the issue described above.
            serviceProxy = client.Proxy;

            Assert.True(CommunicationState.Opened == client.State,
                        String.Format("Expected client state to be Opened but actual was '{0}'", client.State));

            Assert.True(CommunicationState.Opened == factory.State,
                        String.Format("Expected channel factory state to be Opened but actual was '{0}'", factory.State));

            Assert.True(CommunicationState.Opened == ((ICommunicationObject)serviceProxy).State,
                        String.Format("Expected proxy state to be Opened but actual was '{0}'", ((ICommunicationObject)serviceProxy).State));

            // *** EXECUTE *** \\
            // Explicitly close the ClientBase to follow general WCF guidelines
            ar = ((ICommunicationObject)client).BeginClose(timeout, null, null);
            ((ICommunicationObject)client).EndClose(ar);

            // *** VALIDATE *** \\
            // Closing the ClientBase closes the internal channel and factory
            Assert.True(CommunicationState.Closed == client.State,
                        String.Format("Expected client state to be Closed but actual was '{0}'", client.State));

            // Closing the ClientBase also closes the internal channel
            Assert.True(CommunicationState.Closed == ((ICommunicationObject)serviceProxy).State,
                        String.Format("Expected proxy state to be Closed but actual was '{0}'", ((ICommunicationObject)serviceProxy).State));

            // Closing the ClientBase also closes the channel factory
            Assert.True(CommunicationState.Closed == factory.State,
                        String.Format("Expected channel factory state to be Closed but actual was '{0}'", factory.State));
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, client, factory);
        }
    }
Exemple #19
0
        private void button1_Click(object sender, EventArgs e)
        {
            string txtDestinationFolder = @"c:\pobrane_z_ePUAP";
            //string txtAdresSkrytki = "/zsisigidspzoo/skrytkaKD";
            string txtAdresSkrytki = "skrytkaKD";
            string txtNazwaSkrytki = "test KD";
            string txtPodmiot      = "zsisigidspzoo";


            //nowy komentarz

            //parametry do zapytania
            ZapytaniePullOczekujaceTyp zapBody = new ZapytaniePullOczekujaceTyp();

            zapBody.adresSkrytki = txtAdresSkrytki;
            zapBody.nazwaSkrytki = txtNazwaSkrytki;
            zapBody.podmiot      = txtPodmiot;

            textBox1.AppendText("Adres skrytki: " + zapBody.adresSkrytki + Environment.NewLine);
            textBox1.AppendText("Nazwa skrytki: " + zapBody.nazwaSkrytki + Environment.NewLine);
            textBox1.AppendText("Podmiot: " + zapBody.podmiot + Environment.NewLine);

            CustomBinding   pullBinding  = CreatePullBinding();
            EndpointAddress pullEndpoint = CreatePullEndpoint();

            //klient pull
            pullClient _client = new pullClient(pullBinding, pullEndpoint);

            X509Certificate2 certyfikatKlienta = GetClientCert();
            X509Certificate2 certyfikatSerwisu = GetServiceCert();

            _client.ClientCredentials.ClientCertificate.Certificate         = certyfikatKlienta;
            _client.ClientCredentials.ServiceCertificate.DefaultCertificate = certyfikatSerwisu;

            //certyfikat dostarczony przez ePUAP do podpisywanie nie daje się zwalidować pod względem nadrzędnych instytucji
            //tzn. chyba sami go sobie wystawiają
            _client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

            try
            {
                //sprawdź oczekujące dokumenty
                OdpowiedzPullOczekujaceTyp odp = _client.oczekujaceDokumenty(zapBody);

                textBox1.AppendText("Oczekujące dokumenty: " + odp.oczekujace.ToString());
            }
            catch (MessageSecurityException ex)
            {
                try
                {
                    System.ServiceModel.FaultException exInner = (FaultException)ex.InnerException;
                    textBox1.AppendText("Wyjątek 1: " + ex.Message);
                    if (ex.InnerException == null)
                    {
                        throw new Exception("Brak szczegółowych informacji o błędzie.");
                    }
                    FaultException fe = ex.InnerException as FaultException;
                    textBox1.AppendText("Wyjątek 2: " + fe.Message);
                    if (fe == null)
                    {
                        throw new Exception("Szczegółowe informacje zapisane zostały w nieprzewidzianym formacie.");
                    }
                    MessageFault mf = fe.CreateMessageFault();
                    if (mf == null)
                    {
                        throw new Exception("Wystąpił problem podczas odtwarzania szczegółowych informacji.");
                    }
                    XmlReader   xr = mf.GetReaderAtDetailContents();
                    XmlDocument xd = new XmlDocument();
                    xd.Load(xr);
                    XmlNode       elemKomunikat = xd.SelectSingleNode("//*[local-name() = 'komunikat']");
                    XmlNode       elemKod       = xd.SelectSingleNode("//*[local-name() = 'kod']");
                    StringBuilder msg           = new StringBuilder();
                    msg.Append("Wystąpił problem z doręczeniem dokumentów. Poniżej znajdują się szczegółowe informacje (komunikaty) przekazane przez ePUAP.");
                    msg.AppendFormat("Informacja z ePUAP: \"{0}, kod błędu: {1}\"", elemKomunikat.InnerText, elemKod.InnerText);
                    textBox1.AppendText(msg.ToString());
                }
                catch (Exception iex)
                {
                    //textBox1.AppendText(ex.Message);
                    //textBox1.AppendText(iex.Message);
                }
            }
            catch (Exception ex)
            {
                textBox1.AppendText(string.Format("Wystąpił błąd podczas pobierania liczby oczekujacych dokumentow:   " + ex.Message));
                textBox1.AppendText(string.Format("Wystąpił błąd podczas pobierania liczby oczekujacych source:   " + ex));
            }
        }
Exemple #20
0
        void OnExplore(object sender, EventArgs e)
        {
            m_ExploreButton.Enabled = false;

            string mexAddress = m_MexAddressTextBox.Text;

            if (String.IsNullOrEmpty(mexAddress))
            {
                Debug.Assert(false, "Empty address");
            }
            m_MexTree.Nodes.Clear();
            DisplayBlankControl();

            SplashScreen splash = new SplashScreen(Resources.Progress);

            try
            {
                Uri address = new Uri(mexAddress);
                ServiceEndpointCollection endpoints = null;

                if (address.Scheme == "http")
                {
                    HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTP MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpBindingElement);
                    }
                    catch
                    {}
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "https")
                {
                    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTPS MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpsBindingElement);
                    }
                    catch
                    {
                    }
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpsGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpsGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpsBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "net.tcp")
                {
                    TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                    tcpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(tcpBindingElement);
                }
                if (address.Scheme == "net.pipe")
                {
                    NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                    ipcBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(ipcBindingElement);
                }
                ProcessMetaData(endpoints);
            }
            catch
            {
                m_MexTree.Nodes.Clear();

                m_Root = new ServiceNode(this, "Invalid Base Address", ServiceError, ServiceError);
                m_MexTree.Nodes.Add(m_Root);
                return;
            }
            finally
            {
                splash.Close();
                m_ExploreButton.Enabled = true;
            }
        }
Exemple #21
0
        /// <summary>
        /// Get all the information about the services in a current address.
        /// Send the http://schemas.xmlsoap.org/ws/2004/09/transfer/Get message and
        /// receive the http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse.
        /// </summary>
        /// <param name="device">The device containing the services.</param>
        public static void GetMetaData(edu.teco.DPWS.Device device)
        {
            // Custom binding with TextMessageEncoding and HttpTransport and the specific soap and wsa versions shown here:
            CustomBinding binding = new CustomBinding(
                new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressingAugust2004, Encoding.UTF8),
                new HttpTransportBindingElement());

            // A custom mex client deriving from MetadataExchangeClient. The motivation behind writing the custom client was to get at the ClientVia behavior for the MetadataExchangeClient.
            // Followed the instructions here for this.
            // Gave the physical address in the Via for the custom client and the logical address as the EP address to be put into the ws-addressing To header as:
            MetadataExchangeClient mex         = new MetadataExchangeClient(binding);
            MetadataSet            metadataSet = mex.GetMetadata(device.EndpointAddress);

            // Check for the metadata set size.
            System.Collections.ObjectModel.Collection <MetadataSection> documentCollection = metadataSet.MetadataSections;
            if (documentCollection != null)
            {
                //Get the WSDL from each MetadataSection of the metadata set
                foreach (MetadataSection section in documentCollection)
                {
                    try
                    {
                        if (section.Metadata is System.Xml.XmlElement)
                        {
                            System.Xml.XmlElement element = (System.Xml.XmlElement)section.Metadata;
                            if (element.Name == "wsdp:Relationship")
                            {
                                Relationship relationship = (Relationship)Utils.FromXML(element.OuterXml, typeof(Relationship), string.Empty);

                                foreach (System.Xml.XmlElement innerElement in relationship.Any)
                                {
                                    if (innerElement.Name == "wsdp:Host")
                                    {
                                        HostServiceType host = (HostServiceType)Utils.FromXML(innerElement.OuterXml, typeof(HostServiceType),
                                                                                              string.Empty);
                                    }
                                    else if (innerElement.Name == "wsdp:Hosted")
                                    {
                                        HostServiceType hosted = (HostServiceType)Utils.FromXML(innerElement.OuterXml, typeof(HostServiceType),
                                                                                                "http://schemas.xmlsoap.org/ws/2006/02/devprof", new System.Xml.Serialization.XmlRootAttribute("Hosted"));

                                        if (hosted.EndpointReference != null && hosted.EndpointReference.Length > 0)
                                        {
                                            Console.WriteLine("Service ID: {0}", hosted.ServiceId);

                                            foreach (edu.teco.DPWS.Service service in device.GetServices())
                                            {
                                                if (hosted.ServiceId.Equals(service.GetServiceID()))
                                                {
                                                    service.HostedEndpoint = new EndpointAddress(hosted.EndpointReference[0].Address.Value);
                                                    Console.WriteLine("Found endpoint for {0}", service.GetServiceID());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (element.Name == "wsdp:ThisModel")
                            {
                                ThisModelType thisModel = (ThisModelType)Utils.FromXML(element.OuterXml, typeof(ThisModelType), string.Empty);
                            }
                            else if (element.Name == "wsdp:ThisDevice")
                            {
                                ThisDeviceType thisDevice = (ThisDeviceType)Utils.FromXML(element.OuterXml, typeof(ThisDeviceType), string.Empty);
                                Console.WriteLine(string.Format("FirmwareVersion: {0}", thisDevice.FirmwareVersion));
                                Console.WriteLine(string.Format("FriendlyName: {0}", thisDevice.FriendlyName));
                                Console.WriteLine(string.Format("SerialNumber: {0}", thisDevice.SerialNumber));
                            }
                        }
                        else if (section.Metadata is System.Web.Services.Description.ServiceDescription)
                        {
                            System.Web.Services.Description.ServiceDescription sd = (System.Web.Services.Description.ServiceDescription)section.Metadata;
                            Console.WriteLine(string.Format("ServiceDescription name: {0}", sd.Name));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error on getting MetaData.:{0}", ex.Message);
                    }
                }
            }
        }
    public static async Task RetryCountApplied(ReliableMessagingVersion rmVersion, bool ordered, string endpointSuffix)
    {
        ChannelFactory <IWcfReliableService> factory = null;
        IWcfReliableService serviceProxy             = null;
        NetHttpBinding      binding = null;

        try
        {
            // *** SETUP *** \\
            binding = new NetHttpBinding(BasicHttpSecurityMode.None, true);
            binding.ReliableSession.Ordered = ordered;
            var customBinding = new CustomBinding(binding);
            var reliableSessionBindingElement = customBinding.Elements.Find <ReliableSessionBindingElement>();
            reliableSessionBindingElement.MaxRetryCount            = 2;
            reliableSessionBindingElement.ReliableMessagingVersion = rmVersion;
            factory = new ChannelFactory <IWcfReliableService>(customBinding, new EndpointAddress(Endpoints.ReliableSession_NetHttp + endpointSuffix));
            var       handlerFactoryBehavior = new HttpMessageHandlerBehavior();
            bool      delayNextCall          = false;
            int       httpRequestCount       = 0;
            Stopwatch sw = null;
            TaskCompletionSource <object> tcs1 = null, tcs2 = new TaskCompletionSource <object>();
            handlerFactoryBehavior.OnSendingAsync = async(request, token) =>
            {
                Interlocked.Increment(ref httpRequestCount);
                // Once the delayNextCall latch is set, all subsequent calls will be on hold until tcs1 is completed.
                if (delayNextCall)
                {
                    if (tcs1 == null) // First delayed call
                    {
                        sw   = Stopwatch.StartNew();
                        tcs1 = new TaskCompletionSource <object>();
                    }
                    else if (sw.IsRunning)
                    {
                        sw.Stop();               // Get time between initial call and 1st retry
                        tcs2.TrySetResult(null); // Signal main test code that stopwatch measurement taken
                    }
                    // All calls will wait on the same TCS as trying to trigger retry;
                    await tcs1.Task;
                }
                return(null);
            };
            factory.Endpoint.Behaviors.Add(handlerFactoryBehavior);
            serviceProxy = factory.CreateChannel();
            // *** EXECUTE *** \\
            ((IClientChannel)serviceProxy).Open(); // This will establish a reliable session
            delayNextCall = true;
            // Reset request count as it would have incremented in the session open handshake
            httpRequestCount = 0;
            var resultTask = serviceProxy.GetNextNumberAsync();
            await tcs2.Task; // Wait for Stopwatch to be stopped

            // *** VALIDATE *** \\
            // There should only be a single retry at this point
            Assert.Equal(2, httpRequestCount);
            // ReliableSessions doubles the wait time between each retry. We know the first retry time. The second retry
            // will be 2X this, then the request will fail after another wait of 4X this delay. We need to wait at LEAST 6X
            // this initial delay for the channel to fault. 10X should be sufficient
            await Task.Delay((int)sw.ElapsedMilliseconds * 10);

            // There should now be the second retry (3 attempts to send the request) as well as the SequenceTerminated fault
            // making a total of 4 requests
            Assert.Equal(4, httpRequestCount);
            // Release the paused Http requests
            tcs1.TrySetResult(null);
            await Assert.ThrowsAsync <CommunicationException>(() => resultTask);

            Assert.Equal(CommunicationState.Faulted, ((ICommunicationObject)serviceProxy).State);
            ((ICommunicationObject)serviceProxy).Abort(); // Remove from factory so factory doesn't throw when closed.

            // *** CLEANUP *** \\
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Exemple #23
0
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if (String.IsNullOrEmpty(mexAddress))
            {
                Debug.Assert(false, "Empty address");
                return(null);
            }
            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints = null;

            if (address.Scheme == "http")
            {
                HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTP MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpBindingElement);
                }
                catch
                {}

                //Try over HTTP-GET
                if (endpoints == null)
                {
                    string httpGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpGetAddress += "?wsdl";
                    }
                    CustomBinding          binding   = new CustomBinding(httpBindingElement);
                    MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                    MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter       importer  = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "https")
            {
                HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTPS MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpsBindingElement);
                }
                catch
                {}

                //Try over HTTP-GET
                if (endpoints == null)
                {
                    string httpsGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpsGetAddress += "?wsdl";
                    }
                    CustomBinding          binding   = new CustomBinding(httpsBindingElement);
                    MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                    MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter       importer  = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "net.tcp")
            {
                TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                tcpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, tcpBindingElement);
            }
            if (address.Scheme == "net.pipe")
            {
                NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                ipcBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, ipcBindingElement);
            }
            return(endpoints.ToArray());
        }
    public static async Task ResendFailedRequest(ReliableMessagingVersion rmVersion, bool ordered, string endpointSuffix)
    {
        ChannelFactory <IWcfReliableService> factory = null;
        IWcfReliableService serviceProxy             = null;
        NetHttpBinding      binding = null;

        try
        {
            // *** SETUP *** \\
            binding = new NetHttpBinding(BasicHttpSecurityMode.None, true);
            binding.ReliableSession.Ordered = ordered;
            var customBinding = new CustomBinding(binding);
            var reliableSessionBindingElement = customBinding.Elements.Find <ReliableSessionBindingElement>();
            reliableSessionBindingElement.ReliableMessagingVersion = rmVersion;
            factory = new ChannelFactory <IWcfReliableService>(customBinding, new EndpointAddress(Endpoints.ReliableSession_NetHttp + endpointSuffix));
            var  handlerFactoryBehavior = new HttpMessageHandlerBehavior();
            bool delayNextCall          = false;
            int  callCount = 0;
            TaskCompletionSource <object> tcs1 = null, tcs2 = null;
            handlerFactoryBehavior.OnSendingAsync = async(request, token) =>
            {
                Interlocked.Increment(ref callCount);
                // Once the delayNextCall latch is set, the next call will be held back until after
                // it has been retried.
                if (delayNextCall)
                {
                    delayNextCall = false;
                    tcs1          = new TaskCompletionSource <object>();
                    await tcs1.Task;
                }
                return(null);
            };
            handlerFactoryBehavior.OnSentAsync = (response, token) =>
            {
                if (tcs2 != null)
                {
                    // Let the main test code know that the original held back call has returned from the service
                    tcs2.TrySetResult(null);
                }
                if (tcs1 != null)
                {
                    // This is the retry of the first service call. Release the held back initial call
                    tcs1.TrySetResult(null);
                    tcs1 = null;
                    tcs2 = new TaskCompletionSource <object>();
                }
                return(Task.FromResult(response));
            };
            factory.Endpoint.Behaviors.Add(handlerFactoryBehavior);
            serviceProxy = factory.CreateChannel();
            // *** EXECUTE *** \\
            ((IClientChannel)serviceProxy).Open(); // This will establish a reliable session
            delayNextCall = true;
            // Reset call count as it would have incremented in the session open handshake
            callCount = 0;
            var result1 = await serviceProxy.GetNextNumberAsync();

            // Wait for the first attempt for first call to complete before making second call
            await tcs2.Task;
            // This check ensures that the sequence number on the retry was the same as the original. If they
            // were different, the call on the retry would have been dispatched on the service and an extra
            // increment would have happened.
            var result2 = await serviceProxy.GetNextNumberAsync();

            // *** VALIDATE *** \\
            Assert.Equal(1, result1);
            Assert.Equal(2, result2);
            // Validate that 3 http calls were made as first call should have retried.
            Assert.Equal(3, callCount);

            // *** CLEANUP *** \\
            ((IClientChannel)serviceProxy).Close();
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Exemple #25
0
        public static int Login(string AppName, string ModuleName, string ModuleVersion, string server, string username, string password, string KeyInfo)
        {
            int nLogin = 0;

            if (server != null && server.Length > 0)
            {
                if (server.IndexOf(":") > 0)
                {
                    RemoteAddress             = string.Format("http://{0}/CenterService", server);
                    RemoteFileTransferAddress = string.Format("http://{0}/FileTransferService", server);
                }
                else
                {
                    RemoteAddress             = string.Format("http://{0}:22888/CenterService", server);
                    RemoteFileTransferAddress = string.Format("http://{0}:22888/FileTransferService", server);
                }

                try
                {
                    customBinding = new CustomBinding("GZipHttpBinding");

                    using (ChannelFactory <ICenterService> channelFactory = new ChannelFactory <ICenterService>(customBinding, RemoteAddress))
                    {
                        SetMaxItemsInObjectGraph(channelFactory);

                        ICenterService proxy = channelFactory.CreateChannel();

                        string strHostIP       = GetLocalIP();
                        string strClientHost   = strHostIP;
                        string strClientDesKey = "PCOCSimulator";
                        //char[] szDesKey = strClientDesKey.ToCharArray();
                        //IntPtr intPtrClientHost = GetKeyString(szDesKey);
                        //if (intPtrClientHost != null)
                        //{
                        //    strClientHost = Marshal.PtrToStringAnsi(intPtrClientHost);
                        //}
                        gAppName       = AppName;
                        gModuleName    = ModuleName;
                        gModuleVersion = ModuleVersion;
                        gKeyInfo       = KeyInfo;
                        gClientHost    = strClientHost;
                        gServer        = server;
                        gUserName      = username;
                        gPassword      = password;

                        string loginString = string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};",
                                                           LoginID, GetLocalIP(), username, password, AppName, ModuleName, ModuleVersion, KeyInfo, strClientHost);

                        string loginRet = proxy.Login(loginString);

                        if (loginRet == "Success")
                        {
                            nLogin      = 1;
                            ExtraConfig = new ExtraConfig();

                            if (tVerifyServer == null)
                            {
                                //实例化Timer类,设置间隔时间为3*60 000毫秒(3分钟);
                                tVerifyServer = new System.Timers.Timer(180000);
                                //到达时间的时候执行事件;
                                tVerifyServer.Elapsed += new System.Timers.ElapsedEventHandler(handlerVerifyServer);
                                //设置是执行一次(false)还是一直执行(true);
                                tVerifyServer.AutoReset = true;
                                //是否执行System.Timers.Timer.Elapsed事件;
                                tVerifyServer.Enabled = true;
                            }

                            if (AppName != ModuleName)
                            {
                                gVerifyModuleNames += ModuleName;
                                gVerifyModuleNames += ", ";
                            }
                        }
                        else
                        {
                            ErrorInfo = string.Format("登陆失败!\n\n错误信息:{0} \n请确认后再重试。", loginRet);
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    ErrorInfo = string.Format("登陆失败!\n\n错误信息:{0}\n请确认后再重试。", ex.Message);
                }
            }

            if (clientEvent != null)
            {
                if (nLogin == 1)
                {
                    clientEvent.doEvent(ClientEvent.LicenseSucceed);
                }
                else
                {
                    clientEvent.doEvent(ClientEvent.LicenseFailed);
                }
            }

            return(nLogin);
        }
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if (string.IsNullOrWhiteSpace(mexAddress))
            {
                throw new ArgumentException("mexAddress");
            }

            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints      = null;
            BindingElement            bindingElement = null;

            //Try over HTTP-GET first
            if (address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps)
            {
                string getAddress = mexAddress;
                if (mexAddress.EndsWith("?wsdl") == false)
                {
                    getAddress += "?wsdl";
                }
                if (address.Scheme == Uri.UriSchemeHttp)
                {
                    HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                    bindingElement = httpBindingElement;
                }
                else
                {
                    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                    bindingElement = httpsBindingElement;
                }
                CustomBinding binding = new CustomBinding(bindingElement);

                MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
                MetadataSet            metadata  = mexClient.GetMetadata(new Uri(getAddress), MetadataExchangeClientMode.HttpGet);
                MetadataImporter       importer  = new WsdlImporter(metadata);
                endpoints = importer.ImportAllEndpoints();
                return(endpoints.ToArray());
            }

            //Try MEX endpoint:

            if (address.Scheme == Uri.UriSchemeHttp)
            {
                bindingElement = new HttpTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeHttps)
            {
                bindingElement = new HttpsTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeNetTcp)
            {
                bindingElement = new TcpTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeNetPipe)
            {
                bindingElement = new NamedPipeTransportBindingElement();
            }

            endpoints = QueryMexEndpoint(mexAddress, bindingElement);
            return(endpoints.ToArray());
        }
Exemple #27
0
        void AddMetadataEndpoint(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher, bool debugMode)
        {
            Uri baseAddress = endpoint.Address.Uri;

            if (baseAddress == null)
            {
                return;
            }

            ServiceHostBase host = endpointDispatcher.ChannelDispatcher.Host;

            UriBuilder builder = new UriBuilder(baseAddress);

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

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

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

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

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

            // build endpoint dispatcher
            ContractDescription  metadataContract           = ContractDescription.GetContract(typeof(ServiceMetadataExtension.IHttpGetMetadata));
            OperationDescription metadataOperation          = metadataContract.Operations[0];
            EndpointDispatcher   metadataEndpointDispatcher = new EndpointDispatcher(metadataAddress, metadataContract.Name, metadataContract.Namespace);
            DispatchOperation    dispatchOperation          = new DispatchOperation(metadataEndpointDispatcher.DispatchRuntime, metadataOperation.Name, metadataOperation.Messages[0].Action, metadataOperation.Messages[1].Action);

            dispatchOperation.Formatter = new WebScriptMetadataFormatter();
            dispatchOperation.Invoker   = new SyncMethodInvoker(metadataOperation.SyncMethod);
            metadataEndpointDispatcher.DispatchRuntime.Operations.Add(dispatchOperation);
            metadataEndpointDispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, new WebScriptClientGenerator(endpoint, debugMode, !String.IsNullOrEmpty(this.JavascriptCallbackParameterName)));
            metadataEndpointDispatcher.DispatchRuntime.InstanceContextProvider  = new SingletonInstanceContextProvider(metadataEndpointDispatcher.DispatchRuntime);

            // build channel dispatcher
            IChannelListener <IReplyChannel> listener = null;

            if (metadataBinding.CanBuildChannelListener <IReplyChannel>(parameters))
            {
                listener = metadataBinding.BuildChannelListener <IReplyChannel>(metadataAddress.Uri, parameters);
            }
            ChannelDispatcher metadataChannelDispatcher = new ChannelDispatcher(listener);

            metadataChannelDispatcher.MessageVersion = MessageVersion.None;
            metadataChannelDispatcher.Endpoints.Add(metadataEndpointDispatcher);

            host.ChannelDispatchers.Add(metadataChannelDispatcher);
        }
Exemple #28
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="request">Hashtable containing the request fields and their values.</param>
        /// <returns>Hashtable containing the reply fields and their values.</returns>
        public static Hashtable RunTransaction(
            Configuration config, Hashtable request)
        {
            Logger logger = null;
            NVPTransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, request);
                SetVersionInformation(request);
                logger = PrepareLog(config);
                SetConnectionLimit(config);

                //Setup custom binding with HTTPS + Body Signing
                CustomBinding currentBinding = getWCFCustomBinding(config);

                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new NVPTransactionProcessorClient(currentBinding, endpointAddress))
                {
                    //Set protection level to sign
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;


                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = new X509Certificate2Collection();
                    collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    foreach (X509Certificate2 cert1 in collection)
                    {
                        if (cert1.Subject.Contains(config.MerchantID))
                        {
                            proc.ClientCredentials.ClientCertificate.Certificate         = cert1;
                            proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert1;
                            break;
                        }
                    }

                    if (config.UseSignedAndEncrypted)
                    {
                        foreach (X509Certificate2 cert2 in collection)
                        {
                            //Console.WriteLine(cert1.Subject);
                            if (cert2.Subject.Contains(CYBERSOURCE_PUBLIC_KEY))
                            {
                                //Set protection level to sign & encrypt only
                                proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
                                proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert2;
                                break;
                            }
                        }
                    }

                    if (logger != null)
                    {
                        logger.LogRequest(request, config.Demo);
                    }

                    // send request now, converting the hashtable request into
                    // a string, and the string reply back into a hashtable.

                    string resp = proc.runTransaction(Hash2String(request));


                    Hashtable reply = String2Hash(resp);

                    if (logger != null)
                    {
                        logger.LogReply(reply, config.Demo);
                    }

                    return(reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Exemple #29
0
        public bool SetupBinaryClient()
        {
            ServerOnline      = false;
            _clientBinaryHTTP = null;
            ImportFolders.Clear();

            if (!SettingsAreValid())
            {
                return(false);
            }

            try
            {
                AnimePluginSettings settings = new AnimePluginSettings();
                string url = string.Format(@"http://{0}:{1}/JMMServerBinary", settings.JMMServer_Address, settings.JMMServer_Port);
                BaseConfig.MyAnimeLog.Write("JMM Server URL: " + url);

                BinaryMessageEncodingBindingElement encoding = new BinaryMessageEncodingBindingElement();
                encoding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
                encoding.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
                encoding.ReaderQuotas.MaxDepth               = int.MaxValue;
                encoding.ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;
                encoding.ReaderQuotas.MaxStringContentLength = int.MaxValue;

                HttpTransportBindingElement transport = new HttpTransportBindingElement();
                transport.MaxReceivedMessageSize = int.MaxValue;
                transport.MaxBufferPoolSize      = int.MaxValue;
                transport.MaxBufferSize          = int.MaxValue;
                transport.MaxReceivedMessageSize = int.MaxValue;


                Binding binding = new CustomBinding(encoding, transport);

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

                EndpointAddress endpoint = new EndpointAddress(new Uri(url));

                var factory = new ChannelFactory <JMMServerBinary.IJMMServerChannel>(binding, endpoint);
                foreach (OperationDescription op in factory.Endpoint.Contract.Operations)
                {
                    var dataContractBehavior = op.Behaviors.Find <DataContractSerializerOperationBehavior>();
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                    }
                }

                _clientBinaryHTTP = factory.CreateChannel();

                // try connecting to see if the server is responding
                JMMServerBinary.Contract_ServerStatus status = JMMServerVM.Instance.clientBinaryHTTP.GetServerStatus();
                ServerOnline = true;

                GetServerSettings();
                RefreshImportFolders();

                BaseConfig.MyAnimeLog.Write("JMM Server Status: " + status.GeneralQueueState);

                return(true);
            }
            catch (Exception ex)
            {
                //Utils.ShowErrorMessage(ex);
                BaseConfig.MyAnimeLog.Write(ex.ToString());
                return(false);
            }
        }
Exemple #30
0
        static void TestWithTypedMessage()
        {
            string      baseAddress = SizedTcpDuplexTransportBindingElement.SizedTcpScheme + "://localhost:8000";
            ServiceHost host        = new ServiceHost(typeof(Service), new Uri(baseAddress));
            Binding     binding     = new CustomBinding(new SizedTcpDuplexTransportBindingElement());

            host.AddServiceEndpoint(typeof(ITypedTest), binding, "");
            host.Open();

            Console.WriteLine("Host opened");

            Socket socket = GetConnectedSocket(8000);

            string request = @"<s:Envelope
        xmlns:s=""http://www.w3.org/2003/05/soap-envelope""
        xmlns:a=""http://www.w3.org/2005/08/addressing"">
    <s:Header>
        <a:Action s:mustUnderstand=""1"">http://tempuri.org/ITypedTest/Add</a:Action>
        <a:MessageID>urn:uuid:c2998797-7312-481a-8f73-230406b12bea</a:MessageID>
        <a:ReplyTo>
            <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
        </a:ReplyTo>
        <a:To s:mustUnderstand=""1"">ENDPOINT_ADDRESS</a:To>
    </s:Header>
    <s:Body>
        <Add xmlns=""http://tempuri.org/"">
            <x>4</x>
            <y>5</y>
        </Add>
    </s:Body>
</s:Envelope>";

            request = request.Replace("ENDPOINT_ADDRESS", baseAddress);

            Encoding encoding  = new UTF8Encoding(false);
            int      byteCount = encoding.GetByteCount(request);

            byte[] reqBytes = new byte[byteCount + 4];
            Formatting.SizeToBytes(byteCount, reqBytes, 0);
            encoding.GetBytes(request, 0, request.Length, reqBytes, 4);
            Console.WriteLine("Sending those bytes:");
            Debugging.PrintBytes(reqBytes);
            socket.Send(reqBytes);
            byte[] recvBuffer = new byte[10000];
            int    bytesRecvd = socket.Receive(recvBuffer);

            Console.WriteLine("Received {0} bytes", bytesRecvd);
            Debugging.PrintBytes(recvBuffer, bytesRecvd);

            Console.WriteLine("Press ENTER to send another request");
            Console.ReadLine();

            request = @"<s:Envelope
        xmlns:s=""http://www.w3.org/2003/05/soap-envelope""
        xmlns:a=""http://www.w3.org/2005/08/addressing"">
    <s:Header>
        <a:Action s:mustUnderstand=""1"">http://tempuri.org/ITypedTest/Subtract</a:Action>
        <a:MessageID>urn:uuid:c2998797-7312-481a-8f73-230406b12bea</a:MessageID>
        <a:ReplyTo>
            <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
        </a:ReplyTo>
        <a:To s:mustUnderstand=""1"">ENDPOINT_ADDRESS</a:To>
    </s:Header>
    <s:Body>
        <Subtract xmlns=""http://tempuri.org/"">
            <x>4</x>
            <y>5</y>
        </Subtract>
    </s:Body>
</s:Envelope>";

            request   = request.Replace("ENDPOINT_ADDRESS", baseAddress);
            byteCount = encoding.GetByteCount(request);
            reqBytes  = new byte[byteCount + 4];
            Formatting.SizeToBytes(byteCount, reqBytes, 0);
            encoding.GetBytes(request, 0, request.Length, reqBytes, 4);
            Console.WriteLine("Sending those bytes:");
            Debugging.PrintBytes(reqBytes);
            socket.Send(reqBytes);
            bytesRecvd = socket.Receive(recvBuffer);
            Console.WriteLine("Received {0} bytes", bytesRecvd);
            Debugging.PrintBytes(recvBuffer, bytesRecvd);

            socket.Close();

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();
            host.Close();
        }
Exemple #31
0
        private static void AddCustomBindingConfiguration(CodeStatementCollection statements, CustomBinding custom)
        {
            const string ResultVarName = "result";

            statements.Add(
                new CodeVariableDeclarationStatement(
                    typeof(CustomBinding),
                    ResultVarName,
                    new CodeObjectCreateExpression(typeof(CustomBinding))));
            CodeVariableReferenceExpression resultVar = new CodeVariableReferenceExpression(ResultVarName);

            foreach (BindingElement bindingElement in custom.Elements)
            {
                bool handled = false;
                TextMessageEncodingBindingElement textBE = bindingElement as TextMessageEncodingBindingElement;
                if (textBE != null)
                {
                    AddTextBindingElement(statements, resultVar, textBE);
                    handled = true;
                }

                if (!handled)
                {
                    BinaryMessageEncodingBindingElement binaryBE = bindingElement as BinaryMessageEncodingBindingElement;
                    if (binaryBE != null)
                    {
                        AddBinaryBindingElement(statements, resultVar);
                        handled = true;
                    }
                }

                if (!handled)
                {
                    HttpTransportBindingElement httpTE = bindingElement as HttpTransportBindingElement;
                    if (httpTE != null)
                    {
                        AddHttpBindingElement(statements, resultVar, httpTE);
                        handled = true;
                    }
                }

                if (!handled)
                {
                    TcpTransportBindingElement tcpTE = bindingElement as TcpTransportBindingElement;
                    if (tcpTE != null)
                    {
                        AddTcpBindingElement(statements, resultVar, tcpTE);
                        handled = true;
                    }
                }

                if (!handled)
                {
                    TransportSecurityBindingElement transportSE = bindingElement as TransportSecurityBindingElement;
                    if (transportSE != null)
                    {
                        AddTransportSecurityBindingElement(statements, resultVar, transportSE);
                        handled = true;
                    }
                }

                if (!handled)
                {
                    TransactionFlowBindingElement transactionBE = bindingElement as TransactionFlowBindingElement;
                    if (transactionBE != null)
                    {
                        // if transaction is enabled, the binding should have been filtered before. Nothing to do here.
                        handled = true;
                    }
                }

                if (!handled)
                {
                    SslStreamSecurityBindingElement sslStreamSE = bindingElement as SslStreamSecurityBindingElement;
                    if (sslStreamSE != null)
                    {
                        AddSslStreamSecurityBindingElement(statements, resultVar);
                        handled = true;
                    }
                }

                if (!handled)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ErrBindingElementNotSupportedFormat, bindingElement.GetType().FullName));
                }
            }

            statements.Add(new CodeMethodReturnStatement(resultVar));
        }
Exemple #32
0
        public static Binding CreateHttpBinding()
        {
            /*
             * var binding = new WSHttpBinding
             * {
             *  MaxBufferPoolSize = int.MaxValue,
             *  MaxReceivedMessageSize = int.MaxValue,
             *  ReliableSession = {
             *      Enabled = true
             *  },
             *  Security =
             *  {
             *      Mode = SecurityMode.None
             *  },
             *  ReaderQuotas =
             *  {
             *      MaxArrayLength = int.MaxValue,
             *      MaxStringContentLength = int.MaxValue
             *  }
             * };
             * binding.ReceiveTimeout = TimeSpan.FromHours(12);
             * binding.SendTimeout = TimeSpan.FromHours(12);
             * binding.OpenTimeout = TimeSpan.FromHours(12);
             * binding.CloseTimeout = TimeSpan.FromHours(12);
             *
             * binding.MaxReceivedMessageSize = int.MaxValue;
             * binding.ReaderQuotas.MaxArrayLength = int.MaxValue;
             * binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
             * binding.Security.Mode = SecurityMode.None;
             * binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
             */

            var binMessageElement = new BinaryMessageEncodingBindingElement();

            binMessageElement.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            binMessageElement.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            binMessageElement.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
            binMessageElement.ReaderQuotas.MaxDepth = int.MaxValue;
            binMessageElement.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;

            var gzipElement = new GZipMessageEncodingBindingElement
            {
                InnerMessageEncodingBindingElement = binMessageElement
            };

            var reliableElement = new ReliableSessionBindingElement()
            {
                MaxPendingChannels = 16384,
                Ordered            = true
            };
            Boolean _configProxy = false;

            if (App.Configs.UseProxy == CONSTANTS.Yes)
            {
                _configProxy = true;
            }

            var httpTransport = new HttpTransportBindingElement
            {
                KeepAliveEnabled       = true,
                MaxBufferPoolSize      = int.MaxValue,
                MaxBufferSize          = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                UseDefaultWebProxy     = _configProxy,
            };


            //tcpTransport.ReaderQuotas.MaxArrayLength = int.MaxValue;
            //tcpTransport.ReaderQuotas.MaxStringContentLength = int.MaxValue;

            var binding = new CustomBinding(reliableElement, gzipElement, httpTransport)
            {
                ReceiveTimeout = TimeSpan.FromHours(12),
                SendTimeout    = TimeSpan.FromHours(12),
                OpenTimeout    = TimeSpan.FromHours(12),
                CloseTimeout   = TimeSpan.FromHours(12)
            };

            //binding.ReliableSession.Enabled = false;


            //binding.Security.Mode = SecurityMode.None;
            //binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;

            return(binding);
        }
        public IdMappingClientImpl(string location, string pfxFilename, string password)
        {
            /*
             * BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
             * BasicHttpSecurity security = basicBinding.Security;
             * security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
             *
             * BasicHttpMessageSecurity messageSecurity = security.Message;
             * messageSecurity.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
             * messageSecurity.AlgorithmSuite = SecurityAlgorithmSuite.Default;
             *
             * HttpTransportSecurity transportSecurity = security.Transport;
             * transportSecurity.ClientCredentialType = HttpClientCredentialType.None;
             * transportSecurity.ProxyCredentialType = HttpProxyCredentialType.None;
             * transportSecurity.Realm = "";
             *
             * BindingElementCollection bec = basicBinding.CreateBindingElements();
             * TransportSecurityBindingElement tsp = bec.Find<TransportSecurityBindingElement>();
             * HttpsTransportBindingElement httpsBinding = bec.Find<HttpsTransportBindingElement>();
             * TextMessageEncodingBindingElement encoding = bec.Find<TextMessageEncodingBindingElement>();
             * SecurityBindingElement securityBinding = bec.Find<SecurityBindingElement>();
             * CustomBinding binding = new CustomBinding(tsp, encoding, httpsBinding);
             */
            CustomBinding binding = new CustomBinding();
            HttpsTransportBindingElement      httpsTransport = new HttpsTransportBindingElement();
            TextMessageEncodingBindingElement encoding       = new TextMessageEncodingBindingElement();

            encoding.MessageVersion = MessageVersion.Soap11;

            //SecurityBindingElement securityBinding =
            //	SecurityBindingElement.CreateCertificateOverTransportBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
            //SecurityBindingElement securityBinding = SecurityBindingElement.CreateSslNegotiationBindingElement(false);

            /*
             * AsymmetricSecurityBindingElement securityBinding =
             * (AsymmetricSecurityBindingElement)SecurityBindingElement.
             * CreateMutualCertificateBindingElement(
             *      MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, true);
             * securityBinding.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default;
             * securityBinding.SetKeyDerivation(false);
             * securityBinding.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
             */
            SslStreamSecurityBindingElement sslStreamSecurity = new SslStreamSecurityBindingElement();
            //binding.Elements.Add(securityBinding);

            TransportSecurityBindingElement securityBinding = new TransportSecurityBindingElement();

            securityBinding.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
            securityBinding.DefaultAlgorithmSuite  = SecurityAlgorithmSuite.Default;
            securityBinding.SetKeyDerivation(false);
            X509SecurityTokenParameters certToken = new X509SecurityTokenParameters();

            certToken.InclusionMode      = SecurityTokenInclusionMode.AlwaysToRecipient;
            certToken.ReferenceStyle     = SecurityTokenReferenceStyle.Internal;
            certToken.RequireDerivedKeys = false;
            certToken.X509ReferenceStyle = X509KeyIdentifierClauseType.Any;
            securityBinding.EndpointSupportingTokenParameters.SignedEndorsing.Add(certToken);
            securityBinding.LocalClientSettings.DetectReplays = false;

            binding.Elements.Add(securityBinding);
            binding.Elements.Add(encoding);
            binding.Elements.Add(sslStreamSecurity);

            binding.Elements.Add(httpsTransport);

            /*
             * WSHttpBinding binding = new WSHttpBinding(SecurityMode.TransportWithMessageCredential);
             * WSHttpSecurity security = binding.Security;
             *
             * HttpTransportSecurity transportSecurity = security.Transport;
             * transportSecurity.ClientCredentialType = HttpClientCredentialType.None;
             * transportSecurity.ProxyCredentialType = HttpProxyCredentialType.None;
             * transportSecurity.Realm = "";
             *
             * NonDualMessageSecurityOverHttp messageSecurity = security.Message;
             * messageSecurity.ClientCredentialType = MessageCredentialType.Certificate;
             * messageSecurity.NegotiateServiceCredential = false;
             * messageSecurity.AlgorithmSuite = SecurityAlgorithmSuite.Default;
             */

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(SafeOnlineCertificateValidationCallback);

            string          address       = "https://" + location + "/safe-online-ws/idmapping";
            EndpointAddress remoteAddress = new EndpointAddress(address);

            Binding safeOnlineBinding = new SafeOnlineBinding();

            //this.client = new NameIdentifierMappingPortClient(safeOnlineBinding, remoteAddress);

            //X509Certificate2 certificate = new X509Certificate2("C:\\work\\test.pfx", "secret");

            /*
             * this.client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser,
             *                                                             StoreName.My,
             *                                                             X509FindType.FindBySubjectName,
             *                                                             "Test");
             * this.client.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
             */
            //this.client.Endpoint.Contract.Behaviors.Add(new SignBodyBehavior());
            //this.client.Endpoint.Behaviors.Add(new SafeOnlineMessageInspectorBehavior());

            /*
             * X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
             * store.Open(OpenFlags.ReadOnly);
             * X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySubjectName, "Test", false)[0];
             * this.client.ClientCredentials.ClientCertificate.Certificate = cert;
             */
            //Console.WriteLine("cert: " + this.client.ClientCredentials.ClientCertificate.Certificate);

            ChannelFactory <NameIdentifierMappingPort> channelFactory =
                new ChannelFactory <NameIdentifierMappingPort>(safeOnlineBinding, remoteAddress);

            channelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser,
                                                                        StoreName.My,
                                                                        X509FindType.FindBySubjectName,
                                                                        "Test");

            //channelFactory.Credentials.ClientCertificate.Certificate =
            //channelFactory.Endpoint.Behaviors.Add(new SafeOnlineMessageInspectorBehavior());
            //channelFactory.Endpoint.Contract.Behaviors.Add(new SignBodyBehavior());

            /*
             * Next does not work at all.
             * foreach (OperationDescription operation in channelFactory.Endpoint.Contract.Operations) {
             *      operation.ProtectionLevel = ProtectionLevel.Sign
             *      Console.WriteLine("operation: " + operation.Name);
             * }
             */
            channelFactory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
            this.client = channelFactory.CreateChannel();
        }
Exemple #34
0
    public static void WebSocketHttpsDuplexBinaryStreamed()
    {
        BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = null;
        HttpsTransportBindingElement        httpsTransportBindingElement        = null;
        CustomBinding   binding        = null;
        ClientReceiver  clientReceiver = null;
        InstanceContext context        = null;
        DuplexChannelFactory <IWSDuplexService> channelFactory = null;
        IWSDuplexService     client       = null;
        FlowControlledStream uploadStream = null;

        try
        {
            // *** SETUP *** \\
            binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();
            httpsTransportBindingElement        = new HttpsTransportBindingElement();
            httpsTransportBindingElement.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;
            httpsTransportBindingElement.MaxReceivedMessageSize           = ScenarioTestHelpers.DefaultMaxReceivedMessageSize;
            httpsTransportBindingElement.MaxBufferSize = ScenarioTestHelpers.DefaultMaxReceivedMessageSize;
            httpsTransportBindingElement.TransferMode  = TransferMode.Streamed;
            binding = new CustomBinding(binaryMessageEncodingBindingElement, httpsTransportBindingElement);

            clientReceiver = new ClientReceiver();
            context        = new InstanceContext(clientReceiver);

            channelFactory = new DuplexChannelFactory <IWSDuplexService>(context, binding, Endpoints.WebSocketHttpsDuplexBinaryStreamed_Address);
            client         = channelFactory.CreateChannel();

            // *** EXECUTE *** \\
            using (Stream stream = client.DownloadStream())
            {
                int readResult;
                // Read from the stream, 1000 bytes at a time.
                byte[] buffer = new byte[1000];
                do
                {
                    readResult = stream.Read(buffer, 0, buffer.Length);
                }while (readResult != 0);
            }

            uploadStream = new FlowControlledStream();
            uploadStream.ReadThrottle   = TimeSpan.FromMilliseconds(500);
            uploadStream.StreamDuration = TimeSpan.FromSeconds(1);

            client.UploadStream(uploadStream);
            client.StartPushingStream();
            // Wait for the callback to get invoked before telling the service to stop streaming.
            // This ensures we can read from the stream on the callback while the NCL layer at the service
            // is still writing the bytes from the stream to the wire.
            // This will deadlock if the transfer mode is buffered because the callback will wait for the
            // stream, and the NCL layer will continue to buffer the stream until it reaches the end.

            Assert.True(clientReceiver.ReceiveStreamInvoked.WaitOne(ScenarioTestHelpers.TestTimeout), "Test case timeout was reached while waiting for the stream response from the Service.");
            clientReceiver.ReceiveStreamInvoked.Reset();

            // Upload the stream while we are downloading a different stream
            uploadStream = new FlowControlledStream();
            uploadStream.ReadThrottle   = TimeSpan.FromMilliseconds(500);
            uploadStream.StreamDuration = TimeSpan.FromSeconds(1);
            client.UploadStream(uploadStream);

            client.StopPushingStream();
            // Waiting on ReceiveStreamCompleted from the ClientReceiver.
            clientReceiver.ReceiveStreamCompleted.WaitOne();
            clientReceiver.ReceiveStreamCompleted.Reset();

            // *** VALIDATE *** \\
            // Validation is based on no exceptions being thrown.

            // *** CLEANUP *** \\
            ((ICommunicationObject)client).Close();
            channelFactory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory);
            clientReceiver.Dispose();
        }
    }
        //Comienza el llamado del servicio SOA
        public void BGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //1. Binding agregandole transporte y parametros para ambos servicios
            CustomBinding csBinding = Controlador.ConfiguraServicio.AsignaCustomBinding();

            bkWork.ReportProgress(10);
            //----------------------------------------------------------------------------------------------------------------
            #region LlamaServicioPrototipos
            //2. Asigno URL de endpoint de Protototipos
            EndpointAddress endpointAddressPrototipos = new
                                                        EndpointAddress(Modelo.EncDatosServicio.WsdlPrototipos);

            bkWork.ReportProgress(20);

            //3. Declaro Cliente asignandole binding y URL de prototipo
            soaPrototipos.CatPrototiposPortTypeClient serviceClientProto =
                new soaPrototipos.CatPrototiposPortTypeClient(csBinding, endpointAddressPrototipos);
            bkWork.ReportProgress(30);

            //Autentico mediante credenciales del usuario
            solicitoPrototipos.IP_Address      = Modelo.EncDatosIniciales.Ip;
            solicitoPrototipos.RequestedAccess = "PF_ALTA_VIV";
            solicitoPrototipos.Username        = Modelo.EncDatosIniciales.User;//Usuario Correcto
            solicitoPrototipos.RequestDate     = DateTime.Now;
            solicitoPrototipos.SourceSystem    = "AUTODESK";
            solicitoPrototipos.Version         = "1";
            //-------------------------------------------------------

            //Recibo Datos de Prototipos
            reciboPrototipos = serviceClientProto.GetPrototipos(solicitoPrototipos);
            bkWork.ReportProgress(40);
            #endregion

            #region LlamaServicioFraccionamiento
            //Crea EndPoint de Servicio SOA Fraccionamiento
            EndpointAddress endpointAddressFraccionamiento = new
                                                             EndpointAddress(Modelo.EncDatosServicio.WsdlFraccs);

            //-------------------------------------------------------------------------

            //Instancia Cliente de Servicio SOA Fraccionamiento, solicitud y recepción
            soaFracc.CatFraccionamientosPortTypeClient serviceClientFracc =
                new soaFracc.CatFraccionamientosPortTypeClient(csBinding, endpointAddressFraccionamiento);
            bkWork.ReportProgress(60);
            //-------------------------------------------------------------------------

            //Autentico mediante credenciales del usuario
            solicitoFracc.IP_Address      = Modelo.EncDatosIniciales.Ip;
            solicitoFracc.RequestedAccess = "PF_ALTA_VIV";
            solicitoFracc.Username        = Modelo.EncDatosIniciales.User;
            solicitoFracc.RequestDate     = DateTime.Now;
            solicitoFracc.SourceSystem    = "AUTODESK";
            solicitoFracc.Version         = "1";
            bkWork.ReportProgress(80);
            //------------------------------------------------------------------------

            //Realizo solicitud de datos de Fraccionamientos
            reciboFracc = serviceClientFracc.GetFraccionamientosByUserAndRight(solicitoFracc);
            bkWork.ReportProgress(100);
            //-------------------------------------------------------------------------
            #endregion
        }
        public void Reuse_Binding_With_Different_Contexts()
        { 
            // The same binding can be used across multiple action contexts.

            string name = "p1";
            CustomBinding binding = new CustomBinding(name);

            HttpActionContext ctx1 = new HttpActionContext();
            HttpActionContext ctx2 = new HttpActionContext();

            // Act
            object result1 = "abc";
            binding.SetValue(ctx1, result1);

            object result2 = 123;            
            binding.SetValue(ctx2, result2);

            // Assert
            Assert.Same(result1, binding.GetValue(ctx1));
            Assert.Same(result2, binding.GetValue(ctx2));
        }
Exemple #37
0
    public static void Main()
    {
        AsymmetricSecurityBindingElement sbe =
            new AsymmetricSecurityBindingElement();

        //sbe.SecurityHeaderLayout = SecurityHeaderLayout.Lax;
        //sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
        //sbe.RequireSignatureConfirmation = true;

        //sbe.LocalServiceSettings.DetectReplays = false;
        //sbe.IncludeTimestamp = false;

        sbe.RecipientTokenParameters =
            new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
        sbe.InitiatorTokenParameters =
            new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.AlwaysToRecipient);
        X509SecurityTokenParameters p =
            new X509SecurityTokenParameters(X509KeyIdentifierClauseType.IssuerSerial, SecurityTokenInclusionMode.AlwaysToRecipient);

        p.RequireDerivedKeys = false;
        //sbe.EndpointSupportingTokenParameters.Endorsing.Add (p);
        UserNameSecurityTokenParameters up =
            new UserNameSecurityTokenParameters();

        sbe.EndpointSupportingTokenParameters.Signed.Add(up);
        sbe.SetKeyDerivation(false);
        sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
        ServiceHost host = new ServiceHost(typeof(Foo));
        HttpTransportBindingElement hbe =
            new HttpTransportBindingElement();
        CustomBinding binding = new CustomBinding(sbe, hbe);

        binding.ReceiveTimeout = TimeSpan.FromSeconds(5);
        host.AddServiceEndpoint("IFoo",
                                binding, new Uri("http://localhost:8080"));
        ServiceCredentials cred = new ServiceCredentials();

        cred.ServiceCertificate.Certificate =
            new X509Certificate2("test.pfx", "mono");
        cred.ClientCertificate.Authentication.CertificateValidationMode =
            X509CertificateValidationMode.None;
        cred.UserNameAuthentication.UserNamePasswordValidationMode =
            UserNamePasswordValidationMode.Custom;
        cred.UserNameAuthentication.CustomUserNamePasswordValidator =
            UserNamePasswordValidator.None;
        host.Description.Behaviors.Add(cred);
        host.Description.Behaviors.Find <ServiceDebugBehavior> ()
        .IncludeExceptionDetailInFaults = true;
        foreach (ServiceEndpoint se in host.Description.Endpoints)
        {
            se.Behaviors.Add(new StdErrInspectionBehavior());
        }
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

        smb.HttpGetEnabled = true;
        smb.HttpGetUrl     = new Uri("http://localhost:8080/wsdl");
        host.Description.Behaviors.Add(smb);
        host.Open();
        Console.WriteLine("Hit [CR] key to close ...");
        Console.ReadLine();
        host.Close();
    }