Ejemplo n.º 1
0
        private IRequestChannel CreateChannel(SecuritySessionOperation operation, EndpointAddress target, Uri via)
        {
            IRequestChannel channel;

            if ((operation != SecuritySessionOperation.Issue) && (operation != SecuritySessionOperation.Renew))
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
            }
            IChannelFactory <IRequestChannel> rstChannelFactory = this.rstChannelFactory;

            if (via != null)
            {
                channel = rstChannelFactory.CreateChannel(target, via);
            }
            else
            {
                channel = rstChannelFactory.CreateChannel(target);
            }
            if (this.channelParameters != null)
            {
                this.channelParameters.PropagateChannelParameters(channel);
            }
            if (this.ownCredentialsHandle)
            {
                ChannelParameterCollection property = channel.GetProperty <ChannelParameterCollection>();
                if (property != null)
                {
                    property.Add(new SspiIssuanceChannelParameter(true, this.credentialsHandle));
                }
            }
            return(channel);
        }
Ejemplo n.º 2
0
 protected override IAsyncRequestChannel CreateClientChannel(EndpointAddress target, Uri via)
 {
     if (via != null)
     {
         return(_rstChannelFactory.CreateChannel(target, via));
     }
     else
     {
         return(_rstChannelFactory.CreateChannel(target));
     }
 }
