Search This Blog

Wednesday 7 March 2012

BizTalk 2010 Custom Pipeline Component -Using XPathMutatorStream with MarkableForwardOnlyEventingReadStream

The XPathMutatorStream could be used together with the MarkableForwardOnlyEventingReadStream on the BizTalk Custom Pipeline Component to situations like evaluating  the content of the message based on XPath .
Below is the code snippet .
 public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage InMsg)
        {
           
            // get the original stream into an instance of MarkableForwardOnlyEventingReadStream 
            MarkableForwardOnlyEventingReadStream stream = new MarkableForwardOnlyEventingReadStream(InMsg.BodyPart.GetOriginalDataStream());
           
     //Create an XPathMutatorStream instance
            XPathMutatorStream xpathStream = GetXpathMutatorStream(stream);
            InMsg.BodyPart.Data = xpathStream ;
            pContext.ResourceTracker.AddResource(xpathStream);
            return InMsg;
            ////
        }
  private XPathMutatorStream GetXPathMutatorStream(Stream OriginalStream)
        {
            // Define the Xpath Collection
            XPathCollection XpathQueries = new XPathCollection();
  //you can declare namespaces to get rid of the "ns0" prefix issues as well
            //XpathQueries.NamespaceManager  = new System.Xml.XmlNamespaceManager();
            //XpathQueries.NamespaceManager.AddNamespace("ns0","https://blabla/");
  //Xpath Expressions
            XpathQueries.Add(new XPathExpression(FormatXpathQuery("/InMsg/InField1/")));
            XpathQueries.Add(new XPathExpression(FormatXpathQuery("/InMsg/InField2/")));
            // Add the Mutator to this Stream
            ValueMutator XPathDelegate = new ValueMutator(this.OnXPathMatch);
            XPathMutatorStream xpathStream = new XPathMutatorStream(OriginalStream, XpathQueries, XPathDelegate);
          
            return xpathStream;
        }
  private void OnXPathMatch(int matchIdx, XPathExpression xpathExpr, string ActualValue, ref string ReplaceWith)
        {
            // Any logic which needed to be applied on the value returned from the Xpath .
            if (ActualValue == "quack-quack")
            {
                ReplaceWith = "Duck";
            }
            if (ActualValue == "qluck-qluck")
            {
                ReplaceWith = "Hen";
            }
        }