Example #1
0
        public void SendMessageToUnknownReceiver()
        {
            var endpointId   = new EndpointId("id");
            var endpointInfo = new ProtocolInformation(
                ProtocolVersions.V1,
                new Uri("http://localhost/messages"),
                new Uri("http://localhost/data"));

            var msg          = new EndpointDisconnectMessage(endpointId);
            var messageProxy = new Mock <IMessageSendingEndpoint>();
            {
                messageProxy.Setup(p => p.Send(It.IsAny <ICommunicationMessage>(), It.IsAny <int>()))
                .Callback <ICommunicationMessage, int>((input, retries) => Assert.AreSame(msg, input));
            }

            var dataProxy = new Mock <IDataTransferingEndpoint>();
            {
                dataProxy.Setup(p => p.Send(It.IsAny <DataTransferMessage>(), It.IsAny <int>()))
                .Verifiable();
            }

            var localEndpoint = new EndpointId("local");
            Func <ProtocolInformation, IMessageSendingEndpoint>  builder     = id => messageProxy.Object;
            Func <ProtocolInformation, IDataTransferingEndpoint> dataBuilder = id => dataProxy.Object;
            var sender = new SendingEndpoint(localEndpoint, builder, dataBuilder);

            sender.Send(endpointInfo, msg, 1);
            Assert.AreEqual(1, sender.KnownEndpoints().Count());
            dataProxy.Verify(p => p.Send(It.IsAny <DataTransferMessage>(), It.IsAny <int>()), Times.Never());
        }
Example #2
0
        public void CloseChannelTo()
        {
            var endpointId   = new EndpointId("id");
            var endpointInfo = new ProtocolInformation(
                ProtocolVersions.V1,
                new Uri("http://localhost/messages"),
                new Uri("http://localhost/data"));
            var msg               = new EndpointDisconnectMessage(endpointId);
            var messageProxy      = new Mock <IMessageSendingEndpoint>();
            var messageDisposable = messageProxy.As <IDisposable>();

            var dataProxy      = new Mock <IDataTransferingEndpoint>();
            var dataDisposable = dataProxy.As <IDisposable>();

            var localEndpoint = new EndpointId("local");
            Func <ProtocolInformation, IMessageSendingEndpoint>  messageBuilder = id => messageProxy.Object;
            Func <ProtocolInformation, IDataTransferingEndpoint> dataBuilder    = id => dataProxy.Object;
            var sender = new SendingEndpoint(localEndpoint, messageBuilder, dataBuilder);

            sender.Send(endpointInfo, msg, 1);
            Assert.AreEqual(1, sender.KnownEndpoints().Count());

            sender.CloseChannelTo(endpointInfo);
            Assert.AreEqual(0, sender.KnownEndpoints().Count());
        }
        public void FromMessage()
        {
            var translator = new EndpointDisconnectConverter();

            var msg  = new EndpointDisconnectMessage(new EndpointId("a"), "b");
            var data = translator.FromMessage(msg);

            Assert.IsInstanceOf(typeof(EndpointDisconnectData), data);
            Assert.AreSame(msg.Id, data.Id);
            Assert.AreSame(msg.Sender, data.Sender);
            Assert.AreSame(msg.InResponseTo, data.InResponseTo);
            Assert.AreSame(msg.ClosingReason, ((EndpointDisconnectData)data).DisconnectReason);
        }
        public void Invoke()
        {
            var endpoint        = new EndpointId("a");
            var endpointStorage = new Mock <IStoreEndpointApprovalState>();
            {
                endpointStorage.Setup(e => e.TryRemoveEndpoint(It.IsAny <EndpointId>()))
                .Callback <EndpointId>(e => Assert.AreSame(endpoint, e))
                .Returns(true)
                .Verifiable();
            }

            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var action = new EndpointDisconnectProcessAction(endpointStorage.Object, systemDiagnostics);

            var disconnectMsg = new EndpointDisconnectMessage(endpoint);

            action.Invoke(disconnectMsg);

            endpointStorage.Verify(e => e.TryRemoveEndpoint(It.IsAny <EndpointId>()), Times.Once());
        }