Ejemplo n.º 3
0
        void CreateProxies()
        {
            m_Proxies = new Dictionary <string, IDuplexSessionChannel>();

            foreach (ServiceEndpoint endpoint in Description.Endpoints)
            {
                IDuplexSessionChannel channel = m_Factory.CreateChannel(endpoint.Address);
                channel.Open();

                m_Proxies[endpoint.Contract.Name] = channel;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Henter alle adresser.
        /// </summary>
        /// <returns>Liste af adresser.</returns>
        public IEnumerable <AdresseBase> AdresseGetAll()
        {
            var channel = _channelFactory.CreateChannel <IAdresseRepositoryService>(EndpointConfigurationName);

            try
            {
                // Henter alle adressegrupper.
                var adressegruppeQuery = new AdressegruppeGetAllQuery();
                var adressegruppeViews = channel.AdressegruppeGetAll(adressegruppeQuery);
                // Henter alle betalingsbetingelser.
                var betalingsbetingelseQuery = new BetalingsbetingelseGetAllQuery();
                var betalingsbetingelseViews = channel.BetalingsbetingelseGetAll(betalingsbetingelseQuery);
                // Henter alle firmaadresser.
                var firmaQuery = new FirmaGetAllQuery();
                var firmaViews = channel.FirmaGetAll(firmaQuery);
                // Henter alle personadresser.
                var personQuery = new PersonGetAllQuery();
                var personViews = channel.PersonGetAll(personQuery);
                // Mapper views til adresser.
                lock (SyncRoot)
                {
                    var adresser = new List <AdresseBase>();
                    var adressegruppelisteHelper       = new AdressegruppelisteHelper(_domainObjectBuilder.BuildMany <AdressegruppeView, Adressegruppe>(adressegruppeViews));
                    var betalingsbetingelselisteHelper = new BetalingsbetingelselisteHelper(_domainObjectBuilder.BuildMany <BetalingsbetingelseView, Betalingsbetingelse>(betalingsbetingelseViews));
                    var adresselisteHelper             = new AdresselisteHelper(adresser);
                    _domainObjectBuilder.GetAdressegruppeCallback       = adressegruppelisteHelper.GetById;
                    _domainObjectBuilder.GetBetalingsbetingelseCallback = betalingsbetingelselisteHelper.GetById;
                    _domainObjectBuilder.GetAdresseBaseCallback         = adresselisteHelper.GetById;
                    adresser.AddRange(_domainObjectBuilder.BuildMany <FirmaView, AdresseBase>(firmaViews));
                    adresser.AddRange(_domainObjectBuilder.BuildMany <PersonView, AdresseBase>(personViews));
                    return(adresser.OrderBy(m => m, new AdresseComparer()).ToList());
                }
            }
            catch (IntranetRepositoryException)
            {
                throw;
            }
            catch (FaultException ex)
            {
                throw new IntranetRepositoryException(ex.Message);
            }
            catch (Exception ex)
            {
                throw new IntranetRepositoryException(Resource.GetExceptionMessage(ExceptionMessage.RepositoryError, MethodBase.GetCurrentMethod().Name, ex.Message), ex);
            }
            finally
            {
                ChannelTools.CloseChannel(channel);
            }
        }
Ejemplo n.º 5
0
        public Message ProcessMessaage(Message request)
        {
            ModuleProc      PROC    = new ModuleProc(this.DYN_MODULE_NAME, "ProcessMessage");
            Message         result  = default(Message);
            IRequestChannel channel = null;

            try
            {
                channel = _factory.CreateChannel(this.TargetFinder.GetAddress(request));
                channel.Open();
                result = channel.Request(request);
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
            finally
            {
                if (channel != null && channel.State == CommunicationState.Opened)
                {
                    channel.Close();
                }
            }

            return(result);
        }
Ejemplo n.º 6
0
        public void TestAtBrevhovederHentes()
        {
            var client = _channelFactory.CreateChannel <ICommonService>(ClientEndpointName);

            try
            {
                var query  = new BrevhovederGetQuery();
                var result = client.BrevhovederGet(query);
                Assert.That(result, Is.Not.Null);
                Assert.That(result.Count(), Is.GreaterThan(0));
            }
            finally
            {
                ChannelTools.CloseChannel(client);
            }
        }
        /// <summary>
        /// Henter alle brevhoveder.
        /// </summary>
        /// <returns>Liste af brevhoveder.</returns>
        public IEnumerable <Brevhoved> BrevhovedGetAll()
        {
            IFællesRepositoryService channel = _channelFactory.CreateChannel <IFællesRepositoryService>(EndpointConfigurationName);

            try
            {
                BrevhovedGetAllQuery        query          = new BrevhovedGetAllQuery();
                IEnumerable <BrevhovedView> brevhovedViews = channel.BrevhovedGetAll(query);
                return(_domainObjectBuilder.BuildMany <BrevhovedView, Brevhoved>(brevhovedViews));
            }
            catch (IntranetRepositoryException)
            {
                throw;
            }
            catch (FaultException ex)
            {
                throw new IntranetRepositoryException(ex.Message);
            }
            catch (Exception ex)
            {
                throw new IntranetRepositoryException(Resource.GetExceptionMessage(ExceptionMessage.RepositoryError, MethodBase.GetCurrentMethod().Name, ex.Message), ex);
            }
            finally
            {
                ChannelTools.CloseChannel(channel);
            }
        }
    [Issue(1398, OS = OSID.AnyOSX)] // Cert installation on OSX does not work yet
    public static void IRequestChannel_Https_NetHttpsBinding()
    {
#if FULLXUNIT_NOTSUPPORTED
        bool root_Certificate_Installed = Root_Certificate_Installed();
        bool ssl_Available = SSL_Available();

        if (!root_Certificate_Installed ||
            !ssl_Available)
        {
            Console.WriteLine("---- Test SKIPPED --------------");
            Console.WriteLine("Attempting to run the test in ToF, a ConditionalFact evaluated as FALSE.");
            Console.WriteLine("Root_Certificate_Installed evaluated as {0}", root_Certificate_Installed);
            Console.WriteLine("SSL_Available evaluated as {0}", ssl_Available);
            return;
        }
#endif
        IChannelFactory <IRequestChannel> factory = null;
        IRequestChannel channel      = null;
        Message         replyMessage = null;

        try
        {
            // *** SETUP *** \\
            NetHttpsBinding binding = new NetHttpsBinding(BasicHttpsSecurityMode.Transport);

            // Create the channel factory
            factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection());
            factory.Open();

            // Create the channel.
            channel = factory.CreateChannel(new EndpointAddress(Endpoints.HttpBaseAddress_NetHttps));
            channel.Open();

            // Create the Message object to send to the service.
            Message requestMessage = Message.CreateMessage(
                binding.MessageVersion,
                action,
                new CustomBodyWriter(clientMessage));

            // *** EXECUTE *** \\
            // Send the Message and receive the Response.
            replyMessage = channel.Request(requestMessage);

            // *** VALIDATE *** \\
            var    replyReader      = replyMessage.GetReaderAtBodyContents();
            string actualResponse   = replyReader.ReadElementContentAsString();
            string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply.";
            Assert.Equal(expectedResponse, actualResponse);

            // *** CLEANUP *** \\
            replyMessage.Close();
            channel.Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects(channel, factory);
        }
    }
Ejemplo n.º 9
0
        protected override IAsyncResult OnBeginCreateInstance(SingletonDictionaryManager <string, IRequestSessionChannel> .SingletonContext singletonContext, string key, object loadingContext, TimeSpan timeout, AsyncCallback callback, object state)
        {
            Uri             uri             = new Uri(key);
            EndpointAddress endpointAddress = new EndpointAddress(uri, SbmpProtocolDefaults.GetEndpointIdentity(uri), new AddressHeader[0]);
            IChannelFactory <IRequestSessionChannel> channelFactory = this.defaultChannelFactory;

            if (!this.clientMode && loadingContext != null && loadingContext is bool && (bool)loadingContext)
            {
                channelFactory = this.securedChannelFactory;
            }
            IRequestSessionChannel requestSessionChannel = channelFactory.CreateChannel(endpointAddress);

            requestSessionChannel.SafeAddFaulted((object s, EventArgs e) => {
                this.RaiseNotifyCleanup(uri);
                try
                {
                    base.BeginUnloadInstance(key, null, true, TimeSpan.FromSeconds(10), new AsyncCallback(ContainerChannelManager.UnloadCallback), this);
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }
                    MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteExceptionAsWarning(exception.ToString()));
                }
            });
            return(new CompletedAsyncResult <IRequestSessionChannel>(requestSessionChannel, callback, state));
        }
        public void SendRequestWithoutSignatureMessagePart()
        {
            CustomBinding b = CreateBinding();

            // without ChannelProtectionRequirements it won't be
            // signed and/or encrypted.
            IChannelFactory <IRequestChannel> f =
                b.BuildChannelFactory <IRequestChannel> (new BindingParameterCollection());

            f.Open();
            IRequestChannel ch = f.CreateChannel(CreateX509EndpointAddress("stream:dummy"));

            ch.Open();
            // MessageSecurityException : No signature message parts
            // were specified for messages with the 'myAction'
            // action.
            try
            {
                ch.Request(Message.CreateMessage(b.MessageVersion, "myAction"));
                Assert.Fail("MessageSecurityException is expected here.");
            }
            catch (MessageSecurityException)
            {
            }
        }
