public void Send_Synchronous_DelayedReply()
        {
            var message = CreateMessage();

            // make first one time out
            try
            {
                RunAndHandleMessagingException(Client.SendAndWaitAsync(Logger, message), EventIds.SynchronousCallTimeout);
            }
            catch (MessagingException)             // ignore timeout
            {
            }

            // then we post the message
            var mockMessage = CreateMockMessage(message);

            mockMessage.To      = MockFactory.Helsenorge.SynchronousReply.Name;
            mockMessage.ReplyTo = MockFactory.OtherParty.Synchronous.Name;
            mockMessage.Queue   = MockFactory.Helsenorge.SynchronousReply.Messages;
            MockFactory.Helsenorge.SynchronousReply.Messages.Add(mockMessage);

            try
            {
                System.Threading.Thread.Sleep(1000);
                // then we post a new one, and this causes the previous one to have timed out
                message = CreateMessage();
                RunAndHandleMessagingException(Client.SendAndWaitAsync(Logger, message), EventIds.SynchronousCallTimeout);
            }
            catch (MessagingException)            // ignore timeout
            {
            }
            // make sure it's logged
            Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.SynchronousCallDelayed));
        }
Esempio n. 2
0
        public void Asynchronous_Receive_CertificateSignError()
        {
            Exception receiveException = null;

            Client = new MessagingClient(Settings, CollaborationRegistry, AddressRegistry)
            {
                DefaultMessageProtection    = new SignThenEncryptMessageProtection(), // disable protection for most tests
                DefaultCertificateValidator = CertificateValidator
            };
            Client.ServiceBus.RegisterAlternateMessagingFactory(MockFactory);

            Server = new MessagingServer(Settings, Logger, LoggerFactory, CollaborationRegistry, AddressRegistry)
            {
                DefaultMessageProtection    = new SignThenEncryptMessageProtection(), // disable protection for most tests
                DefaultCertificateValidator = CertificateValidator
            };
            Server.ServiceBus.RegisterAlternateMessagingFactory(MockFactory);

            CollaborationRegistry.SetupFindAgreementForCounterparty(i =>
            {
                var file = Path.Combine("Files", $"CPA_{i}_ChangedSignedCertificate.xml");
                return(File.Exists(file) == false ? null : File.ReadAllText(file));
            });

            RunAsynchronousReceive(
                postValidation: () => {
                Assert.IsTrue(_startingCalled);
                Assert.IsFalse(_receivedCalled);
                Assert.IsTrue(_completedCalled);
                var error = MockLoggerProvider.FindEntry(EventIds.RemoteCertificate);
                Assert.IsTrue(error.Message
                              .Contains($"{TestCertificates.HelsenorgePrivateSigntature.Thumbprint}"));
                Assert.IsTrue(error.Message
                              .Contains($"{TestCertificates.HelsenorgePrivateSigntature.NotBefore}"));
                var signingException = receiveException as CertificateException;
                Assert.IsNotNull(signingException);
                Assert.IsNotNull(signingException.Payload);
            },
                wait: () => _completedCalled,
                received: (m) => { },
                messageModification: (m) => { },
                handledException: ((m, e) =>
            {
                Server.Stop(TimeSpan.FromSeconds(10));
                _handledExceptionCalled = true;
                _completedCalled = true;
                receiveException = e;
            }),
                messageProtected: true);
        }
Esempio n. 3
0
        public void Asynchronous_Receive_LocalCertificateRevokedUnknown()
        {
            CertificateValidator.SetError(
                (c, u) => (u == X509KeyUsageFlags.DataEncipherment) ? CertificateErrors.RevokedUnknown : CertificateErrors.None);

            RunAsynchronousReceive(
                postValidation: () =>
            {
                Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count);
                Assert.AreEqual(0, MockFactory.OtherParty.Error.Messages.Count);
                Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.LocalCertificateRevocation));
            },
                wait: () => _completedCalled,
                received: (m) => { Assert.IsTrue(m.DecryptionError != CertificateErrors.None); },
                messageModification: (m) => { });
        }
