public void FindProcessAndCreateMessagingStepBeforeStreamFirstReadEvent()
        {
            var trackingContext = new TrackingContext {
                ProcessActivityId = ActivityId.NewActivityId(),
            };

            using (var stream = new TrackingStream(new StringStream("some-content")))
            {
                MessageMock.Object.BodyPart.Data = stream;
                MessageMock.Setup(m => m.GetProperty(BtsProperties.OutboundTransportLocation)).Returns("outbound-transport-location");
                MessageMock.Setup(m => m.GetProperty(TrackingProperties.ProcessActivityId)).Returns(trackingContext.ProcessActivityId);
                MessageMock.Setup(m => m.GetProperty(TrackingProperties.MessagingStepActivityId)).Returns(trackingContext.MessagingStepActivityId);

                var sut = ActivityTracker.Create(new MicroComponent.ActivityTracker.Context(PipelineContextMock.Object, MessageMock.Object, ActivityTrackingModes.Step));
                sut.TrackActivity();

                ActivityFactory.Verify(
                    af => af.CreateProcess(It.IsAny <IBaseMessage>(), It.IsAny <string>()),
                    Times.Never());
                ActivityFactory.Verify(
                    af => af.FindProcess(It.Is <TrackingContext>(c => c.ProcessActivityId == trackingContext.ProcessActivityId)),
                    Times.Once());
                ActivityFactory.Verify(
                    af => af.CreateMessagingStep(It.IsAny <IBaseMessage>()),
                    Times.Once());
                ActivityFactory.Verify(
                    af => af.FindMessagingStep(It.IsAny <TrackingContext>()),
                    Times.Never());
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Ascertain, i.e. assess and setup, whether the payload of a message body <paramref name="trackingStream"/>
        /// needs to be captured outside of the BAM monitoring database, that is in the <see cref="ClaimStore"/>, or not.
        /// </summary>
        /// <param name="trackingStream">
        /// The stream to assess.
        /// </param>
        /// <param name="trackingModes">
        /// The extent to which a messaging activity will be recorded.
        /// </param>
        /// <param name="transactionFactory">
        /// The <see cref="IKernelTransaction"/> factory method whose offspring transaction has to be piggybacked if the
        /// message body's payload needs to be claimed to disk. It can be <c>null</c> if piggybacking is not desired nor
        /// possible, like for instance when calling this method from a send pipeline, as BizTalk does not provide for
        /// transaction piggybacking in send pipelines.
        /// </param>
        /// <returns>
        /// The ascertained <see cref="ActivityTrackingModes"/>, that is the one that will actually be applied.
        /// </returns>
        /// <remarks>
        /// <para>
        /// If the size of the <see cref="TrackingStream"/> does not exceed a 512KB threshold, the <see
        /// cref="TrackingStream"/>'s capture will be setup according to a <see cref="MessageBodyCaptureDescriptor"/>
        /// whose <see cref="MessageBodyCaptureDescriptor.Data"/> will contain a base64-encoding of the compressed stream
        /// content.
        /// </para>
        /// <para>
        /// If the size of the <see cref="TrackingStream"/> exceeds the 512KB threshold, the <see
        /// cref="TrackingStream"/>'s capture will be setup according to a <see cref="MessageBodyCaptureDescriptor"/>
        /// whose <see cref="MessageBodyCaptureDescriptor.Data"/> will contain the relative URL that can be used to get
        /// back the payload from the <see cref="ClaimStore"/>.
        /// </para>
        /// <para>
        /// The 512KB threshold has been chosen according to the BizTalk documentation which proscribes BAM
        /// <c>LongReferenceData</c> item of more than 512 KB.
        /// </para>
        /// </remarks>
        public virtual void SetupMessageBodyCapture(TrackingStream trackingStream, ActivityTrackingModes trackingModes, Func <IKernelTransaction> transactionFactory)
        {
            if (trackingStream == null)
            {
                throw new ArgumentNullException("trackingStream");
            }

            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat(
                    "Message body capture is being set up for '{0}' tracking requirements.",
                    Convert.ToString(trackingModes));
            }

            // never want to claim (save to disk) a payload if it is small, hence always probe for its size
            string encodedCompression;
            var    isCompressible = trackingStream.AsMarkable().TryCompressToBase64String(PAYLOAD_SIZE_THRESHOLD, out encodedCompression);

            if (isCompressible)
            {
                var captureDescriptor = new MessageBodyCaptureDescriptor(encodedCompression, MessageBodyCaptureMode.Unclaimed);
                trackingStream.SetupCapture(captureDescriptor);
            }
            else
            {
                var captureDescriptor = new MessageBodyCaptureDescriptor(GenerateClaimStoreEntry(), MessageBodyCaptureMode.Claimed);
                var capturingStream   = CreateCapturingStream(captureDescriptor.Data, trackingModes, transactionFactory);
                trackingStream.SetupCapture(captureDescriptor, capturingStream);
            }
        }
        public void CompleteTrackingOfOutboundMessageWithProcessAffiliationAfterStreamLastReadEvent()
        {
            using (var stream = new TrackingStream(new StringStream("some-content")))
            {
                MessageMock.Object.BodyPart.Data = stream;
                MessageMock.Setup(m => m.GetProperty(BtsProperties.OutboundTransportLocation)).Returns("outbound-transport-location");
                MessageMock.Setup(m => m.GetProperty(TrackingProperties.ProcessActivityId)).Returns(ActivityId.NewActivityId());

                var sut = ActivityTracker.Create(new MicroComponent.ActivityTracker.Context(PipelineContextMock.Object, MessageMock.Object, ActivityTrackingModes.Step));
                sut.TrackActivity();
                MessageMock.Object.BodyPart.Data.Drain();

                ProcessMock.Verify(
                    p => p.TrackActivity(),
                    Times.Never());
                InitiatingMessagingStepMock.Verify(
                    ms => ms.TrackActivity(It.IsAny <ActivityTrackingModes>(), It.IsAny <TrackingStream>()),
                    Times.Never());
                ProcessMock.Verify(
                    p => p.AddStep(InitiatingMessagingStepMock.Object),
                    Times.Never());
                MessagingStepMock.Verify(
                    ms => ms.TrackActivity(It.IsAny <ActivityTrackingModes>(), It.IsAny <TrackingStream>()),
                    Times.Once());
                ProcessMock.Verify(
                    p => p.AddStep(MessagingStepMock.Object),
                    Times.Once());
            }
        }
Exemplo n.º 4
0
        public void MessageBodyIsTracked()
        {
            var message = new MessageMock();

            message.Setup(m => m.GetProperty(BtsProperties.InboundTransportLocation)).Returns("inbound-transport-location");

            var eventStream = new Mock <EventStream>();

            var pipelineContext = new Mock <IPipelineContext> {
                DefaultValue = DefaultValue.Mock
            };

            pipelineContext
            .Setup(pc => pc.GetEventStream())
            .Returns(eventStream.Object);

            var sut = new MessagingStep(pipelineContext.Object, message.Object);

            using (var trackingStream = new TrackingStream(new MemoryStream(_content), new MessageBodyCaptureDescriptor("data", MessageBodyCaptureMode.Claimed)))
            {
                // TrackActivity is supposed to occur at stream's end
                trackingStream.Drain();
                sut.TrackActivity(ActivityTrackingModes.Body, trackingStream);
            }

            eventStream.Verify(
                es => es.AddReference(
                    nameof(MessagingStep),
                    sut.ActivityId,
                    MessageBodyCaptureMode.Claimed.ToString(),
                    MessagingStep.MESSAGE_BODY_REFERENCE_NAME,
                    It.IsAny <string>(),
                    It.IsAny <string>()),
                Times.Once());
        }
        public void CaptureMessageBody()
        {
            var trackingStream = new TrackingStream(FakeTextStream.Create(1024 * 1024));

            var messageMock = new Unit.Message.Mock <IBaseMessage> {
                DefaultValue = DefaultValue.Mock
            };

            messageMock.Object.BodyPart.Data = trackingStream;

            SsoSettingsReaderMock
            .Setup(ssr => ssr.ReadString(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_IN_DIRECTORY_PROPERTY_NAME))
            .Returns(Path.GetTempPath());
            SsoSettingsReaderMock
            .Setup(ssr => ssr.ReadString(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_OUT_DIRECTORY_PROPERTY_NAME))
            .Returns(@"\\network\share");

            ClaimStore.Instance.SetupMessageBodyCapture(trackingStream, ActivityTrackingModes.Body, null);

            messageMock.Object.BodyPart.Data.Drain();

            // payload is claimed to disk and file extension is .trk
            var captureDescriptor = trackingStream.CaptureDescriptor;

            Assert.That(captureDescriptor.CaptureMode, Is.EqualTo(MessageBodyCaptureMode.Claimed));
            Assert.That(captureDescriptor.Data, Does.StartWith(DateTime.Today.ToString(@"yyyyMMdd\\")));
            Assert.That(File.Exists(Path.Combine(Path.GetTempPath(), captureDescriptor.Data.Replace("\\", "") + ".trk")), Is.True);
        }
        public void CaptureMessageBody()
        {
            var trackingStream = new TrackingStream(TextStreamDummy.Create(1024 * 1024));

            var messageMock = new Unit.Message.Mock <IBaseMessage> {
                DefaultValue = DefaultValue.Mock
            };

            messageMock.Object.BodyPart.Data = trackingStream;

            using (var configurationReaderMockInjectionScope = new SsoConfigurationReaderMockInjectionScope())
            {
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckInDirectory)))
                .Returns(Path.GetTempPath());
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckOutDirectory)))
                .Returns(@"\\server\share");

                ClaimStore.Instance.SetupMessageBodyCapture(trackingStream, ActivityTrackingModes.Body, null);

                messageMock.Object.BodyPart.Data.Drain();

                // payload is claimed to disk and file extension is .trk
                var captureDescriptor = trackingStream.CaptureDescriptor;
                captureDescriptor.CaptureMode.Should().Be(MessageBodyCaptureMode.Claimed);
                captureDescriptor.Data.Should().StartWith(DateTime.Today.ToString(@"yyyyMMdd\\"));
                File.Exists(Path.Combine(Path.GetTempPath(), captureDescriptor.Data.Replace("\\", "") + ".trk")).Should().BeTrue();
            }
        }
        public void CompleteTrackingOfInboundMessageWithoutProcessAffiliationAfterStreamLastReadEvent()
        {
            using (var stream = new TrackingStream(new StringStream("some-content")))
            {
                MessageMock.Object.BodyPart.Data = stream;

                var sut = ActivityTracker.Create(new MicroComponent.ActivityTracker.Context(PipelineContextMock.Object, MessageMock.Object, ActivityTrackingModes.Step));
                sut.TrackActivity();
                MessageMock.Object.BodyPart.Data.Drain();

                ProcessMock.Verify(
                    p => p.TrackActivity(),
                    Times.Never());
                InitiatingMessagingStepMock.Verify(
                    ms => ms.TrackActivity(It.IsAny <ActivityTrackingModes>(), It.IsAny <TrackingStream>()),
                    Times.Never());
                ProcessMock.Verify(
                    p => p.AddStep(InitiatingMessagingStepMock.Object),
                    Times.Never());
                MessagingStepMock.Verify(
                    ms => ms.TrackActivity(It.IsAny <ActivityTrackingModes>(), It.IsAny <TrackingStream>()),
                    Times.Once());
                ProcessMock.Verify(
                    p => p.AddStep(MessagingStepMock.Object),
                    Times.Never());
            }
        }
