public XPathStream(XmlReader reader, Encoding encoding, SchemaMetaData schemaMetaData,IBaseMessageContext context)
        {
            m_context = context;

            m_schemaMetaData = schemaMetaData;

            xPathCollection = new XPathCollection();

            foreach (var item in m_schemaMetaData.Properties)
            {
                xPathCollection.Add(item.Key);
            }
           

            m_bodyPath = new LinkedList<string>();

            m_outputStream = new MemoryStream();

            this.m_reader = new XPathReader(reader, xPathCollection);
            

            this.m_writer = XmlWriter.Create(this.m_outputStream);

          
        }
        protected override void Open()
        {
            if (_xpath == null)
            {
                _xmlReader = _stream != null?
                             XmlTextReader.Create(_stream, _settings) :
                                 XmlTextReader.Create(_url, _settings);
            }
            else
            {
                var xpaths = new XPathCollection();
                xpaths.Add(_xpath);

                var inner = _stream != null ?
                            new XmlTextReader(_stream) :
                            new XmlTextReader(_url);

                inner.Namespaces = !_ignoreNamespaces;
                if (_settings != null)
                {
                    // TODO: map more XmlReaderSettings to XmlTextReader properties (check in reflector)
                    if (_settings.IgnoreWhitespace)
                    {
                        inner.WhitespaceHandling = WhitespaceHandling.None;
                    }
                    inner.DtdProcessing = _settings.DtdProcessing;
                }

                _xmlReader = new XPathReader(inner, xpaths);
            }
        }
Example #3
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

            if (!Validate(out errorMessage))
            {
                throw new ArgumentException(errorMessage);
            }

            String value = null;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            Stream                 inboundStream          = bodyPart.GetOriginalDataStream();
            VirtualStream          virtualStream          = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream);

            XmlTextReader   xmlTextReader   = new XmlTextReader(readOnlySeekableStream);
            XPathCollection xPathCollection = new XPathCollection();
            XPathReader     xPathReader     = new XPathReader(xmlTextReader, xPathCollection);

            xPathCollection.Add(XPath);

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(0))
                {
                    if (xPathReader.NodeType == XmlNodeType.Attribute)
                    {
                        value = xPathReader.GetAttribute(xPathReader.Name);
                    }
                    else
                    {
                        value = xPathReader.ReadString();
                    }

                    if (PromoteProperty)
                    {
                        pInMsg.Context.Promote(new ContextProperty(PropertyPath), value);
                    }
                    else
                    {
                        pInMsg.Context.Write(new ContextProperty(PropertyPath), value);
                    }

                    break;
                }
            }

            if (string.IsNullOrEmpty(value) && ThrowIfNoMatch)
            {
                throw new InvalidOperationException("The specified XPath did not exist or contained an empty value.");
            }

            readOnlySeekableStream.Position = 0;
            pContext.ResourceTracker.AddResource(readOnlySeekableStream);
            bodyPart.Data = readOnlySeekableStream;

            return(pInMsg);
        }
Example #4
0
        protected override void Open()
        {
            if (_xpath == null)
            {
                _xmlReader = _stream != null?
                             XmlTextReader.Create(_stream, _settings) :
                                 XmlTextReader.Create(_url, _settings);
            }
            else
            {
                var xpaths = new XPathCollection();
                xpaths.Add(_xpath);
                NameTable n = new NameTable();
                xpaths.NamespaceManager = new XmlNamespaceManager(n);
                //xpaths.NamespaceManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
                var inner = _stream != null ?
                            new XmlTextReader(_stream) :
                            new XmlTextReader(_url);
                inner.Namespaces = true;

                //inner.Namespaces = !_ignoreNamespaces;
                if (_settings != null)
                {
                    // TODO: map more XmlReaderSettings to XmlTextReader properties (check in reflector)
                    if (_settings.IgnoreWhitespace)
                    {
                        inner.WhitespaceHandling = WhitespaceHandling.None;
                    }
                    inner.DtdProcessing = _settings.DtdProcessing;
                }

                _xmlReader = new XPathReader(inner, xpaths);
            }
        }