Esempio n. 4
0
 public void Asynchronous_Receive_NotifySender()
 {
     RunAsynchronousReceive(
         postValidation: () =>
     {
         Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count);
         Assert.AreEqual(1, MockFactory.OtherParty.Error.Messages.Count);
         CheckError(MockFactory.OtherParty.Error.Messages, "transport:internal-error", "NotifySender", string.Empty);
         var logEntry = MockLoggerProvider.FindEntry(EventIds.ApplicationReported);
         Assert.IsNotNull(logEntry);
         Assert.IsTrue(logEntry.LogLevel == LogLevel.Warning);
     },
         wait: () => _handledExceptionCalled,
         received: (m) => { throw new NotifySenderException("NotifySender"); },
         messageModification: (m) => { });
 }
Esempio n. 5
0
 public void Asynchronous_Receive_XmlSchemaError()
 {
     RunAsynchronousReceive(
         postValidation: () =>
     {
         Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count);
         Assert.AreEqual(1, MockFactory.OtherParty.Error.Messages.Count);
         CheckError(MockFactory.OtherParty.Error.Messages, "transport:not-well-formed-xml", "XML-Error", string.Empty);
         var logEntry = MockLoggerProvider.FindEntry(EventIds.NotXml);
         Assert.IsNotNull(logEntry);
         Assert.IsTrue(logEntry.LogLevel == LogLevel.Warning);
     },
         wait: () => _handledExceptionCalled,
         received: (m) => { throw new XmlSchemaValidationException("XML-Error"); },
         messageModification: (m) => { });
 }
Esempio n. 6
0
        public void Asynchronous_Receive_RemoteCertificateRevokedUnknown()
        {
            CertificateValidator.SetError(
                (c, u) => (u == X509KeyUsageFlags.NonRepudiation) ? CertificateErrors.RevokedUnknown : CertificateErrors.None);

            RunAsynchronousReceive(
                postValidation: () =>
            {
                Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count);
                Assert.AreEqual(1, MockFactory.OtherParty.Error.Messages.Count);
                Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.RemoteCertificateRevocation));
                CheckError(MockFactory.OtherParty.Error.Messages, "transport:revoked-certificate", "Unable to determine revocation status", string.Empty);
            },
                wait: () => _completedCalled,
                received: (m) => { Assert.IsTrue(m.SignatureError != CertificateErrors.None); },
                messageModification: (m) => { });
        }
Esempio n. 7
0
 public void Asynchronous_Receive_ReceivedDataMismatch()
 {
     RunAsynchronousReceive(
         postValidation: () =>
     {
         Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count);
         Assert.AreEqual(1, MockFactory.OtherParty.Error.Messages.Count);
         CheckError(MockFactory.OtherParty.Error.Messages, "transport:invalid-field-value", "Mismatch", "Expected;Received;");
         var logEntry = MockLoggerProvider.FindEntry(EventIds.DataMismatch);
         Assert.IsNotNull(logEntry);
         Assert.IsTrue(logEntry.LogLevel == LogLevel.Warning);
     },
         wait: () => _handledExceptionCalled,
         received: (m) => { throw new ReceivedDataMismatchException("Mismatch")
                            {
                                ExpectedValue = "Expected", ReceivedValue = "Received"
                            }; },
         messageModification: (m) => { });
 }
Esempio n. 8
0
        public void Asynchronous_Receive_RemoteCertificateMultiple()
        {
            CertificateValidator.SetError(
                (c, u) =>
                (u == X509KeyUsageFlags.NonRepudiation)
                                                   ? CertificateErrors.StartDate | CertificateErrors.EndDate
                                                   : CertificateErrors.None);

            RunAsynchronousReceive(
                postValidation: () =>
            {
                Assert.AreEqual(0, MockFactory.Helsenorge.Asynchronous.Messages.Count);
                Assert.AreEqual(1, MockFactory.OtherParty.Error.Messages.Count);
                Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.RemoteCertificate));
                CheckError(MockFactory.OtherParty.Error.Messages, "transport:invalid-certificate", "More than one error with certificate", string.Empty);
            },
                wait: () => _completedCalled,
                received: (m) => { Assert.IsTrue(m.SignatureError != CertificateErrors.None); },
                messageModification: (m) => { });
        }