Ejemplo n.º 11
0
    public static void Main()
    {
        var b = new BasicHttpBinding();

        b.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
        b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
        var cc = new ClientCredentials();

        cc.UserName.UserName = "******";
        IChannelFactory <IRequestChannel> cf = b.BuildChannelFactory <IRequestChannel> (cc);

        cf.Open();
        IRequestChannel req = cf.CreateChannel(
            new EndpointAddress("http://localhost:8080/"));

        Console.WriteLine(cf.GetProperty <ClientCredentials> ());
        req.Open();
        Message msg = Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IFoo/Echo", new EchoType("hoge"));

        //Message ret = req.Request (msg);
        IAsyncResult result = req.BeginRequest(msg, null, null);
        //return;
        Message ret = req.EndRequest(result);

        using (XmlWriter w = XmlWriter.Create(Console.Out)) {
            ret.WriteMessage(w);
        }
    }
        protected override IRequestChannel OnCreateChannel(EndpointAddress to, Uri via)
        {
            IRequestChannel         innerchannel  = innerChannelFactory.CreateChannel(to, via);
            MessageInspectorChannel clientChannel = new MessageInspectorChannel(this, innerchannel, messageInspector);

            return((IRequestChannel)clientChannel);
        }
Ejemplo n.º 13
0
        protected override IRequestChannel OnCreateChannel(EndpointAddress to, Uri via)
        {
            IRequestChannel     innerchannel  = innerChannelFactory.CreateChannel(to, via);
            CustomHeaderChannel clientChannel = new CustomHeaderChannel(this, innerchannel, m_customHeader);

            return((IRequestChannel)clientChannel);
        }
