Example #1
0
        /// <summary>
        /// Executes the custom runtime task component to process the input message and returns the result message.
        /// </summary>
        /// <param name="pContext">A reference to <see cref="Microsoft.BizTalk.Component.Interop.IPipelineContext"/> object that contains the current pipeline context.</param>
        /// <param name="pInMsg">A reference to <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object that contains the message to process.</param>
        /// <returns>A reference to the returned <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object which will contain the output message.</returns>
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            Guard.ArgumentNotNull(pContext, "pContext");
            Guard.ArgumentNotNull(pInMsg, "pInMsg");

            var callToken = TraceManager.PipelineComponent.TraceIn();

            if (pInMsg.BodyPart != null)
            {
                Stream messageDataStream = BizTalkUtility.EnsureSeekableStream(pInMsg, pContext);

                if (messageDataStream != null)
                {
                    try
                    {
                        XmlReaderSettings readerSettings = new XmlReaderSettings()
                        {
                            CloseInput = false, CheckCharacters = false, IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true, ValidationType = ValidationType.None
                        };

                        using (XmlReader messageDataReader = XmlReader.Create(messageDataStream, readerSettings))
                        {
                            XElement            eventDataXml = XElement.Load(messageDataReader);
                            TraceEventRecord    eventRecord;
                            ITraceEventProvider traceProvider = null;

                            var traceEventRecords = eventDataXml.Descendants(XName.Get(WellKnownContractMember.MessageParameters.TraceEvents, eventDataXml.Name.Namespace.NamespaceName)).Descendants(XName.Get(traceEventRecordAttr.Name, traceEventRecordAttr.Namespace));

                            foreach (var r in traceEventRecords)
                            {
                                eventRecord   = TraceEventRecord.Create(XmlReader.Create(r.CreateReader(), readerSettings));
                                traceProvider = TraceManager.Create(eventRecord.EventSourceId);

                                if (traceProvider != null)
                                {
                                    traceProvider.TraceEvent(eventRecord);
                                }
                                else
                                {
                                    object[] parameters = new object[] { eventRecord.Message, eventRecord.EventId, eventRecord.EventSource, eventRecord.MachineName, eventRecord.ProcessName, eventRecord.ProcessId, eventRecord.ThreadId, eventRecord.DateTime.ToString("o") };
                                    TraceManager.PipelineComponent.TraceWarning(TraceLogMessages.NoTraceProviderFound, eventRecord.EventSource, String.Format(CultureInfo.InvariantCulture, Resources.TraceEventMessageFormatString, parameters));
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (messageDataStream.CanSeek)
                        {
                            messageDataStream.Seek(0, SeekOrigin.Begin);
                        }
                    }
                }
            }

            TraceManager.PipelineComponent.TraceOut(callToken);
            return(pInMsg);
        }
Example #2
0
        /// <summary>
        /// Executes the custom runtime task component to process the input message and returns the result message.
        /// </summary>
        /// <param name="pContext">A reference to <see cref="Microsoft.BizTalk.Component.Interop.IPipelineContext"/> object that contains the current pipeline context.</param>
        /// <param name="pInMsg">A reference to <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object that contains the message to process.</param>
        /// <returns>A reference to the returned <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object which will contain the output message.</returns>
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            Guard.ArgumentNotNull(pContext, "pContext");
            Guard.ArgumentNotNull(pInMsg, "pInMsg");

            var callToken = TraceManager.PipelineComponent.TraceIn();

            if (pInMsg.BodyPart != null)
            {
                Stream messageDataStream = BizTalkUtility.EnsureSeekableStream(pInMsg, pContext);

                if (messageDataStream != null)
                {
                    try
                    {
                        XmlReaderSettings readerSettings = new XmlReaderSettings()
                        {
                            CloseInput = false, CheckCharacters = false, IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true, ValidationType = ValidationType.None
                        };

                        using (XmlReader messageDataReader = XmlReader.Create(messageDataStream, readerSettings))
                        {
                            ActivityBase genericActivity = ActivityBase.Create(messageDataReader);

                            if (genericActivity != null)
                            {
                                using (IActivityTrackingEventStream eventStream = ActivityTrackingEventStreamFactory.CreateEventStream(pContext))
                                {
                                    string methodName = pInMsg.Context.Read(SoapMethodProperty.Name.Name, SoapMethodProperty.Name.Namespace) as string;

                                    if (!String.IsNullOrEmpty(methodName))
                                    {
                                        if (methodName.EndsWith(Resources.BeginActivityMethodName))
                                        {
                                            eventStream.BeginActivity(genericActivity);
                                        }
                                        else if (methodName.EndsWith(Resources.UpdateActivityMethodName))
                                        {
                                            eventStream.UpdateActivity(genericActivity);
                                        }
                                        else if (methodName.EndsWith(Resources.CompleteActivityMethodName))
                                        {
                                            eventStream.CompleteActivity(genericActivity);
                                        }
                                    }
                                    else
                                    {
                                        TraceManager.PipelineComponent.TraceWarning(TraceLogMessages.CannotDetermineSoapAction, this.GetType().Name, SoapMethodProperty.Name.Name, SoapMethodProperty.Name.Namespace);
                                    }
                                }
                            }
                            else
                            {
                                TraceManager.PipelineComponent.TraceWarning(TraceLogMessages.CannotDeserializeActivityMessage, this.GetType().Name, typeof(ActivityBase).FullName);
                            }
                        }
                    }
                    finally
                    {
                        if (messageDataStream.CanSeek)
                        {
                            messageDataStream.Seek(0, SeekOrigin.Begin);
                        }
                    }
                }
            }

            TraceManager.PipelineComponent.TraceOut(callToken);
            return(pInMsg);
        }
Example #3
0
        /// <summary>
        /// Synchronously executes the task using the specified <see cref="RuntimeTaskExecutionContext"/> execution context object.
        /// </summary>
        /// <param name="context">The execution context.</param>
        public override void Run(RuntimeTaskExecutionContext context)
        {
            Guard.ArgumentNotNull(context, "context");
            Guard.ArgumentNotNull(context.Message, "context.Message");

            var callToken = TraceManager.PipelineComponent.TraceIn();

            Stream messageDataStream = null;
            IEnumerable <object> facts = null;
            string             policyName = PolicyName, ctxPropName = null, ctxPropNamespace = null;
            Version            policyVersion = PolicyVersion;
            RulesEngineRequest request       = null;
            bool responseRequired            = true;

            try
            {
                XmlReaderSettings readerSettings = new XmlReaderSettings()
                {
                    CloseInput = false, CheckCharacters = false, IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true, ValidationType = ValidationType.None
                };

                if (context.Message.BodyPart != null)
                {
                    messageDataStream = BizTalkUtility.EnsureSeekableStream(context.Message, context.PipelineContext);

                    if (messageDataStream != null)
                    {
                        using (XmlReader messageDataReader = XmlReader.Create(messageDataStream, readerSettings))
                        {
                            // Navigate through the XML reader until we find an element with the expected name and namespace.
                            while (!messageDataReader.EOF && messageDataReader.Name != WellKnownContractMember.MessageParameters.Request && messageDataReader.NamespaceURI != WellKnownNamespace.DataContracts.General)
                            {
                                messageDataReader.Read();
                            }

                            // Element was found, let's perform de-serialization from XML into a RulesEngineRequest object.
                            if (!messageDataReader.EOF)
                            {
                                DataContractSerializer serializer = new DataContractSerializer(typeof(RulesEngineRequest));
                                request = serializer.ReadObject(messageDataReader, false) as RulesEngineRequest;

                                if (request != null)
                                {
                                    policyName    = request.PolicyName;
                                    policyVersion = request.PolicyVersion;
                                    facts         = request.Facts;
                                }
                            }
                        }
                    }
                }

                // Check if the policy name was supplied when this component was instantiated or retrieved from a request message.
                if (!String.IsNullOrEmpty(policyName))
                {
                    // If policy version is not specified, use the latest deployed version.
                    PolicyExecutionInfo policyExecInfo = policyVersion != null ? new PolicyExecutionInfo(policyName, policyVersion) : new PolicyExecutionInfo(policyName);

                    // Use all context properties as parameters when invoking a policy.
                    for (int i = 0; i < context.Message.Context.CountProperties; i++)
                    {
                        ctxPropName      = null;
                        ctxPropNamespace = null;

                        object ctxPropValue = context.Message.Context.ReadAt(i, out ctxPropName, out ctxPropNamespace);
                        policyExecInfo.AddParameter(String.Format("{0}#{1}", ctxPropNamespace, ctxPropName), ctxPropValue);
                    }

                    // If we still haven't determined what facts should be passed to the policy, let's use the request message as a single fact.
                    if (null == facts)
                    {
                        if (messageDataStream != null)
                        {
                            // Unwind the data stream back to the beginning.
                            messageDataStream.Seek(0, SeekOrigin.Begin);

                            // Read the entire message into a BRE-compliant type XML document.
                            using (XmlReader messageDataReader = XmlReader.Create(messageDataStream, readerSettings))
                            {
                                facts            = new object[] { new TypedXmlDocument(Resources.DefaultTypedXmlDocumentTypeName, messageDataReader) };
                                responseRequired = false;
                            }
                        }
                    }

                    // Execute a BRE policy.
                    PolicyExecutionResult policyExecResult = PolicyHelper.Execute(policyExecInfo, facts);

                    // CHeck if we need to return a response. We don't need to reply back if we are not handling ExecutePolicy request message.
                    if (responseRequired)
                    {
                        // Construct a response message.
                        RulesEngineResponse response = new RulesEngineResponse(policyExecResult.PolicyName, policyExecResult.PolicyVersion, policyExecResult.Success);

                        // Add all facts that were being used when invoking the policy.
                        response.AddFacts(facts);

                        // Create a response message.
                        IBaseMessagePart  responsePart = BizTalkUtility.CreateResponsePart(context.PipelineContext.GetMessageFactory(), context.Message);
                        XmlWriterSettings settings     = new XmlWriterSettings();

                        // Initialize a new stream that will hold the response message payload.
                        MemoryStream dataStream = new MemoryStream();
                        context.PipelineContext.ResourceTracker.AddResource(dataStream);

                        settings.CloseOutput       = false;
                        settings.CheckCharacters   = false;
                        settings.ConformanceLevel  = ConformanceLevel.Fragment;
                        settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;

                        using (XmlWriter responseWriter = XmlWriter.Create(dataStream, settings))
                        {
                            responseWriter.WriteResponseStartElement("r", WellKnownContractMember.MethodNames.ExecutePolicy, WellKnownNamespace.ServiceContracts.General);

                            DataContractSerializer dcSerializer = new DataContractSerializer(typeof(RulesEngineResponse), String.Concat(WellKnownContractMember.MethodNames.ExecutePolicy, WellKnownContractMember.ResultMethodSuffix), WellKnownNamespace.ServiceContracts.General);
                            dcSerializer.WriteObject(responseWriter, response);

                            responseWriter.WriteEndElement();
                            responseWriter.Flush();
                        }

                        dataStream.Seek(0, SeekOrigin.Begin);
                        responsePart.Data = dataStream;
                    }
                    else
                    {
                        if (facts != null)
                        {
                            TypedXmlDocument xmlDoc = facts.Where((item) => { return(item.GetType() == typeof(TypedXmlDocument)); }).FirstOrDefault() as TypedXmlDocument;

                            if (xmlDoc != null)
                            {
                                // Initialize a new stream that will hold the response message payload.
                                MemoryStream dataStream = new MemoryStream();
                                context.PipelineContext.ResourceTracker.AddResource(dataStream);

                                XmlWriterSettings settings = new XmlWriterSettings
                                {
                                    CloseOutput       = false,
                                    CheckCharacters   = false,
                                    ConformanceLevel  = ConformanceLevel.Fragment,
                                    NamespaceHandling = NamespaceHandling.OmitDuplicates
                                };

                                using (XmlWriter dataWriter = XmlWriter.Create(dataStream, settings))
                                {
                                    xmlDoc.Document.WriteContentTo(dataWriter);
                                    dataWriter.Flush();
                                }

                                dataStream.Seek(0, SeekOrigin.Begin);
                                context.Message.BodyPart.Data = dataStream;
                            }
                        }
                    }
                }
                else
                {
                    throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, ExceptionMessages.PolicyNameNotSpecified));
                }
            }
            finally
            {
                if (messageDataStream != null && messageDataStream.CanSeek && messageDataStream.Position > 0)
                {
                    messageDataStream.Seek(0, SeekOrigin.Begin);
                }

                TraceManager.PipelineComponent.TraceOut(callToken);
            }
        }