Esempio n. 9
0
 public void Error_Receive_Soap()
 {
     // postition of arguments have been reversed so that we inster the name of the argument without getting a resharper indication
     // makes it easier to read
     RunReceive(
         SoapFault,
         postValidation: () =>
     {
         Assert.IsTrue(_errorReceiveCalled);
         Assert.AreEqual(0, MockFactory.Helsenorge.Error.Messages.Count);
         Assert.IsTrue(_errorStartingCalled, "Error message received starting callback not called");
         Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.ExternalReportedError));
     },
         wait: () => _errorReceiveCalled,
         messageModification: (m) =>
     {
         m.ContentType     = ContentType.Soap;
         m.MessageFunction = "AMQP_SOAP_FAULT";
     });
 }
Esempio n. 10
0
 public void Error_Receive_Encrypted()
 {
     // postition of arguments have been reversed so that we inster the name of the argument without getting a resharper indication
     // makes it easier to read
     RunReceive(
         GenericMessage,
         postValidation: () =>
     {
         Assert.IsTrue(_errorReceiveCalled);
         Assert.AreEqual(0, MockFactory.Helsenorge.Error.Messages.Count);
         Assert.IsTrue(_errorStartingCalled, "Error message received starting callback not called");
         Assert.IsNull(MockLoggerProvider.Entries.FirstOrDefault(e => e.Message.Contains("CPA_FindAgreementForCounterpartyAsync_0_93252")));
         Assert.IsNotNull(MockLoggerProvider.FindEntry(EventIds.ExternalReportedError));
     },
         wait: () => _errorReceiveCalled,
         messageModification: (m) =>
     {
         m.Properties.Add("property1", 1);
         m.Properties.Add("property2", 1);
     });
 }
Esempio n. 11
0
        private string[] RunTest(Arguments arguments = null)
        {
            // Copy to the test run dir to avoid cross-test contamination
            var testPath = Path.GetFullPath(Path.Combine("TestData", this.TestContext.TestName));
            var root     = Path.Combine(this.TestContext.TestRunDirectory, this.TestContext.TestName);

            DirectoryCopy(testPath, root);

            // Run ReferenceTrimmer and collect the log entries
            if (arguments == null)
            {
                arguments = new Arguments {
                    CompileIfNeeded = true, RestoreIfNeeded = true
                };
            }

            arguments.Path = root;

            // To help with UT debugging
            arguments.UseBinaryLogger = true;

            var loggerFactory      = new LoggerFactory();
            var mockLoggerProvider = new MockLoggerProvider();

            loggerFactory.AddProvider(mockLoggerProvider);

            // MSBuild sets the current working directory, so we need to be sure to restore it after each run.
            var currentWorkingDirectory = Directory.GetCurrentDirectory();

            try
            {
                ReferenceTrimmer.Run(arguments, loggerFactory.CreateLogger(this.TestContext.TestName));
            }
            finally
            {
                Directory.SetCurrentDirectory(currentWorkingDirectory);
            }

            return(mockLoggerProvider.LogLines);
        }