Ejemplo n.º 14
0
 private static NetworkDetector.ConnectivityStatus CheckTcpConnectivity(Uri baseAddress, out Exception exception)
 {
     NetworkDetector.ConnectivityStatus connectivityStatu = NetworkDetector.ConnectivityStatus.Unavailable;
     exception = null;
     if (!RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTP", false) && !RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTPS", false))
     {
         try
         {
             BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();
             TcpTransportBindingElement          tcpTransportBindingElement          = new TcpTransportBindingElement();
             tcpTransportBindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = 100;
             tcpTransportBindingElement.MaxReceivedMessageSize = (long)65536;
             CustomBinding customBinding = new CustomBinding();
             customBinding.Elements.Add(binaryMessageEncodingBindingElement);
             customBinding.Elements.Add(tcpTransportBindingElement);
             customBinding.OpenTimeout    = TimeSpan.FromSeconds(10);
             customBinding.SendTimeout    = TimeSpan.FromSeconds(10);
             customBinding.ReceiveTimeout = TimeSpan.MaxValue;
             int num = 9350;
             Uri uri = ServiceBusUriHelper.CreateServiceUri("net.tcp", string.Concat(baseAddress.DnsSafeHost, ":", num.ToString(CultureInfo.InvariantCulture)), "/");
             IChannelFactory <IDuplexSessionChannel> channelFactory = null;
             IDuplexSessionChannel duplexSessionChannel             = null;
             try
             {
                 channelFactory = customBinding.BuildChannelFactory <IDuplexSessionChannel>(new object[0]);
                 channelFactory.Open();
                 duplexSessionChannel = channelFactory.CreateChannel(new EndpointAddress(uri, new AddressHeader[0]));
                 duplexSessionChannel.Open();
                 Message message = Message.CreateMessage(MessageVersion.Default, "http://schemas.microsoft.com/netservices/2009/05/servicebus/connect/OnewayPing", new OnewayPingMessage());
                 duplexSessionChannel.Send(message, customBinding.SendTimeout);
                 duplexSessionChannel.Close();
                 duplexSessionChannel = null;
                 channelFactory.Close();
                 channelFactory = null;
             }
             finally
             {
                 if (duplexSessionChannel != null)
                 {
                     duplexSessionChannel.Abort();
                 }
                 if (channelFactory != null)
                 {
                     channelFactory.Abort();
                 }
             }
             connectivityStatu = NetworkDetector.ConnectivityStatus.Available;
         }
         catch (CommunicationException communicationException)
         {
             exception = communicationException;
         }
         catch (TimeoutException timeoutException)
         {
             exception = timeoutException;
         }
     }
     NetworkDetector.LogResult(baseAddress, "Tcp", connectivityStatu);
     return(connectivityStatu);
 }
Ejemplo n.º 15
0
 public DefaultConnector(IChannelFactory channelFactory, IdleStateMonitor idleStateMonitor, IHandshakeHandler handshakeHandler)
 {
     this.channel          = channelFactory.CreateChannel();
     this.handshakeHandler = handshakeHandler;
     this.idleStateMonitor = idleStateMonitor ?? new IdleStateMonitor(TimeSpan.FromSeconds(30.0));
     this.idleStateMonitor.IdleStateChanged += OnIdleStateChanged;
 }