Exemplo n.º 8
0
        private static Stream[] CreatePipeline(List <ConfigPair> pipelineConfig, IList <Stream> fileStreams, bool isBackup, IStreamNotification streamNotification, long estimatedTotalBytes)
        {
            streamNotification.EstimatedBytes = estimatedTotalBytes;

            List <Stream> result = new List <Stream>(fileStreams.Count);

            foreach (Stream fileStream in fileStreams)
            {
                Stream topStream = fileStream;
                if (!isBackup)
                {
                    topStream = new TrackingStream(topStream, streamNotification);
                }

                for (int i = pipelineConfig.Count - 1; i >= 0; i--)
                {
                    ConfigPair config = pipelineConfig[i];

                    IBackupTransformer tran = config.TransformationType.GetConstructor(new Type[0]).Invoke(new object[0]) as IBackupTransformer;
                    if (tran == null)
                    {
                        throw new ArgumentException(string.Format("Unable to create pipe component: {0}", config.TransformationType.Name));
                    }
                    topStream = isBackup ? tran.GetBackupWriter(config.Parameters, topStream) : tran.GetRestoreReader(config.Parameters, topStream);
                }

                if (isBackup)
                {
                    topStream = new TrackingStream(topStream, streamNotification);
                }
                result.Add(topStream);
            }
            return(result.ToArray());
        }
        public void InboundSuccessfulPropertiesForSolicitResponsePortAreTracked()
        {
            var message = new MessageMock();

            SetupCommonProperties(message);
            // no ReceiveLocationName on the inbound of a solicit-response port but a ReceivePortName
            message.Setup(m => m.GetProperty(BtsProperties.ReceivePortName)).Returns("receive-port-name");
            message.Setup(m => m.GetProperty(BtsProperties.InboundTransportLocation)).Returns("inbound-transport-location");
            message.Setup(m => m.GetProperty(BtsProperties.InboundTransportType)).Returns("inbound-transport-type");

            var activityId = string.Empty;
            Dictionary <string, object> data = null;
            var eventStream = new Mock <EventStream>();

            eventStream
            // ReSharper disable AccessToModifiedClosure
            .Setup(es => es.UpdateActivity(MessagingStep.ActivityName, It.Is <string>(id => id == activityId), It.IsAny <object[]>()))
            // ReSharper restore AccessToModifiedClosure
            .Callback <string, string, object[]>((n, id, d) => data = ToDictionary(d))
            .Verifiable();

            var pipelineContext = new Mock <IPipelineContext> {
                DefaultValue = DefaultValue.Mock
            };

            pipelineContext.Setup(pc => pc.GetEventStream()).Returns(eventStream.Object);

            var sut = new MessagingStep(pipelineContext.Object, message.Object);

            activityId = sut.ActivityId;
            using (var trackingStream = new TrackingStream(new MemoryStream(_content)))
            {
                // TrackActivity is supposed to occur at stream's end
                trackingStream.Drain();
                sut.TrackActivity(ActivityTrackingModes.Step, trackingStream);
            }

            eventStream.Verify();

            var expectedData = new Dictionary <string, object> {
                { MessagingStep.MessageIDFieldName, _messageId.AsNormalizedActivityId() },
                { MessagingStep.MessageTypeFieldName, "message-type" },
                { MessagingStep.PortNameFieldName, "receive-port-name" },
                { MessagingStep.TransportLocationFieldName, "inbound-transport-location" },
                { MessagingStep.TransportTypeFieldName, "inbound-transport-type" },
                { MessagingStep.StatusFieldName, TrackingStatus.Received },
                { MessagingStep.MachineNameFieldName, Environment.MachineName },
                { MessagingStep.TimeFieldName, sut.Time }
            }
            .Union(ExpectedCommonData, new LambdaComparer <KeyValuePair <string, object> >((kvp1, kvp2) => kvp1.Key == kvp2.Key))
            .OrderBy(kvp => kvp.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            Assert.That(data, Is.EquivalentTo(expectedData));
        }
        public void OutboundSuccessfulPropertiesAreTrackedAtStreamExhaustion()
        {
            var message = new MessageMock();

            SetupCommonProperties(message);
            SetupInboundSuccessfulProperties(message);
            SetupOutboundSuccessfulProperties(message);

            var activityId = string.Empty;
            Dictionary <string, object> data = null;
            var eventStream = new Mock <EventStream>();

            eventStream
            // ReSharper disable AccessToModifiedClosure
            .Setup(es => es.UpdateActivity(MessagingStep.ActivityName, It.Is <string>(id => id == activityId), It.IsAny <object[]>()))
            // ReSharper restore AccessToModifiedClosure
            .Callback <string, string, object[]>((n, id, d) => data = ToDictionary(d))
            .Verifiable();

            var pipelineContext = new Mock <IPipelineContext> {
                DefaultValue = DefaultValue.Mock
            };

            pipelineContext.Setup(pc => pc.GetEventStream()).Returns(eventStream.Object);

            var sut = new MessagingStep(pipelineContext.Object, message.Object);

            activityId = sut.ActivityId;
            using (var trackingStream = new TrackingStream(new MemoryStream(_content)))
            {
                // TrackActivity is supposed to occur at stream's end
                trackingStream.Drain();
                sut.TrackActivity(ActivityTrackingModes.Step, trackingStream);
            }

            eventStream.Verify();

            var expectedData = new Dictionary <string, object> {
                { MessagingStep.MessageIDFieldName, _messageId.AsNormalizedActivityId() },
                { MessagingStep.PortNameFieldName, "send-port-name" },
                { MessagingStep.TransportLocationFieldName, "outbound-transport-location" },
                { MessagingStep.TransportTypeFieldName, "outbound-transport-type" },
                { MessagingStep.StatusFieldName, TrackingStatus.Sent },
                { MessagingStep.MachineNameFieldName, Environment.MachineName },
                { MessagingStep.TimeFieldName, sut.Time }
            }
            .Union(ExpectedCommonData)
            .OrderBy(kvp => kvp.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            Assert.That(data, Is.EquivalentTo(expectedData));
            Assert.That(sut.MessageType, Is.EqualTo("message-type"));
        }
        public void OutboundFailedPropertiesAreTracked()
        {
            var message = new MessageMock();

            SetupCommonProperties(message);
            SetupInboundSuccessfulProperties(message);
            SetupOutboundSuccessfulProperties(message);
            SetupCommonFailedProperties(message);
            message.Setup(m => m.GetProperty(ErrorReportProperties.SendPortName)).Returns("failed-send-port-name");
            message.Setup(m => m.GetProperty(ErrorReportProperties.OutboundTransportLocation)).Returns("failed-outbound-transport-location");

            var activityId = string.Empty;
            Dictionary <string, object> data = null;
            var eventStream = new Mock <EventStream>();

            eventStream
            // ReSharper disable AccessToModifiedClosure
            .Setup(es => es.UpdateActivity(MessagingStep.ActivityName, It.Is <string>(id => id == activityId), It.IsAny <object[]>()))
            // ReSharper restore AccessToModifiedClosure
            .Callback <string, string, object[]>((n, id, d) => data = ToDictionary(d))
            .Verifiable();

            var pipelineContext = new Mock <IPipelineContext> {
                DefaultValue = DefaultValue.Mock
            };

            pipelineContext.Setup(pc => pc.GetEventStream()).Returns(eventStream.Object);

            var sut = new MessagingStep(pipelineContext.Object, message.Object);

            activityId = sut.ActivityId;
            using (var trackingStream = new TrackingStream(new MemoryStream(_content)))
            {
                // TrackActivity is supposed to occur at stream's end
                trackingStream.Drain();
                sut.TrackActivity(ActivityTrackingModes.Step, trackingStream);
            }

            eventStream.Verify();

            var expectedData = new Dictionary <string, object> {
                { MessagingStep.TransportTypeFieldName, "outbound-transport-type" },
                { MessagingStep.PortNameFieldName, "failed-send-port-name" },
                { MessagingStep.TransportLocationFieldName, "failed-outbound-transport-location" }
            }
            .Union(ExpectedCommonFailedData, new LambdaComparer <KeyValuePair <string, object> >((kvp1, kvp2) => kvp1.Key == kvp2.Key))
            .Union(ExpectedCommonData, new LambdaComparer <KeyValuePair <string, object> >((kvp1, kvp2) => kvp1.Key == kvp2.Key))
            .OrderBy(kvp => kvp.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            Assert.That(data, Is.EquivalentTo(expectedData));
            Assert.That(sut.MessageType, Is.EqualTo("failed-message-type"));
        }
        public void ResolveProcessNameBeforeStreamFirstReadEvent()
        {
            using (var stream = new TrackingStream(new StringStream("some-content")))
            {
                MessageMock.Object.BodyPart.Data = stream;
                MessageMock.Setup(m => m.GetProperty(BtsProperties.OutboundTransportLocation)).Returns("outbound-transport-location");

                var sut = ActivityTracker.Create(new MicroComponent.ActivityTracker.Context(PipelineContextMock.Object, MessageMock.Object, ActivityTrackingModes.Step));
                sut.TrackActivity();

                TrackingResolverMock.Verify(tr => tr.ResolveProcessName(), Times.Once());
            }
        }
Exemplo n.º 13
0
        public void CaptureIsNotSetupIfTrackingStreamAlreadyHasCaptureDescriptor()
        {
            using (var trackingStream = new TrackingStream(new MemoryStream(), new MessageBodyCaptureDescriptor("url", MessageBodyCaptureMode.Claimed)))
            {
                MessageMock.Object.BodyPart.Data = trackingStream;

                var sut = MessageBodyTracker.Create(new MicroComponent.ActivityTracker.Context(PipelineContextMock.Object, MessageMock.Object, ActivityTrackingModes.Body));
                sut.SetupTracking();
            }

            ClaimStoreMock.Verify(
                cs => cs.SetupMessageBodyCapture(It.IsAny <TrackingStream>(), It.IsAny <ActivityTrackingModes>(), It.IsAny <Func <IKernelTransaction> >()),
                Times.Never());
        }
Exemplo n.º 14
0
        public void InboundSuccessfulPropertiesAreTracked()
        {
            var message = new MessageMock();

            SetupCommonProperties(message);
            SetupInboundSuccessfulProperties(message);

            var activityId = string.Empty;
            Dictionary <string, object> data = null;
            var eventStream = new Mock <EventStream>();

            eventStream
            .Setup(es => es.UpdateActivity(nameof(MessagingStep), It.Is <string>(id => id == activityId), It.IsAny <object[]>()))
            .Callback <string, string, object[]>((n, id, d) => data = ToDictionary(d))
            .Verifiable();

            var pipelineContext = new Mock <IPipelineContext> {
                DefaultValue = DefaultValue.Mock
            };

            pipelineContext.Setup(pc => pc.GetEventStream()).Returns(eventStream.Object);

            var sut = new MessagingStep(pipelineContext.Object, message.Object);

            activityId = sut.ActivityId;
            using (var trackingStream = new TrackingStream(new MemoryStream(_content)))
            {
                // TrackActivity is supposed to occur at stream's end
                trackingStream.Drain();
                sut.TrackActivity(ActivityTrackingModes.Step, trackingStream);
            }

            eventStream.Verify();

            var expectedData = new Dictionary <string, object> {
                { nameof(MessagingStep.MessageID), _messageId.AsNormalizedActivityId() },
                { nameof(MessagingStep.MessageType), "message-type" },
                { nameof(MessagingStep.PortName), "receive-location-name" },
                { nameof(MessagingStep.TransportLocation), "inbound-transport-location" },
                { nameof(MessagingStep.TransportType), "inbound-transport-type" },
                { nameof(MessagingStep.Status), TrackingStatus.Received },
                { nameof(MessagingStep.MachineName), Environment.MachineName },
                { nameof(MessagingStep.Time), sut.Time }
            }
            .Union(ExpectedCommonData, new LambdaComparer <KeyValuePair <string, object> >((kvp1, kvp2) => kvp1.Key == kvp2.Key))
            .OrderBy(kvp => kvp.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            data.Should().BeEquivalentTo(expectedData);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Creates a BAM <c>MessagingStep</c> activity that captures descriptive information about the <see
 /// cref="IBaseMessage"/> being processed.
 /// </summary>
 /// <param name="trackingModes">
 /// The extent to which information about a messaging step activity will be tracked and recorded.
 /// </param>
 /// <param name="trackingStream">
 /// The <see cref="TrackingStream"/> that wraps the actual message body's stream that will captured.
 /// </param>
 internal virtual void TrackActivity(ActivityTrackingModes trackingModes, TrackingStream trackingStream)
 {
     if (trackingModes.RequiresStepTracking())
     {
         TrackStep(trackingStream.Length);
     }
     if (trackingModes.RequiresContextTracking())
     {
         TrackMessageContext();
     }
     if (trackingModes.RequiresBodyTracking())
     {
         TrackMessageBody(trackingStream.CaptureDescriptor);
     }
 }
Exemplo n.º 16
0
        //**************************************************
        //* Public interface
        //**************************************************

        //-------------------------------------------------
        /// <summary>
        /// Compute checksum for the specified source file,
        /// return it as hex string ("F3BA87...").
        /// </summary>
        /// <remarks>
        /// This method will be run on a worker thread
        /// (from thread pool) via async invocation.
        /// </remarks>
        public static string ComputeChecksum(string sourceFile, ChecksumMethod method, Action <decimal> progressNotifier)
        {
            System.Threading.Thread.Sleep(100);
            using (var hashAlgorithm = CreateHashAlgorithm(method))
                using (var source = new TrackingStream(File.OpenRead(sourceFile), progressNotifier))
                {
                    var hash = hashAlgorithm.ComputeHash(source);

                    var msg = new StringBuilder(128);
                    foreach (var byteValue in hash)
                    {
                        msg.AppendFormat(byteValue.ToString("X2", CultureInfo.InvariantCulture));
                    }
                    return(msg.ToString());
                }
        }
        private void Complete(ActivityTrackingModes trackingModes, TrackingStream trackingStream)
        {
            var isMessagingProcess = _previousMessagingStep != null;

            if (_logger.IsDebugEnabled)
            {
                _logger.Debug($"Completing tracking of a messaging {(isMessagingProcess ? "process" : "step")}.");
            }

            // track the whole wealth of messaging activity, it might be a complete process or a single messaging step
            if (isMessagingProcess)
            {
                _process.TrackActivity();
                _process.AddStep(_previousMessagingStep);
            }
            _messagingStep.TrackActivity(trackingModes, trackingStream);
            _process.IfNotNull(p => p.AddStep(_messagingStep));
        }
        public void ClaimMessageBody()
        {
            using (var configurationReaderMockInjectionScope = new SsoConfigurationReaderMockInjectionScope())
            {
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckInDirectory)))
                .Returns(Path.GetTempPath());
                configurationReaderMockInjectionScope.Mock
                .Setup(ssr => ssr.Read(ClaimStoreSsoSettings.AFFILIATE_APPLICATION_NAME, nameof(ClaimStoreSsoSettings.ClaimStoreCheckOutDirectory)))
                .Returns(@"\\server\share");

                using (var contentStream = TextStreamDummy.Create(1024 * 1024))
                    using (var trackingStream = new TrackingStream(contentStream))
                    {
                        MessageMock.Object.BodyPart.Data = trackingStream;

                        ClaimStore.Instance.SetupMessageBodyCapture(trackingStream, ActivityTrackingModes.Claim, null);
                        ClaimStore.Instance.Claim(MessageMock.Object, ResourceTrackerMock.Object);

                        // message's actual body stream has been exhausted (i.e. saved to disk)
                        contentStream.Position.Should().Be(contentStream.Length);

                        // message's body stream is replaced by a token message
                        using (var reader = new StreamReader(MessageMock.Object.BodyPart.Data))
                        {
                            reader.ReadToEnd().Should().Be(ClaimFactory.CreateCheckIn(trackingStream.CaptureDescriptor.Data).OuterXml);
                        }

                        // MessageType of token message is promoted in message context
                        var schemaMetadata = SchemaMetadata.For <Claim.CheckIn>();
                        MessageMock.Verify(m => m.Promote(BtsProperties.MessageType, schemaMetadata.MessageType), Times.Once());
                        MessageMock.Verify(m => m.Promote(BtsProperties.SchemaStrongName, schemaMetadata.DocumentSpec.DocSpecStrongName), Times.Once());

                        // payload is claimed to disk and file extension is .chk
                        var captureDescriptor = trackingStream.CaptureDescriptor;
                        captureDescriptor.CaptureMode.Should().Be(MessageBodyCaptureMode.Claimed);
                        captureDescriptor.Data.Should().StartWith(DateTime.Today.ToString(@"yyyyMMdd\\"));
                        File.Exists(Path.Combine(Path.GetTempPath(), captureDescriptor.Data.Replace("\\", "") + ".chk")).Should().BeTrue();
                    }
            }
        }
Exemplo n.º 19
0
        public void MessageContextIsTracked()
        {
            var ns   = BtsProperties.MessageType.Namespace;
            var name = BtsProperties.MessageType.Name;

            var message = new MessageMock();

            message.Setup(m => m.GetProperty(BtsProperties.InboundTransportLocation)).Returns("inbound-transport-location");
            message.Setup(m => m.Context.CountProperties).Returns(1);
            message.Setup(m => m.Context.ReadAt(0, out name, out ns)).Returns("message-type");
            message.Setup(m => m.Context.IsPromoted(name, ns)).Returns(false);

            var eventStream = new Mock <EventStream>();

            var pipelineContext = new Mock <IPipelineContext> {
                DefaultValue = DefaultValue.Mock
            };

            pipelineContext.Setup(pc => pc.GetEventStream()).Returns(eventStream.Object);

            var sut = new MessagingStep(pipelineContext.Object, message.Object);

            using (var trackingStream = new TrackingStream(new MemoryStream(_content)))
            {
                // TrackActivity is supposed to occur at stream's end
                trackingStream.Drain();
                sut.TrackActivity(ActivityTrackingModes.Context, trackingStream);
            }

            eventStream.Verify(
                es => es.AddReference(
                    nameof(MessagingStep),
                    sut.ActivityId,
                    MessagingStep.MESSAGE_CONTEXT_REFERENCE_TYPE,
                    MessagingStep.MESSAGE_CONTEXT_REFERENCE_NAME,
                    It.IsAny <string>(),
                    message.Object.Context.ToXml()),
                Times.Once());
        }
        public void ClaimMessageBody()
        {
            SsoSettingsReaderMock
            .Setup(ssr => ssr.ReadString(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_IN_DIRECTORY_PROPERTY_NAME))
            .Returns(Path.GetTempPath());
            SsoSettingsReaderMock
            .Setup(ssr => ssr.ReadString(BizTalkFactorySettings.APPLICATION_NAME, BizTalkFactorySettings.CLAIM_STORE_CHECK_OUT_DIRECTORY_PROPERTY_NAME))
            .Returns(@"\\network\share");

            using (var contentStream = FakeTextStream.Create(1024 * 1024))
                using (var trackingStream = new TrackingStream(contentStream))
                {
                    MessageMock.Object.BodyPart.Data = trackingStream;

                    ClaimStore.Instance.SetupMessageBodyCapture(trackingStream, ActivityTrackingModes.Claim, null);
                    ClaimStore.Instance.Claim(MessageMock.Object, ResourceTrackerMock.Object);

                    // message's actual body stream has been exhausted (i.e. saved to disk)
                    Assert.That(contentStream.Position, Is.EqualTo(contentStream.Length));

                    // message's body stream is replaced by a token message
                    using (var reader = new StreamReader(MessageMock.Object.BodyPart.Data))
                    {
                        Assert.That(reader.ReadToEnd(), Is.EqualTo(MessageFactory.CreateClaimCheckIn(trackingStream.CaptureDescriptor.Data).OuterXml));
                    }

                    // MessageType of token message is promoted in message context
                    var schemaMetadata = typeof(Claim.CheckIn).GetMetadata();
                    MessageMock.Verify(m => m.Promote(BtsProperties.MessageType, schemaMetadata.MessageType), Times.Once());
                    MessageMock.Verify(m => m.Promote(BtsProperties.SchemaStrongName, schemaMetadata.DocumentSpec.DocSpecStrongName), Times.Once());

                    // payload is claimed to disk and file extension is .chk
                    var captureDescriptor = trackingStream.CaptureDescriptor;
                    Assert.That(captureDescriptor.CaptureMode, Is.EqualTo(MessageBodyCaptureMode.Claimed));
                    Assert.That(captureDescriptor.Data, Does.StartWith(DateTime.Today.ToString(@"yyyyMMdd\\")));
                    Assert.That(File.Exists(Path.Combine(Path.GetTempPath(), captureDescriptor.Data.Replace("\\", "") + ".chk")), Is.True);
                }
        }
Exemplo n.º 21
0
        public void ActivityIsCommittedAndEnded()
        {
            var eventStream     = new Mock <EventStream>();
            var pipelineContext = new Mock <IPipelineContext>();

            pipelineContext.Setup(pc => pc.GetEventStream()).Returns(eventStream.Object);

            var message = new MessageMock();

            message.Setup(m => m.GetProperty(BtsProperties.InboundTransportLocation)).Returns("inbound-transport-location");

            var sut = new MessagingStep(pipelineContext.Object, message.Object);

            using (var trackingStream = new TrackingStream(new MemoryStream(_content)))
            {
                // TrackActivity is supposed to occur at stream's end
                trackingStream.Drain();
                sut.TrackActivity(ActivityTrackingModes.Step, trackingStream);
            }

            eventStream.Verify(s => s.UpdateActivity(nameof(MessagingStep), sut.ActivityId, It.IsAny <object[]>()), Times.Once());
            eventStream.Verify(s => s.Flush(), Times.Once());
            eventStream.Verify(s => s.EndActivity(nameof(MessagingStep), sut.ActivityId), Times.Once());
        }
Exemplo n.º 22
0
 internal override void TrackActivity(ActivityTrackingModes trackingModes, TrackingStream trackingStream)
 {
     throw new NotSupportedException();
 }