Esempio n. 12
0
        internal void SetupInternal(int otherHerId)
        {
            var addressRegistrySettings = new AddressRegistrySettings()
            {
                UserName         = "******",
                Password         = "******",
                EndpointName     = "SomeEndpointName",
                WcfConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None),
                CachingInterval  = TimeSpan.FromSeconds(5)
            };
            var collaborationRegistrySettings = new CollaborationProtocolRegistrySettings()
            {
                UserName         = "******",
                Password         = "******",
                EndpointName     = "SomeEndpointName",
                WcfConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None),
                CachingInterval  = TimeSpan.FromSeconds(5)
            };

            LoggerFactory = new LoggerFactory();

            MockLoggerProvider = new MockLoggerProvider(null);
            LoggerFactory.AddProvider(MockLoggerProvider);

            //LoggerFactory.AddDebug();
            //Logger = new LoggerMock(LoggerFactory.CreateLogger<BaseTest>());
            Logger = LoggerFactory.CreateLogger <BaseTest>();

            var memoryCache      = new MemoryCache(new MemoryCacheOptions());
            var distributedCache = new MemoryDistributedCache(memoryCache);

            AddressRegistry = new AddressRegistryMock(addressRegistrySettings, distributedCache);
            AddressRegistry.SetupFindCommunicationPartyDetails(i =>
            {
                var file = Path.Combine("Files", $"CommunicationDetails_{i}.xml");
                return(File.Exists(file) == false ? null : XElement.Load(file));
            });
            AddressRegistry.SetupGetCertificateDetailsForEncryption(i =>
            {
                var path = Path.Combine("Files", $"GetCertificateDetailsForEncryption_{i}.xml");
                return(File.Exists(path) == false ? null : XElement.Load(path));
            });
            AddressRegistry.SetupGetCertificateDetailsForValidatingSignature(i =>
            {
                var path = Path.Combine("Files", $"GetCertificateDetailsForValidatingSignature_{i}.xml");
                return(File.Exists(path) == false ? null : XElement.Load(path));
            });

            CollaborationRegistry = new CollaborationProtocolRegistryMock(collaborationRegistrySettings, distributedCache, AddressRegistry);
            CollaborationRegistry.SetupFindProtocolForCounterparty(i =>
            {
                var file = Path.Combine("Files", $"CPP_{i}.xml");
                return(File.Exists(file) == false ? null : File.ReadAllText(file));
            });
            CollaborationRegistry.SetupFindAgreementForCounterparty(i =>
            {
                var file = Path.Combine("Files", $"CPA_{i}.xml");
                return(File.Exists(file) == false ? null : File.ReadAllText(file));
            });
            CollaborationRegistry.SetupFindAgreementById(i =>
            {
                var file = Path.Combine("Files", $"CPA_{i:D}.xml");
                return(File.Exists(file) == false ? null : File.ReadAllText(file));
            });

            Settings = new MessagingSettings()
            {
                MyHerId            = MockFactory.HelsenorgeHerId,
                SigningCertificate = new CertificateSettings()
                {
                    Certificate = TestCertificates.HelsenorgePrivateSigntature
                },
                DecryptionCertificate = new CertificateSettings()
                {
                    Certificate = TestCertificates.HelsenorgePrivateEncryption
                }
            };

            Settings.ServiceBus.ConnectionString = "connection string";
            Settings.ServiceBus.Synchronous.ReplyQueueMapping.Add(Environment.MachineName.ToLower(), "RepliesGoHere");
            // make things easier by only having one processing task per queue
            Settings.ServiceBus.Asynchronous.ProcessingTasks = 1;
            Settings.ServiceBus.Synchronous.ProcessingTasks  = 1;
            Settings.ServiceBus.Error.ProcessingTasks        = 1;

            MockFactory          = new MockFactory(otherHerId);
            CertificateValidator = new MockCertificateValidator();

            Client = new MessagingClient(Settings, CollaborationRegistry, AddressRegistry)
            {
                DefaultMessageProtection    = new NoMessageProtection(), // disable protection for most tests
                DefaultCertificateValidator = CertificateValidator
            };
            Client.ServiceBus.RegisterAlternateMessagingFactory(MockFactory);

            Server = new MessagingServer(Settings, Logger, LoggerFactory, CollaborationRegistry, AddressRegistry)
            {
                DefaultMessageProtection    = new NoMessageProtection(), // disable protection for most tests
                DefaultCertificateValidator = CertificateValidator
            };
            Server.ServiceBus.RegisterAlternateMessagingFactory(MockFactory);
        }