Example #5
0
        /// <summary>
        /// Get a node name or namespace based on an XPATH query run against the body stream
        /// </summary>
        /// <param name="_XPathResultType"></param>
        /// <param name="_XPathQuery"></param>
        /// <returns></returns>
        private void SetMessageTypeVariables()
        {
            string _XPathQuery = "/*";

            try
            {
                XmlTextReader   xmlTextReader   = new XmlTextReader(documentStream);
                XPathCollection xPathCollection = new XPathCollection();
                xPathCollection.Add(_XPathQuery);

                XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection);

                while (xPathReader.ReadUntilMatch())
                {
                    if (xPathReader.Match(_XPathQuery))
                    {
                        rootNodeName             = xPathReader.LocalName;
                        rootNodeNamespace        = xPathReader.NamespaceURI;
                        messageTypePropertiesSet = true;
                    }
                }
            }
            catch
            {
                //Don't rethrow the exception, if it's a flat file set message type properties to blank values
                rootNodeName             = "";
                rootNodeNamespace        = "";
                messageTypePropertiesSet = true;
            }

            documentStream.Position = 0;
        }
Example #6
0
        public void Execute(ref IBaseMessage inmsg, IPipelineContext pc)
        {
            string _XPathQuery       = "/*";
            string rootNodeName      = string.Empty;
            string rootNodeNamespace = string.Empty;

            XmlTextReader   xmlTextReader   = new XmlTextReader(inmsg.BodyPart.GetOriginalDataStream());
            XPathCollection xPathCollection = new XPathCollection();

            xPathCollection.Add(_XPathQuery);

            XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection);

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(_XPathQuery))
                {
                    rootNodeName      = xPathReader.LocalName;
                    rootNodeNamespace = xPathReader.NamespaceURI;
                }
            }

            inmsg.Context.Promote(BizTalkGlobalPropertySchemaEnum.MessageType.ToString(), ContextPropertyNamespaces._BTSPropertyNamespace, string.Format("{0}#{1}", rootNodeNamespace, rootNodeName));
            inmsg.BodyPart.Data.Position = 0;
        }
        public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

            if (!Validate(out errorMessage))
            {
                throw new ArgumentException(errorMessage);
            }

            var data = pInMsg.BodyPart.GetOriginalDataStream();

            const int bufferSize    = 0x280;
            const int thresholdSize = 0x100000;

            if (!data.CanSeek || !data.CanRead)
            {
                data = new ReadOnlySeekableStream(data, new VirtualStream(bufferSize, thresholdSize), bufferSize);
                pContext.ResourceTracker.AddResource(data);
            }
            XmlTextReader   xmlTextReader   = new XmlTextReader(data);
            XPathCollection xPathCollection = new XPathCollection();
            XPathReader     xPathReader     = new XPathReader(xmlTextReader, xPathCollection);

            xPathCollection.Add(Xpath);
            var  ms        = new MemoryStream();
            int  readBytes = 0;
            bool found     = false;

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(0))
                {
                    var    bw     = new BinaryWriter(ms);
                    byte[] buffer = new byte[bufferSize];

                    while ((readBytes = xPathReader.BaseReader.ReadElementContentAsBase64(buffer, 0, bufferSize)) > 0)
                    {
                        bw.Write(buffer);
                    }
                    bw.Flush();
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                throw new ArgumentException("Could not element at specified xpath");
            }

            ms.Seek(0, SeekOrigin.Begin);
            ms.Position = 0;

            var docType = Microsoft.BizTalk.Streaming.Utils.GetDocType(new MarkableForwardOnlyEventingReadStream(ms));

            pInMsg.Context.Promote(new ContextProperty(SystemProperties.MessageType), docType);
            pInMsg.BodyPart.Data = ms;
            _outputQueue.Enqueue(pInMsg);
        }