Ejemplo n.º 16
0
        private void CreateAndAttachEvents()
        {
            ExecutionLog.Info("Opening the channel ...");
            _channel = _channelFactory.CreateChannel();
            ExecutionLog.Info($"Channel opened with channelNumber: {_channel.ChannelNumber}. MaxAllowedTimeBetweenMessages={_maxTimeBetweenMessages.TotalSeconds}s.");
            var declareResult = _channel.QueueDeclare();

            foreach (var routingKey in _routingKeys)
            {
                ExecutionLog.Info($"Binding queue={declareResult.QueueName} with routingKey={routingKey}");
                _channel.QueueBind(declareResult.QueueName, "unifiedfeed", routingKey);
            }

            var interestName = _interest == null ? "system" : _interest.Name;

            _channel.ModelShutdown += ChannelOnModelShutdown;
            _consumer             = new EventingBasicConsumer(_channel);
            _consumer.ConsumerTag = $"UfSdk-Net|{SdkInfo.GetVersion()}|{interestName}|{_channel.ChannelNumber}|{DateTime.Now:yyyyMMdd-HHmmss}";
            _consumer.Received   += ConsumerOnDataReceived;
            _consumer.Shutdown   += ConsumerOnShutdown;
            _channel.BasicConsume(declareResult.QueueName, true, _consumer.ConsumerTag, _consumer);

            _lastMessageReceived = DateTime.MinValue;
            _channelStarted      = DateTime.Now;
        }
Ejemplo n.º 17
0
        public static void Snippet3()
        {
            // <Snippet3>
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            Object[] bindingParams = new Object[2];

            // <Snippet30>
            IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(bindingParams);

            factory.Open();
            EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp");
            IRequestChannel channel = factory.CreateChannel(address);

            channel.Open();
            // </Snippet30>

            Message request = Message.CreateMessage(MessageVersion.Default, "hello");
            Message reply   = channel.Request(request);

            Console.Out.WriteLine(reply.Headers.Action);
            reply.Close();
            channel.Close();
            factory.Close();
            // </Snippet3>
        }
Ejemplo n.º 18
0
    public static void Main()
    {
        HttpTransportBindingElement el =
            new HttpTransportBindingElement();
        IChannelFactory <IRequestChannel> factory =
            el.BuildChannelFactory <IRequestChannel> (
                new BindingContext(new CustomBinding(),
                                   new BindingParameterCollection()));

        factory.Open();

        IRequestChannel request = factory.CreateChannel(
            new EndpointAddress("http://localhost:37564"));

        request.Open();

        using (XmlWriter w = XmlWriter.Create(Console.Out)) {
            Message.CreateMessage(MessageVersion.Default, "Echo")
            .WriteMessage(w);
        }
        Console.WriteLine();

        Message msg = request.Request(
            Message.CreateMessage(MessageVersion.Default, "Echo"),
            TimeSpan.FromSeconds(15));

        using (XmlWriter w = XmlWriter.Create(Console.Out)) {
            msg.WriteMessage(w);
        }
    }
Ejemplo n.º 19
0
        public void WireUpContextFeatures <TMessageContext>(TMessageContext context, IRawConsumer consumer, BasicDeliverEventArgs args) where TMessageContext : IMessageContext
        {
            var advancedCtx = context as IAdvancedMessageContext;

            if (advancedCtx == null)
            {
                return;
            }

            advancedCtx.Nack = () =>
            {
                consumer.AcknowledgedTags.Add(args.DeliveryTag);
                consumer.Model.BasicNack(args.DeliveryTag, false, true);
            };

            advancedCtx.RetryLater = timespan =>
            {
                var dlxName     = _conventions.RetryLaterExchangeConvention(timespan);
                var dlQueueName = _conventions.RetryLaterExchangeConvention(timespan);
                var channel     = _channelFactory.CreateChannel();
                channel.ExchangeDeclare(dlxName, ExchangeType.Direct, true, true, null);
                channel.QueueDeclare(dlQueueName, true, false, true, new Dictionary <string, object>
                {
                    { QueueArgument.DeadLetterExchange, args.Exchange },
                    { QueueArgument.Expires, Convert.ToInt32(timespan.Add(TimeSpan.FromSeconds(1)).TotalMilliseconds) },
                    { QueueArgument.MessageTtl, Convert.ToInt32(timespan.TotalMilliseconds) }
                });
                channel.QueueBind(dlQueueName, dlxName, args.RoutingKey, null);
                UpdateHeaders(args.BasicProperties);
                channel.BasicPublish(dlxName, args.RoutingKey, args.BasicProperties, args.Body);
                channel.QueueUnbind(dlQueueName, dlxName, args.RoutingKey, null);
            };

            advancedCtx.RetryInfo = GetRetryInformatino(args.BasicProperties);
        }