Example #5
0
        public void EndpointDisconnectedWithOpenConnection()
        {
            var id           = new EndpointId("a");
            var endpointInfo = new ProtocolInformation(
                ProtocolVersions.V1,
                new Uri("http://localhost/messages"),
                new Uri("http://localhost/data"));
            var template = new Mock <IProtocolChannelTemplate>();

            var messageUri = new Uri("http://localhost/messages/invalid");
            var dataUri    = new Uri("http://localhost/data/invalid");
            var host       = new Mock <IHoldServiceConnections>();
            {
                host.Setup(
                    h =>
                    h.OpenChannel(
                        It.IsAny <IReceiveInformationFromRemoteEndpoints>(),
                        It.IsAny <Func <ServiceHost, ServiceEndpoint> >()))
                .Returns <IReceiveInformationFromRemoteEndpoints, Func <ServiceHost, ServiceEndpoint> >(
                    (r, f) => r is IMessagePipe ? messageUri : dataUri)
                .Verifiable();
                host.Setup(h => h.CloseConnection())
                .Verifiable();
            }

            Func <IHoldServiceConnections> hostBuilder = () => host.Object;

            var messagePipe = new Mock <IMessagePipe>();
            Func <Version, Tuple <Type, IMessagePipe> > messageReceiverBuilder =
                version => new Tuple <Type, IMessagePipe>(typeof(IMessagePipe), messagePipe.Object);

            var dataPipe = new Mock <IDataPipe>();
            Func <Version, Tuple <Type, IDataPipe> > dataReceiverBuilder =
                version => new Tuple <Type, IDataPipe>(typeof(IDataPipe), dataPipe.Object);

            var msg             = new EndpointDisconnectMessage(id);
            var sendingEndpoint = new Mock <ISendingEndpoint>();
            {
                sendingEndpoint.Setup(e => e.KnownEndpoints())
                .Returns(new[] { endpointInfo });
                sendingEndpoint.Setup(e => e.CloseChannelTo(It.IsAny <ProtocolInformation>()))
                .Verifiable();
                sendingEndpoint.Setup(e => e.Send(It.IsAny <ProtocolInformation>(), It.IsAny <ICommunicationMessage>(), It.IsAny <int>()))
                .Callback <ProtocolInformation, ICommunicationMessage, int>(
                    (e, m, t) => Assert.IsInstanceOf(typeof(EndpointDisconnectMessage), m))
                .Verifiable();
            }

            BuildSendingEndpoint senderBuilder = (endpoint, builder, endpointBuilder) => sendingEndpoint.Object;

            var messageEndpoint = new Mock <IMessageSendingEndpoint>();
            Func <Version, Uri, IMessageSendingEndpoint> versionedMessageSenderBuilder = (version, uri) => messageEndpoint.Object;

            var dataEndpoint = new Mock <IDataTransferingEndpoint>();
            Func <Version, Uri, IDataTransferingEndpoint> versionedDataSenderBuilder = (version, uri) => dataEndpoint.Object;

            var channel = new ProtocolChannel(
                id,
                template.Object,
                hostBuilder,
                messageReceiverBuilder,
                dataReceiverBuilder,
                senderBuilder,
                versionedMessageSenderBuilder,
                versionedDataSenderBuilder);

            channel.OpenChannel();
            var protocols = channel.LocalConnectionPoints().ToList();

            Assert.AreEqual(1, protocols.Count());

            channel.Send(endpointInfo, msg, 1);
            sendingEndpoint.Verify(e => e.Send(It.IsAny <ProtocolInformation>(), It.IsAny <ICommunicationMessage>(), It.IsAny <int>()), Times.Once());

            host.Verify(
                h => h.OpenChannel(It.IsAny <IReceiveInformationFromRemoteEndpoints>(), It.IsAny <Func <ServiceHost, ServiceEndpoint> >()),
                Times.Exactly(2));

            channel.EndpointDisconnected(endpointInfo);
            sendingEndpoint.Verify(s => s.CloseChannelTo(It.IsAny <ProtocolInformation>()), Times.Once());
        }
        private void CloseChannel(Version version)
        {
            lock (m_Lock)
            {
                if (m_SendingEndpoints.ContainsKey(version))
                {
                    var sender = m_SendingEndpoints[version];
                    m_SendingEndpoints.Remove(version);

                    // First notify the recipients that we're closing the channel.
                    var knownEndpoints = new List <ProtocolInformation>(sender.KnownEndpoints());
                    foreach (var key in knownEndpoints)
                    {
                        var msg = new EndpointDisconnectMessage(m_Id);
                        try
                        {
                            // Don't bother retrying this many times because we're about to go away. If the other
                            // side isn't there, they won't care we're not there.
                            sender.Send(key, msg, 1);
                        }
                        catch (FailedToSendMessageException)
                        {
                            // For some reason the message didn't arrive. Honestly we don't
                            // care, we're about to quit, not our problem anymore.
                        }
                    }

                    // Then close the channel. We'll do this in a different
                    // loop to give the channels time to process the messages.
                    foreach (var key in knownEndpoints)
                    {
                        sender.CloseChannelTo(key);
                    }
                }

                if (m_MessageHostsByVersion.ContainsKey(version))
                {
                    var host = m_MessageHostsByVersion[version];
                    m_MessageHostsByVersion.Remove(version);
                    host.CloseConnection();
                }

                if (m_MessagePipesByVersion.ContainsKey(version))
                {
                    var pair = m_MessagePipesByVersion[version];
                    m_MessagePipesByVersion.Remove(version);
                    pair.Item1.OnNewMessage -= pair.Item2;
                }

                if (m_DataHostsByVersion.ContainsKey(version))
                {
                    var host = m_DataHostsByVersion[version];
                    m_DataHostsByVersion.Remove(version);
                    host.CloseConnection();
                }

                if (m_DataPipesByVersion.ContainsKey(version))
                {
                    var pair = m_DataPipesByVersion[version];
                    m_DataPipesByVersion.Remove(version);
                    pair.Item1.OnNewData -= pair.Item2;
                }

                m_LocalConnectionPoints.RemoveAll(c => c.Version.Equals(version));
            }
        }