Example #8
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            String value   = null;
            bool   suspend = false;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;



            Stream                 inboundStream          = bodyPart.GetOriginalDataStream();
            VirtualStream          virtualStream          = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream);

            XmlTextReader   xmlTextReader   = new XmlTextReader(readOnlySeekableStream);
            XPathCollection xPathCollection = new XPathCollection();
            XPathReader     xPathReader     = new XPathReader(xmlTextReader, xPathCollection);

            xPathCollection.Add(XPath);

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(0))
                {
                    if (xPathReader.NodeType == XmlNodeType.Attribute)
                    {
                        value = xPathReader.GetAttribute(xPathReader.Name);
                    }
                    else
                    {
                        value = xPathReader.ReadString();
                    }

                    break;
                }
            }


            suspend = ScriptExpressionHelper.ValidateExpression(value, Expression);

            if (suspend)
            {
                readOnlySeekableStream.Position = 0;
                pContext.ResourceTracker.AddResource(readOnlySeekableStream);
                bodyPart.Data = readOnlySeekableStream;
                pInMsg.Context.Write("SuspendAsNonResumable", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true);
                pInMsg.Context.Write("SuppressRoutingFailureDiagnosticInfo", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true);

                throw new Exception(String.Format("Expression {0} {1} did not evaluate to true", value, Expression));
            }
            else
            {
                pInMsg = null;
            }


            return(pInMsg);
        }
Example #9
0
        private XPathCollection GetXPathCollection()
        {
            XPathCollection _XPathCollection = new XPathCollection();

            foreach (var _XPathInstruction in _XPathInstructions)
            {
                _XPathCollection.Add(_XPathInstruction.XPathQuery);
            }

            return(_XPathCollection);
        }
Example #10
0
        public void Execute(ref IBaseMessage inmsg, IPipelineContext pc)
        {
            XmlTextReader   xmlTextReader   = new XmlTextReader(inmsg.BodyPart.GetOriginalDataStream());
            XPathCollection xPathCollection = GetXPathCollection();
            XPathReader     xPathReader     = new XPathReader(xmlTextReader, xPathCollection);

            while (xPathReader.ReadUntilMatch())
            {
                for (int i = 0; i < xPathCollection.Count; i++)
                {
                    if (xPathReader.Match(i))
                    {
                        string value = null;

                        _XPathInstructions.ElementAt(i).IsFound = true;
                        switch (_XPathInstructions.ElementAt(i).XPathResultType)
                        {
                        case XPathResultTypeEnum.Name:
                            value = xPathReader.LocalName;
                            break;

                        case XPathResultTypeEnum.Namespace:
                            value = xPathReader.NamespaceURI;
                            break;

                        case XPathResultTypeEnum.Value:
                            value = xPathReader.ReadString();
                            break;
                        }

                        if (_XPathInstructions.ElementAt(i).Promotion == ContextInstructionTypeEnum.Promote)
                        {
                            inmsg.Context.Promote(_XPathInstructions.ElementAt(i).PropertyName, _XPathInstructions.ElementAt(i).PropertyNamespace, TypeCaster.GetTypedObject(value, _XPathInstructions.ElementAt(i).Type));
                        }
                        else
                        {
                            inmsg.Context.Write(_XPathInstructions.ElementAt(i).PropertyName, _XPathInstructions.ElementAt(i).PropertyNamespace, TypeCaster.GetTypedObject(value, _XPathInstructions.ElementAt(i).Type));
                        }
                    }
                }
            }

            for (int i = 0; i < xPathCollection.Count; i++)
            {
                if (_XPathInstructions.ElementAt(i).IsFound == false && _XPathInstructions.ElementAt(i).ExceptionIfNotFound == true)
                {
                    throw new Exception("Unable to evaluate XPath expression " + _XPathInstructions.ElementAt(i).XPathQuery + " against the message.");
                }
            }

            inmsg.BodyPart.Data.Position = 0;
        }
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

            if (!Validate(out errorMessage))
            {
                throw new ArgumentException(errorMessage);
            }

            String value = null;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            Stream inboundStream = bodyPart.GetOriginalDataStream();
            VirtualStream virtualStream = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream);

            XmlTextReader xmlTextReader = new XmlTextReader(readOnlySeekableStream);
            XPathCollection xPathCollection = new XPathCollection();
            XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection);
            xPathCollection.Add(XPath);

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(0))
                {
                    value = xPathReader.ReadString();

                    if (PromoteProperty)
                    {
                        pInMsg.Context.Promote(new ContextProperty(PropertyPath), value);
                    }
                    else
                    {
                        pInMsg.Context.Write(new ContextProperty(PropertyPath), value);
                    }

                    break;
                }
            }

            if (string.IsNullOrEmpty(value) && ThrowIfNoMatch)
            {
                throw new InvalidOperationException("The specified XPath did not exist or contained an empty value.");
            }

            readOnlySeekableStream.Position = 0;
            pContext.ResourceTracker.AddResource(readOnlySeekableStream);
            bodyPart.Data = readOnlySeekableStream;

            return pInMsg;
        }
        public static Dictionary <string, string> SelectMultiple(this IBaseMessage pInMsg, params string[] xPaths)
        {
            Stream inboundStream          = pInMsg.BodyPart.GetOriginalDataStream();
            var    virtualStream          = new VirtualStream();
            var    readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream);

            readOnlySeekableStream.Seek(0, SeekOrigin.Begin);
            var xmlTextReader = new XmlTextReader(readOnlySeekableStream);

            var xPathCollection = new XPathCollection();

            //Keep track of the mapping between XPaths and their position in the XPathCollection
            var indexToXPathMap = new Dictionary <int, string>();

            foreach (var xPath in xPaths)
            {
                int index = xPathCollection.Add(xPath);
                indexToXPathMap.Add(index, xPath);
            }

            var xPathReader = new XPathReader(xmlTextReader, xPathCollection);

            var xPathToValueMap = new Dictionary <string, string>();

            while (xPathReader.ReadUntilMatch())
            {
                string value = xPathReader.NodeType == XmlNodeType.Attribute ?
                               xPathReader.GetAttribute(xPathReader.Name) :
                               xPathReader.ReadString();

                //Which XPath triggered the match
                int index = indexToXPathMap.Keys.First(x => xPathReader.Match(x));

                //Only return the first match for each XPath
                if (!xPathToValueMap.ContainsKey(indexToXPathMap[index]))
                {
                    xPathToValueMap.Add(indexToXPathMap[index], value);
                }
            }

            readOnlySeekableStream.Seek(0, SeekOrigin.Begin);
            return(xPathToValueMap);
        }