Example #4
0
        /// <summary>
        /// Synchronously executes the task using the specified <see cref="RuntimeTaskExecutionContext"/> execution context object.
        /// </summary>
        /// <param name="context">The execution context.</param>
        public override void Run(RuntimeTaskExecutionContext context)
        {
            string propName, propNamespace;

            // Check if there are any properties with values to be promoted.
            if (this.propertyToValueMap.Count > 0)
            {
                foreach (var property in this.propertyToValueMap)
                {
                    if (TryParsePropertyName(property.Key, out propName, out propNamespace))
                    {
#if DEBUG
                        TraceManager.CustomComponent.TraceDetails("DETAIL: Context property promoted: {0}{1}{2} = {3}", propNamespace, BizTalkUtility.ContextPropertyNameSeparator, propName, property.Value);
#endif
                        context.Message.Context.Promote(propName, propNamespace, property.Value);
                    }
                }
            }

            // Check if there are any properties to be promoted by inspecting the incoming message and capturing property values using XPath.
            if (this.propertyToXPathMap.Count > 0)
            {
                Stream messageDataStream = BizTalkUtility.EnsureSeekableStream(context.Message, context.PipelineContext);

                if (messageDataStream != null)
                {
                    byte[]   buffer = new byte[BizTalkUtility.VirtualStreamBufferSize];
                    string[] propValues = new string[this.propertyToXPathMap.Count];
                    int      arrIndex = 0, matchFound = 0;

                    XPathCollection   xc       = new XPathCollection();
                    XPathQueryLibrary xPathLib = ApplicationConfiguration.Current.XPathQueries;

                    foreach (var property in this.propertyToXPathMap)
                    {
                        propValues[arrIndex++] = property.Key;
                        xc.Add(xPathLib.GetXPathQuery(property.Value));
                    }

                    try
                    {
                        XPathMutatorStream mutator = new XPathMutatorStream(messageDataStream, xc,
                                                                            delegate(int matchIdx, XPathExpression expr, string origValue, ref string finalValue)
                        {
                            if (matchIdx >= 0 && matchIdx < propValues.Length)
                            {
                                if (TryParsePropertyName(propValues[matchIdx], out propName, out propNamespace))
                                {
#if DEBUG
                                    TraceManager.CustomComponent.TraceDetails("DETAIL: Context property promoted: {0}{1}{2} = {3}", propNamespace, BizTalkUtility.ContextPropertyNameSeparator, propName, origValue);
#endif
                                    context.Message.Context.Promote(propName, propNamespace, origValue);
                                }

                                matchFound++;
                            }
                        });

                        while (mutator.Read(buffer, 0, buffer.Length) > 0 && matchFound < propValues.Length)
                        {
                            ;
                        }
                    }
                    finally
                    {
                        if (messageDataStream.CanSeek)
                        {
                            messageDataStream.Seek(0, SeekOrigin.Begin);
                        }
                    }
                }
            }
        }