Ejemplo n.º 20
0
 //入口方法
 static void Main(string[] args)
 {
     try
     {
         NetTcpBinding binding = new NetTcpBinding();
         using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body"))
         {
             //创建ChannelFactory
             IChannelFactory <IDuplexChannel> factory = binding.BuildChannelFactory <IDuplexChannel>(new BindingParameterCollection());
             factory.Open();
             //这里创建IRequestChannel
             IDuplexChannel duplexChannel = factory.CreateChannel(new EndpointAddress("net.tcp://localhost:9090/DuplexService/Point2"));
             duplexChannel.Open();
             //发送消息
             duplexChannel.Send(message);
             Console.WriteLine("已经成功发送消息!");
             //var msg = duplexChannel.Receive();
             //Console.WriteLine($"收到消息:{msg.GetBody<string>()}");
             duplexChannel.Close();
             factory.Close();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Ejemplo n.º 21
0
 //入口方法
 static void Main(string[] args)
 {
     try
     {
         //建立自定义的通道栈
         BindingElement[] bindingElements = new BindingElement[2];
         bindingElements[0] = new TextMessageEncodingBindingElement();
         bindingElements[1] = new HttpTransportBindingElement();
         CustomBinding binding = new CustomBinding(bindingElements);
         using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body"))
         {
             //创建ChannelFactory
             IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection());
             factory.Open();
             //这里创建IRequestChannel
             IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost/RequestReplyService"));
             requestChannel.Open();
             //发送消息
             Message response = requestChannel.Request(message);
             Console.WriteLine("已经成功发送消息!");
             //查看返回消息
             Console.WriteLine("接受到一条返回消息,action为:{0},body为:{1}", response.Headers.Action, response.GetBody <String>());
             requestChannel.Close();
             factory.Close();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Ejemplo n.º 22
0
        public void Open(IEnumerable <string> routingKeys)
        {
            if (Interlocked.CompareExchange(ref _isOpened, 1, 0) != 0)
            {
                ExecutionLog.Error("Opening an already opened channel is not allowed");
                throw new InvalidOperationException("The instance is already opened");
            }

            Guard.Argument(routingKeys, nameof(routingKeys)).NotNull();//.NotEmpty();
            if (!routingKeys.Any())
            {
                throw new ArgumentOutOfRangeException(nameof(routingKeys));
            }

            _channel = _channelFactory.CreateChannel();
            ExecutionLog.Info($"Opening the channel with channelNumber: {_channel.ChannelNumber}.");
            var declareResult = _channel.QueueDeclare();

            foreach (var routingKey in routingKeys)
            {
                ExecutionLog.Info($"Binding queue={declareResult.QueueName} with routingKey={routingKey}");
                _channel.QueueBind(declareResult.QueueName, "unifiedfeed", routingKey);
            }

            _channel.ModelShutdown += ChannelOnModelShutdown;

            _consumer           = new EventingBasicConsumer(_channel);
            _consumer.Received += OnDataReceived;
            _consumer.Shutdown += ConsumerOnShutdown;
            _channel.BasicConsume(declareResult.QueueName, true, _consumer);
        }
Ejemplo n.º 23
0
        public void Listen(string connectionId)
        {
            Task.Run(() =>
            {
                _successChannel = _channelFactory.CreateChannel();
                _successChannel.SubscribeToExchange(RabbitMqRoutingConfiguration.SuccessExchange, connectionId, ConsumerOnSuccess);
                SuccessSubscriptions.TryAdd(connectionId, _successChannel);
            });

            Task.Run(() =>
            {
                _errorChannel = _channelFactory.CreateChannel();
                _errorChannel.SubscribeToExchange(RabbitMqRoutingConfiguration.ErrorExchange, connectionId, ConsumerOnError);
                ErrorSubscriptions.TryAdd(connectionId, _errorChannel);
            });
        }
Ejemplo n.º 24
0
        void RunTest()
        {
            listener.Open();
            Thread thread = new Thread(ServerThread);

            thread.Start(this);

            CustomBinding binding = new CustomBinding(new WseTcpTransportBindingElement());
            IChannelFactory <IDuplexSessionChannel> channelFactory = binding.BuildChannelFactory <IDuplexSessionChannel>();

            channelFactory.Open();
            IDuplexSessionChannel channel = channelFactory.CreateChannel(new EndpointAddress(this.uri));
            Message requestMessage;

            channel.Open();
            requestMessage = Message.CreateMessage(binding.MessageVersion, "http://SayHello", "to you.");
            channel.Send(requestMessage);
            Message hello = channel.Receive();

            using (hello)
            {
                Console.WriteLine(hello.GetBody <string>());
            }
            Console.WriteLine("Press enter.");
            Console.ReadLine();
            requestMessage = Message.CreateMessage(binding.MessageVersion, "http://NotHello", "to me.");
            channel.Send(requestMessage);
            channel.Close();
            thread.Join();

            channelFactory.Close();
            listener.Close();
            Console.WriteLine("Press enter.");
            Console.ReadLine();
        }
Ejemplo n.º 25
0
        private static TService CreateService(string baseUrl, IChannelFactory <TService> factory, ChannelEndpointElement endPoint)
        {
            var address    = endPoint.Address.AbsoluteUri;
            var serviceUri = address.Replace("domain", baseUrl);

            return(factory.CreateChannel(new EndpointAddress(serviceUri)));
        }
        public void OpenRequestNonAuthenticatable()
        {
            SymmetricSecurityBindingElement sbe =
                new SymmetricSecurityBindingElement();

            sbe.ProtectionTokenParameters =
                new UserNameSecurityTokenParameters();
            Binding binding = new CustomBinding(sbe, new HandlerTransportBindingElement(null));
            BindingParameterCollection pl =
                new BindingParameterCollection();
            ClientCredentials cred = new ClientCredentials();

            cred.UserName.UserName = "******";
            pl.Add(cred);
            IChannelFactory <IRequestChannel> f =
                binding.BuildChannelFactory <IRequestChannel> (pl);

            f.Open();
            IRequestChannel ch = f.CreateChannel(new EndpointAddress("stream:dummy"));

            try {
                ch.Open();
                Assert.Fail("NotSupportedException is expected.");
            } catch (NotSupportedException) {
            }
        }
Ejemplo n.º 27
0
 static void Main(string[] args)
 {
     try
     {        //使用说明先启动input,然后在启动启动output。
         //记得使用管理员启动VS,我在程序清单中添加了管理员权限。
         //创建自定义通道
         BindingElement[] bindingElements = new BindingElement[2];
         bindingElements[0] = new TextMessageEncodingBindingElement(); //文本编码
         bindingElements[1] = new HttpTransportBindingElement();       //Htp传输
         CustomBinding binding = new CustomBinding(bindingElements);
         using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body"))
         {
             //创建ChannelFactory request 请求 reply回复
             IChannelFactory <IRequestChannel> factory = binding.BuildChannelFactory <IRequestChannel>(new BindingParameterCollection());
             factory.Open();        //打开ChannelFactory
                                    //这里创建IRequestChannel
             IRequestChannel requestChannel = factory.CreateChannel(new System.ServiceModel.EndpointAddress("http://localhost:9090/RequestReplyService"));
             requestChannel.Open(); //打开通道
             Message response = requestChannel.Request(message);
             //发送消息
             Console.WriteLine("已经成功发送消息!");
             //查看返回消息
             Console.WriteLine($"接收到一条返回消息,action为:{response.Headers.Action},body为{response.GetBody<String>()}");
             requestChannel.Close(); //关闭通道
             factory.Close();        //关闭工厂
         }
     }
     catch (Exception ex)
     { Console.WriteLine(ex.ToString()); }
     finally
     {
         Console.Read();
     }
 }
Ejemplo n.º 28
0
 //入口方法
 static void Main(string[] args)
 {
     try
     {
         //建立自定义的通道栈
         BindingElement[] bindingElements = new BindingElement[3];
         bindingElements[0] = new TextMessageEncodingBindingElement();
         //OneWayBindingElement可以使得传输通道支持数据报模式
         bindingElements[1] = new OneWayBindingElement();
         bindingElements[2] = new HttpTransportBindingElement();
         CustomBinding binding = new CustomBinding(bindingElements);
         using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body"))
         {
             //创建ChannelFactory
             IChannelFactory <IOutputChannel> factory = binding.BuildChannelFactory <IOutputChannel>(new BindingParameterCollection());
             factory.Open();
             //这里创建IOutputChannel
             IOutputChannel outputChannel = factory.CreateChannel(new EndpointAddress("http://localhost/InputService"));
             outputChannel.Open();
             //发送消息
             outputChannel.Send(message);
             Console.WriteLine("已经成功发送消息!");
             outputChannel.Close();
             factory.Close();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Ejemplo n.º 29
0
        public MainWindow()
        {
            InitializeComponent();
            var ender = new EndpointAddress(MyEndpoint);
            bindbert.MaxReceivedMessageSize = 2147483647;
            bindbert.MaxBufferSize = 2147483647;

            MyScanneriChannel = new ChannelFactory<ScannerEngine.ScannerInterfaceDefinition>(bindbert);
            
            Trycorder = MyScanneriChannel.CreateChannel(ender);



            StartWCFService();
            var teststate = host.State;
            
            Trycorder.Initialize();
            BuildProfileMenuList();
            BuildRegionMenuList();
            BuildComponentMenuList();
            ConfigureComponentSelectComboBox();

            ///Get a timer to update status on UI.
            /// 
            DispatcherTimer UpdateStatusTimer = new DispatcherTimer();
            UpdateStatusTimer.Tick += new EventHandler(updateStatusTimer_Tick);
            UpdateStatusTimer.Interval = new TimeSpan(0, 0, 5);
            UpdateStatusTimer.Start();


        }
Ejemplo n.º 30
0
        public GuestHandleFactory(IChannelFactory channelFactory)
        {
            ISerializer serializer = new ProtobufSerializer();
            IChannel channel = channelFactory.CreateChannel();

            // todo1[ak] check args
            _requester = new Requester(serializer, channel);
        }
Ejemplo n.º 31
0
		protected override TChannel OnCreateChannel (EndpointAddress address, Uri uri)
		{
			if (typeof (TChannel) == typeof (IRequestChannel))
				return (TChannel) (object) new InterceptorRequestChannel (
					(InterceptorChannelFactory<IRequestChannel>) (object) this,
					(IRequestChannel) (object) inner.CreateChannel (address, uri));
			throw new NotImplementedException ();
		}
        private void CreateAndAttachEvents()
        {
            _channel = _channelFactory.CreateChannel();
            ExecutionLog.LogInformation($"Channel opened with channelNumber: {_channel.ChannelNumber}.");
            var declareResult = _channel.QueueDeclare();

            foreach (var routingKey in _routingKeys)
            {
                ExecutionLog.LogInformation($"Binding queue={declareResult.QueueName} with routingKey={routingKey}");
                _channel.QueueBind(declareResult.QueueName, "unifiedfeed", routingKey);
            }

            _channel.ModelShutdown += ChannelOnModelShutdown;
            _consumer           = new EventingBasicConsumer(_channel);
            _consumer.Received += ConsumerOnDataReceived;
            _consumer.Shutdown += ConsumerOnShutdown;
            _channel.BasicConsume(declareResult.QueueName, true, _consumer);
        }
Ejemplo n.º 33
0
        public void TestInitialize()
        {
            _ev = new ManualResetEvent(false);

            const string clientAddress = "amqp://localhost/amq.direct?routingKey=NoSuchRoute";

            _binding = new RabbitMQBinding
                {
                    OneWayOnly = true,
                    ApplicationId = "MyApp",
                    Mandatory = true
                };

            _channelFactory = _binding.BuildChannelFactory<IOutputChannel>(this);

            _channelFactory.Open();

            _outputChannel = _channelFactory.CreateChannel(new EndpointAddress(clientAddress)) as RabbitMQTransportOutputChannel;

            _outputChannel.Open();
        }