Example #13
0
        /// <summary>
        /// Get the result of an XPath expression on the given message
        /// </summary>
        /// <param name="_XPathResultType">Whether the resulting node's value, name, or namspace should be treated as the result</param>
        /// <param name="_XPathQuery">The XPath Expression</param>
        /// <param name="exceptionIfNotFound">Whether or not to thrown an exception if the XPath expression does not evaluate</param>
        /// <returns>The result of an XPath expression on the given message</returns>
        public string GetXPathResult(XPathResultTypeEnum _XPathResultType, string _XPathQuery, bool exceptionIfNotFound)
        {
            XmlTextReader   xmlTextReader   = new XmlTextReader(base.InMsg.BodyPart.GetOriginalDataStream());
            XPathCollection xPathCollection = new XPathCollection();

            xPathCollection.Add(_XPathQuery);

            XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection);
            bool        isFound     = false;
            string      value       = null;

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(_XPathQuery))
                {
                    isFound = true;
                    switch (_XPathResultType)
                    {
                    case XPathResultTypeEnum.Name:
                        value = xPathReader.LocalName;
                        break;

                    case XPathResultTypeEnum.Namespace:
                        value = xPathReader.NamespaceURI;
                        break;

                    case XPathResultTypeEnum.Value:
                        value = xPathReader.ReadString();
                        break;
                    }
                }
            }

            if ((isFound == false) && (exceptionIfNotFound))
            {
                base.SetException(new Exception("No result found for XPath query - " + _XPathQuery));
            }

            base.InMsg.BodyPart.Data.Position = 0;
            return(value);
        }
        public IEnumerable <ISearchResult> FindAllForwardOnly(ITextSource document, int offset, int length)
        {
            var xc = new XPathCollection();

            try
            {
                xc.Add(_xPath);
            }
            catch (Exception)
            {
                yield break;
            }
            using (var reader = new XmlTextReader(document.CreateReader()))
                using (var xpathReader = new XPathReader(reader, xc))
                {
                    var      lineInfo = xpathReader as IXmlLineInfo;
                    var      doc      = (IDocument)document;
                    ISegment segment;

                    while (Read(xpathReader))
                    {
                        if (xpathReader.Match(0) && xpathReader.NodeType != XmlNodeType.EndElement)
                        {
                            segment = null;
                            try
                            {
                                segment = XmlSegment(doc, lineInfo.LineNumber, lineInfo.LinePosition);
                            }
                            catch (Exception) { }
                            if (segment != null && segment.Offset >= offset && segment.EndOffset <= (offset + length))
                            {
                                yield return(new XPathSearchResult()
                                {
                                    StartOffset = segment.Offset,
                                    Length = segment.Length
                                });
                            }
                        }
                    }
                }
        }
        public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
        {
            IBaseMessagePart bodyPart = pInMsg.BodyPart;
            Stream inboundStream = bodyPart.GetOriginalDataStream();
            VirtualStream virtualStream = new VirtualStream(0x280, 0x100000);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream, 0x280);
            XmlTextReader xmlTextReader = new XmlTextReader(readOnlySeekableStream);
            XPathCollection xPathCollection = new XPathCollection();
            xPathCollection.Add("/*[local-name()='LFT' and namespace-uri()='http://Codit.LFT.Schemas']/*[local-name()='TempFile' and namespace-uri()='']");
            XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection);
            bool ok = false;
            string val = string.Empty;
            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(0) && !ok)
                {
                    val = xPathReader.ReadString();
                    ok = true;
                }
            }
            if (ok)
            {
                VirtualStream outboundStream = new VirtualStream(0x280, 0xA00000);
                using (FileStream fs = new FileStream(val, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead = fs.Read(buffer, 0, buffer.Length);
                    while (bytesRead != 0)
                    {
                        outboundStream.Write(buffer, 0, bytesRead);
                        outboundStream.Flush();
                        bytesRead = fs.Read(buffer, 0, buffer.Length);
                    }
                }
                outboundStream.Position = 0;
                bodyPart.Data = outboundStream;
            }

            return pInMsg;
        }
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            bool terminate = true;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;



            Stream                 inboundStream          = bodyPart.GetOriginalDataStream();
            VirtualStream          virtualStream          = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream);

            XmlTextReader   xmlTextReader   = new XmlTextReader(readOnlySeekableStream);
            XPathCollection xPathCollection = new XPathCollection();
            XPathReader     xPathReader     = new XPathReader(xmlTextReader, xPathCollection);

            xPathCollection.Add(XPath);

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(0))
                {
                    terminate = false;
                    inboundStream.Seek(0, SeekOrigin.Begin);
                    break;
                }
            }


            if (terminate == true)
            {
                pInMsg = null;
            }


            return(pInMsg);
        }