Example #7
0
        public void SendWithNoChannel()
        {
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
            var endpointId        = new EndpointId("id");
            var msg = new EndpointDisconnectMessage(endpointId);

            var  autoReset      = new AutoResetEvent(false);
            bool hasBeenInvoked = false;
            Func <IStoreV1CommunicationData, MessageReceptionConfirmation> handler =
                s =>
            {
                hasBeenInvoked = true;
                autoReset.Set();
                Assert.AreEqual(endpointId, s.Sender);
                return(new MessageReceptionConfirmation
                {
                    WasDataReceived = true,
                });
            };
            var receiver = new MockMessageReceivingEndpoint(handler);

            var uri  = new Uri("net.pipe://localhost/test/pipe");
            var host = new ServiceHost(receiver, uri);

            host.Faulted += (s, e) => Assert.Fail();

            var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
            {
                TransferMode = TransferMode.Buffered,
            };

            var address        = string.Format("{0}_{1}", "ThroughNamedPipe", Process.GetCurrentProcess().Id);
            var remoteEndpoint = host.AddServiceEndpoint(typeof(IMessageReceivingEndpoint), binding, address);

            foreach (var operation in remoteEndpoint.Contract.Operations)
            {
                var behavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (behavior == null)
                {
                    behavior = new DataContractSerializerOperationBehavior(operation);
                    operation.Behaviors.Add(behavior);
                }

                behavior.DataContractResolver = new ProtocolDataContractResolver();
            }

            host.Open();
            try
            {
                var configuration = new Mock <IConfiguration>();
                {
                    configuration.Setup(c => c.HasValueFor(It.IsAny <ConfigurationKey>()))
                    .Returns(false);
                }

                var localAddress = string.Format("{0}/{1}", uri.OriginalString, address);
                var template     = new NamedPipeProtocolChannelTemplate(configuration.Object, new ProtocolDataContractResolver());
                var sender       = new RestoringMessageSendingEndpoint(
                    new Uri(localAddress),
                    template,
                    new ProtocolDataContractResolver(),
                    new IConvertCommunicationMessages[]
                {
                    new EndpointDisconnectConverter(),
                },
                    systemDiagnostics);

                sender.Send(msg, 1);

                autoReset.WaitOne(500);
                Assert.IsTrue(hasBeenInvoked);
            }
            finally
            {
                host.Close();
            }
        }
Example #8
0
        public void SendWithFailureOnRetry()
        {
            var count             = 0;
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
            var endpointId        = new EndpointId("id");
            var msg = new EndpointDisconnectMessage(endpointId);

            Func <IStoreV1CommunicationData, MessageReceptionConfirmation> handler =
                s =>
            {
                count++;
                throw new Exception("Lets bail the first one");
            };
            var receiver = new MockMessageReceivingEndpoint(handler);

            var uri  = new Uri("net.pipe://localhost/test/pipe");
            var host = new ServiceHost(receiver, uri);

            var binding        = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
            var address        = string.Format("{0}_{1}", "ThroughNamedPipe", Process.GetCurrentProcess().Id);
            var remoteEndpoint = host.AddServiceEndpoint(typeof(IMessageReceivingEndpoint), binding, address);

            foreach (var operation in remoteEndpoint.Contract.Operations)
            {
                var behavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (behavior == null)
                {
                    behavior = new DataContractSerializerOperationBehavior(operation);
                    operation.Behaviors.Add(behavior);
                }

                behavior.DataContractResolver = new ProtocolDataContractResolver();
            }

            host.Open();
            try
            {
                var configuration = new Mock <IConfiguration>();
                {
                    configuration.Setup(c => c.HasValueFor(It.IsAny <ConfigurationKey>()))
                    .Returns(false);
                }

                var localAddress = string.Format("{0}/{1}", uri.OriginalString, address);
                var template     = new NamedPipeProtocolChannelTemplate(configuration.Object, new ProtocolDataContractResolver());
                var sender       = new RestoringMessageSendingEndpoint(
                    new Uri(localAddress),
                    template,
                    new ProtocolDataContractResolver(),
                    new IConvertCommunicationMessages[]
                {
                    new EndpointDisconnectConverter(),
                },
                    systemDiagnostics);

                // This message should fault the channel
                Assert.Throws <FailedToSendMessageException>(() => sender.Send(msg, 2));
                Assert.AreEqual(2, count);
            }
            finally
            {
                host.Close();
            }
        }