Example #5
0
        /// <summary>
        /// Synchronously executes the task using the specified <see cref="RuntimeTaskExecutionContext"/> execution context object.
        /// </summary>
        /// <param name="context">The execution context.</param>
        public override void Run(RuntimeTaskExecutionContext context)
        {
            if (this.lateBoundActivityValueMap.Count > 0)
            {
                foreach (var dateTimeMilestone in this.lateBoundActivityValueMap.Where((item) => { return(item.Value == typeof(DateTime)); }))
                {
                    SetActivityData(dateTimeMilestone.Key, DateTime.UtcNow);
                }
            }

            if (this.milestoneToXPathMap.Count > 0)
            {
                Stream messageDataStream = BizTalkUtility.EnsureSeekableStream(context.Message, context.PipelineContext);

                if (messageDataStream != null)
                {
                    byte[]   buffer = new byte[BizTalkUtility.VirtualStreamBufferSize];
                    string[] milestones = new string[this.milestoneToXPathMap.Count];
                    int      arrIndex = 0, matchFound = 0;

                    XPathCollection   xc       = new XPathCollection();
                    XPathQueryLibrary xPathLib = ApplicationConfiguration.Current.XPathQueries;

                    foreach (var listItem in this.milestoneToXPathMap)
                    {
                        milestones[arrIndex++] = listItem.Key;
                        xc.Add(xPathLib.GetXPathQuery(listItem.Value));
                    }

                    try
                    {
                        XPathMutatorStream mutator = new XPathMutatorStream(messageDataStream, xc,
                                                                            delegate(int matchIdx, XPathExpression expr, string origValue, ref string finalValue)
                        {
                            if (matchIdx >= 0 && matchIdx < milestones.Length)
                            {
                                SetActivityData(milestones[matchIdx], origValue);
                                matchFound++;
                            }
                        });

                        while (mutator.Read(buffer, 0, buffer.Length) > 0 && matchFound < milestones.Length)
                        {
                            ;
                        }

                        // Check we had performed continuation token value resolution via XPath.
                        object continuationToken = null;

                        if (CurrentActivity.ActivityData.TryGetValue(ContinuationTokenInternalDataItemName, out continuationToken))
                        {
                            CurrentActivity.ContinuationToken = (string)continuationToken;
                            CurrentActivity.ActivityData.Remove(ContinuationTokenInternalDataItemName);
                        }
                    }
                    finally
                    {
                        if (messageDataStream.CanSeek)
                        {
                            messageDataStream.Seek(0, SeekOrigin.Begin);
                        }
                    }
                }
            }
        }