Example #17
0
        internal static XPathCollection Create(string bodyXPath)
        {
            var segments = RegexCache.Instance[PATTERN].Matches(bodyXPath).Cast <Match>()
                           .Where(m => m.Success)
                           .Select(m => m.Value);

            if (!segments.Any())
            {
                throw new ArgumentException("Body XPath does not match expected pattern.", nameof(bodyXPath));
            }

            var collection  = new XPathCollection();
            var partialPath = string.Empty;

            foreach (var segment in segments)
            {
                collection.Add(partialPath += segment);
            }
            if (partialPath.Length != bodyXPath.Length)
            {
                throw new ArgumentException("Body XPath could not be entirely parsed.", nameof(bodyXPath));
            }
            return(collection);
        }
        public static void Mutate(this IBaseMessage pInMsg,
                                  Dictionary <string, Func <string, string> > xPathToMutatorMap)
        {
            var xPathCollection = new XPathCollection();

            foreach (var xPath in xPathToMutatorMap.Keys)
            {
                xPathCollection.Add(xPath);
            }

            Stream inboundStream = pInMsg.BodyPart.GetOriginalDataStream();
            var    virtualStream = new VirtualStream(inboundStream);

            ValueMutator valueMutator = delegate(int matchIdx, XPathExpression matchExpr,
                                                 string origVal, ref string finalVal)
            {
                var mutator = xPathToMutatorMap[matchExpr.XPath];
                finalVal = mutator(origVal);
            };

            var xPathMutatorStream = new XPathMutatorStream(virtualStream, xPathCollection, valueMutator);

            pInMsg.BodyPart.Data = xPathMutatorStream;
        }
        private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem tvi = (TreeViewItem)e.Source;
            TreeNodeViewModel treeNode = (TreeNodeViewModel)tvi.Header;

            if (treeNode != null)
            {
                string xpathBase = treeNode.getXPath();
                string xpath = xpathBase + "/child::*";
                string xpath2 = xpathBase + "/attribute::*";
                string xpath3 = xpathBase + "/text()";

                XPathCollection xpc = new XPathCollection();
                int query = xpc.Add(xpath);
                int query2 = xpc.Add(xpath2);
                int query3 = xpc.Add(xpath3);

                XPathReader xreader = new XPathReader(ModelTree.modelFile, xpc);

                //MessageBox.Show("expanded -> " + xpath);

                treeNode.generateChildren(xreader);

                e.Handled = true;
            }
            else
                MessageBox.Show("Nist agha!");
        }
Example #20
0
 private XmlEnvelopeDecodingStream(XmlReader reader, XPathCollection xpathExpressions) : base(new XPathReader(reader, xpathExpressions))
 {
     XPathReader = (XPathReader)m_reader;
 }
Example #21
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);
                        }
                    }
                }
            }
        }
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            bool   found      = false;
            string value      = string.Empty;
            string evalString = string.Empty;

            Stream                 inboundStream          = bodyPart.GetOriginalDataStream();
            VirtualStream          virtualStream          = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream);

            XmlTextReader   xmlTextReader   = new XmlTextReader(readOnlySeekableStream);
            XPathCollection xPathCollection = new XPathCollection();
            XPathReader     xPathReader     = new XPathReader(xmlTextReader, xPathCollection);

            int lastxpath = XPath.LastIndexOf("][");

            if (lastxpath > -1)
            {
                evalString = XPath.Substring(lastxpath + 2, XPath.LastIndexOf(']') - (lastxpath + 2));
                XPath      = XPath.Substring(0, lastxpath + 1);

                if (evalString.Contains("text(") || evalString.Contains("number("))
                {
                    evalString = evalString.Substring(evalString.IndexOf(')') + 1);
                }

                evalString = replaceHTMLOpearators(evalString);

                if (evalString.Contains(" = "))//c# equal sign
                {
                    evalString = evalString.Replace("=", "==");
                }
            }

            xPathCollection.Add(XPath);

            while (xPathReader.ReadUntilMatch())
            {
                if (xPathReader.Match(0))
                {
                    if (evalString != string.Empty)
                    {
                        if (xPathReader.NodeType == XmlNodeType.Attribute)
                        {
                            value = xPathReader.GetAttribute(xPathReader.Name);
                        }
                        else
                        {
                            value = xPathReader.ReadString();
                        }

                        string literal = String.Empty;
                        if (evalString.Contains("'"))
                        {
                            literal    = "\"";
                            evalString = evalString.Replace("'", "\"");
                        }

                        found = ScriptExpressionHelper.ValidateExpression(String.Format("{0}{1}{0}", literal, value), evalString);
                    }
                    else
                    {
                        found = true;
                    }



                    break;
                }
            }

            readOnlySeekableStream.Seek(0, SeekOrigin.Begin);
            pInMsg.BodyPart.Data = readOnlySeekableStream;

            if (found)
            {
                pInMsg = null;
            }


            return(pInMsg);
        }
Example #23
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);
                        }
                    }
                }
            }
        }