Exemple #1
0
        private XmlSchema GetMatchingSchema(IPipelineContext pipelineContext, Stream xmlStream)
        {
            XmlSchema     schema             = null;
            IDocumentSpec documentSpecByType = null;
            string        docType            = Utils.GetDocType(MarkableForwardOnlyEventingReadStream.EnsureMarkable(xmlStream));

            try
            {
                documentSpecByType = pipelineContext.GetDocumentSpecByType(docType);
            }
            catch (Exception)
            {
                return(null);
            }
            XmlSchemaSet schemaSet = (documentSpecByType as IDocumentSpec2).GetSchemaSet();

            if (schemaSet.Count == 0)
            {
                return(null);
            }
            foreach (XmlSchema schema2 in schemaSet.Schemas())
            {
                if (docType.Contains(schema2.TargetNamespace + "#"))
                {
                    schema = schema2;
                }
            }
            return(schema);
        }
Exemple #2
0
        /// <summary>
        /// Returns the message type.
        /// </summary>
        /// <param name="context">Pipeline context.</param>
        /// <param name="message">Message instance.</param>
        /// <returns>The message type.</returns>
        public static string GetMessageType(IPipelineContext context, IBaseMessage message)
        {
            MarkableForwardOnlyEventingReadStream stm = new MarkableForwardOnlyEventingReadStream(message.BodyPart.GetOriginalDataStream());

            context.ResourceTracker.AddResource((object)stm);
            return(Utils.GetDocType(stm));
        }
Exemple #3
0
 public Prober(MarkableForwardOnlyEventingReadStream stream)
 {
     if (stream == null)
     {
         throw new ArgumentNullException("stream");
     }
     _stream = stream;
 }
Exemple #4
0
        private MarkableForwardOnlyEventingReadStream MakeMarkable(Stream stream)
        {
            MarkableForwardOnlyEventingReadStream eventingReadStream = null;

            if (stream != null)
            {
                eventingReadStream = stream as MarkableForwardOnlyEventingReadStream ?? new MarkableForwardOnlyEventingReadStream(stream);
            }

            return(eventingReadStream);
        }
Exemple #5
0
        /// <summary>
        /// Provides the <see cref="TrackingStream"/> with probing capabilities without firing any <see
        /// cref="EventingReadStream"/> events.
        /// </summary>
        /// <returns></returns>
        internal MarkableForwardOnlyEventingReadStream AsMarkable()
        {
            // use a markable stream to be able to rewind to the start after capture mode assessment
            var markableForwardOnlyEventingReadStream = MarkableForwardOnlyEventingReadStream.EnsureMarkable(InnerStream);

            // and keep a ref to it to ensure it will be properly disposed
            InnerStream = markableForwardOnlyEventingReadStream;

            // ensure we can rewind TrackingStream
            markableForwardOnlyEventingReadStream.MarkPosition();

            // return markableForwardOnlyEventingReadStream, i.e. InnerStream, and not this TrackingStream to prevent base
            // EventingReadStream class' events from firing while assessing TrackingStream's capture mode
            return(markableForwardOnlyEventingReadStream);
        }
        public void WrapOriginalDataStream()
        {
            var originalStream = new MemoryStream();
            var part           = new Mock <IBaseMessagePart>()
                                 .SetupAllProperties();

            part.Setup(p => p.GetOriginalDataStream())
            .Returns(originalStream);
            var tracker = new Mock <IResourceTracker>();

            System.IO.Stream wrapper = null;
            part.Object.WrapOriginalDataStream(s => wrapper = new MarkableForwardOnlyEventingReadStream(s), tracker.Object);

            part.Object.Data.Should().BeSameAs(wrapper);
            tracker.Verify(t => t.AddResource(wrapper));
        }
Exemple #7
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string stageID = pContext.StageID.ToString("D");

            m_portDirection = PortDirection.send;
            if (stageID == CategoryTypes.CATID_Decoder || stageID == CategoryTypes.CATID_Validate || stageID == CategoryTypes.CATID_PartyResolver)
            {
                m_portDirection = PortDirection.receive;
            }

            if (!string.IsNullOrEmpty(_mapName))
            {
                MarkableForwardOnlyEventingReadStream stream =
                    new MarkableForwardOnlyEventingReadStream(
                        pInMsg.BodyPart.GetOriginalDataStream());

                string messageType = (string)pInMsg.Context.Read("MessageType", _systemPropertiesNamespace);

                if (messageType == String.Empty)
                {
                    stream.MarkPosition();
                    //Thanks to http://maximelabelle.wordpress.com/2010/07/08/determining-the-type-of-an-xml-message-in-a-custom-pipeline-component/
                    messageType = Microsoft.BizTalk.Streaming.Utils.GetDocType(stream);
                    stream.ResetPosition();
                }


                TransformMetaData _map = FindFirstMapMatch(messageType);

                if (_map == null)
                {
                    System.Diagnostics.Debug.WriteLine("No match for map could be made for message type: " + messageType);
                }
                else
                {
                    pInMsg.BodyPart.Data = TransformMessage(stream, _map, pInMsg);

                    pContext.ResourceTracker.AddResource(stream);
                }
            }


            return(pInMsg);
        }
Exemple #8
0
        private string GetMessageType(MarkableForwardOnlyEventingReadStream stm)
        {
            string msgType = null;

            stm.MarkPosition();
            try
            {
                XmlTextReader xmlTextReader = null;

                xmlTextReader = new XmlTextReader((Stream)stm);

                while (msgType == null)
                {
                    if (xmlTextReader.Read())
                    {
                        if (xmlTextReader.NodeType == XmlNodeType.Element && xmlTextReader.Depth == 0)
                        {
                            if (xmlTextReader.NamespaceURI == null || xmlTextReader.NamespaceURI.Length <= 0)
                            {
                                msgType = xmlTextReader.LocalName;
                            }
                            else
                            {
                                msgType = xmlTextReader.NamespaceURI + '#' + xmlTextReader.LocalName;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            finally
            {
                stm.ResetPosition();
            }
            return(msgType);
        }
Exemple #9
0
        private string RecognizeMessageType(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            var stream =
                new MarkableForwardOnlyEventingReadStream(
                    pInMsg.BodyPart.GetOriginalDataStream());

            try
            {
                string messagetype = Utils.GetDocType(stream);

                pInMsg.BodyPart.Data = stream;
                pContext.ResourceTracker.AddResource(stream);

                return(messagetype);
            }

// ReSharper disable once EmptyGeneralCatchClause
            catch (Exception /* e */)
            {
            }

            return(String.Empty);
        }
Exemple #10
0
        public void XsltEntailsMessageTypeIsPromotedOnlyIfOutputMethodIsXml()
        {
            using (var dataStream = new StringStream("<root xmlns='urn:ns'></root>"))
                using (var stream = new MarkableForwardOnlyEventingReadStream(dataStream))
                    using (var transformedStream = dataStream.Transform().Apply(typeof(IdentityTransform)))
                        using (var probeBatchContentStreamMockInjectionScope = new ProbeBatchContentStreamMockInjectionScope())
                            using (var transformStreamMockInjectionScope = new TransformStreamMockInjectionScope())
                            {
                                PipelineContextMock
                                .Setup(m => m.GetDocumentSpecByType("urn:ns#root"))
                                .Returns(SchemaMetadata.For <Batch.Content>().DocumentSpec);

                                MessageMock.Object.BodyPart.Data = stream;

                                probeBatchContentStreamMockInjectionScope.Mock
                                .Setup(ps => ps.BatchDescriptor)
                                .Returns(new BatchDescriptor {
                                    EnvelopeSpecName = SchemaMetadata.For <Envelope>().DocumentSpec.DocSpecStrongName
                                });

                                transformStreamMockInjectionScope.Mock
                                .Setup(ts => ts.ExtendWith(MessageMock.Object.Context))
                                .Returns(transformStreamMockInjectionScope.Mock.Object);
                                transformStreamMockInjectionScope.Mock
                                .Setup(ts => ts.Apply(typeof(AnyToText), Encoding.UTF8))
                                .Returns(transformedStream);

                                var sut = new EnvelopeBuilder {
                                    Encoding = Encoding.UTF8, MapType = typeof(AnyToText)
                                };
                                sut.Execute(PipelineContextMock.Object, MessageMock.Object);

                                MessageMock.Verify(m => m.Promote(BtsProperties.MessageType, It.IsAny <string>()), Times.Never);
                                MessageMock.Verify(m => m.Promote(BtsProperties.SchemaStrongName, It.IsAny <string>()), Times.Never);
                            }
        }
Exemple #11
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            pipelineAssembly = pContext.PipelineName.Substring(pContext.PipelineName.IndexOf(",") + 1).TrimStart();

            /*
             * string stageID = pContext.StageID.ToString("D");
             * m_portDirection = PortDirection.send;
             * if(stageID == CategoryTypes.CATID_Decoder || stageID == CategoryTypes.CATID_Validate || stageID == CategoryTypes.CATID_PartyResolver)
             *  m_portDirection = PortDirection.receive;
             */

            /*2019-05-20 Add map dynamically*/
            //Microsoft.XLANGs.BaseTypes.XmlQName TransformHint = new BTS.SendPortTransformHint().QName; -- Could not use SendPortTransformHint as this would run the map in a "normal mode" and IsDynamic did not need to be set.
            _mapName = _mapName.Trim();


            string map = GetContextTransform(pInMsg.Context);

            if (string.IsNullOrEmpty(map) == false)
            {
                _dynamicMap = true;

                if (string.IsNullOrEmpty(_mapName))
                {
                    _mapName = map;
                }
                else
                {
                    _mapName = String.Format("{0}|{1}", _mapName, map);//Add the map last
                }
            }



            if (string.IsNullOrEmpty(_mapName))
            {
                if (_mapRequired)
                {
                    throw new ArgumentNullException("MapName");
                }
                else
                {
                    return(pInMsg);
                }
            }
            else
            {
                MarkableForwardOnlyEventingReadStream stream =
                    new MarkableForwardOnlyEventingReadStream(
                        pInMsg.BodyPart.GetOriginalDataStream());


                string          schemaStrongName = null;
                string          messageType      = null;
                ContextProperty property         = null;

                if ((schemaStrongName = (string)pInMsg.Context.Read("SchemaStrongName", _systemPropertiesNamespace)) != null)
                {
                    if (schemaStrongName.StartsWith("Microsoft.XLANGs.BaseTypes.Any") == false)
                    {
                        property    = new ContextProperty("SchemaStrongName", _systemPropertiesNamespace);
                        messageType = schemaStrongName;
                    }
                }

                if (messageType == null)
                {
                    messageType = (string)pInMsg.Context.Read("MessageType", _systemPropertiesNamespace);

                    //In cases where XmlDocument is used in orchestration, revert to check MessageType
                    property = new ContextProperty("MessageType", _systemPropertiesNamespace);
                }

                if (messageType == null)
                {
                    property = new ContextProperty("MessageType", _systemPropertiesNamespace);

                    stream.MarkPosition();
                    //Thanks to http://maximelabelle.wordpress.com/2010/07/08/determining-the-type-of-an-xml-message-in-a-custom-pipeline-component/
                    messageType = Microsoft.BizTalk.Streaming.Utils.GetDocType(stream);

                    stream.ResetPosition();
                }

                TransformMetaData _map = FindFirstMapMatch(property, messageType);

                if (_map == null)
                {
                    System.Diagnostics.Debug.WriteLine("No match for map could be made for message type: " + messageType);
                }
                else
                {
                    pInMsg.BodyPart.Data = TransformMessage(stream, _map, pInMsg);

                    pContext.ResourceTracker.AddResource(stream);
                }
            }


            return(pInMsg);
        }
Exemple #12
0
 /// <summary>
 /// Support for <see cref="Stream"/> probing.
 /// </summary>
 /// <param name="stream">
 /// The current <see cref="Stream"/>.
 /// </param>
 /// <returns>
 /// The <see cref="IProbeStream"/> instance that will probe the current <see cref="Stream"/>s.
 /// </returns>
 public static IProbeStream Probe(this MarkableForwardOnlyEventingReadStream stream)
 {
     return(_streamProberFactory(stream));
 }
Exemple #13
0
 /// <summary>
 /// Ensure the <see cref="Stream"/> is wrapped in a <see cref="MarkableForwardOnlyEventingReadStream"/> and
 /// thereby ready for probing, see <see cref="Probe"/>.
 /// </summary>
 /// <param name="stream">
 /// The current <see cref="Stream"/>.
 /// </param>
 /// <returns>
 /// A <see cref="MarkableForwardOnlyEventingReadStream"/> stream.
 /// </returns>
 public static MarkableForwardOnlyEventingReadStream AsMarkable(this Stream stream)
 {
     return(MarkableForwardOnlyEventingReadStream.EnsureMarkable(stream));
 }
Exemple #14
0
        /// <summary>
        /// processes the inbound message part
        /// </summary>
        /// <param name="pc"></param>
        /// <param name="inmsg"></param>
        /// <param name="outmsg"></param>
        /// <param name="part"></param>
        private void ProcessPart(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart part)
        {
            IDocumentSpec docSpec = null;

            Stream dataStream = part.GetOriginalDataStream();
            MarkableForwardOnlyEventingReadStream eventingDataStream = new MarkableForwardOnlyEventingReadStream(dataStream);

            XmlSchemaCollection schemaCollection = new XmlSchemaCollection(new NameTable());

            schemaCollection.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallBack);

            // retrieve the assigned document schemas to validate against
            SchemaList docSchemas = this.DocumentSchemas;

            // retrieve the namespace this document adheres to
            string contextProperty = (string)outmsg.Context.Read(XmlCompleteValidator._documentSpecNameProperty.Name.Name, XmlCompleteValidator._documentSpecNameProperty.Name.Namespace);

            // if the inbound message has a namespace,
            if (contextProperty != null && contextProperty.Length > 0)
            {
                // clear the original schemas to validate against
                docSchemas.Clear();

                string[] contextSchemas = contextProperty.Split(new char[] { '|' });

                // set it's schemas
                foreach (string schemaName in contextSchemas)
                {
                    docSchemas.Add(new Schema(schemaName));
                }
            }

            #region retrieve validation schemas, shamelessly copied from the original XmlValidator pipeline component
            bool validateSchemas = this.DocumentSchemas != null && this.DocumentSchemas.Count > 0;
            if (validateSchemas && this.DocumentSchemas.Count == 1 && this.DocumentSchemas[0].SchemaName.Length == 0)
            {
                validateSchemas = false;
            }

            if (validateSchemas)
            {
                foreach (Schema s in docSchemas)
                {
                    try
                    {
                        docSpec = pc.GetDocumentSpecByName(s.SchemaName);
                    }
                    catch (COMException e)
                    {
                        throw new XmlCompleteValidatorException(
                                  ExceptionType.CANNOT_GET_DOCSPEC_BY_NAME,
                                  e.ErrorCode.ToString("X") + ": " + e.Message,
                                  new string[] { s.SchemaName });
                    }

                    if (docSpec == null)
                    {
                        throw new XmlCompleteValidatorException(
                                  ExceptionType.CANNOT_GET_DOCSPEC_BY_NAME,
                                  string.Empty,
                                  new string[] { s.SchemaName });
                    }

                    XmlSchemaCollection coll = docSpec.GetSchemaCollection();

                    schemaCollection.Add(coll);
                }
            }
            else
            {
                try
                {
                    docSpec = pc.GetDocumentSpecByType(Utils.GetDocType(eventingDataStream));
                }
                catch (COMException e)
                {
                    throw new XmlCompleteValidatorException(
                              ExceptionType.CANNOT_GET_DOCSPEC_BY_TYPE,
                              e.ErrorCode.ToString("X") + ": " + e.Message,
                              new string[] { Utils.GetDocType(eventingDataStream) });
                }

                if (docSpec == null)
                {
                    throw new XmlCompleteValidatorException(
                              ExceptionType.CANNOT_GET_DOCSPEC_BY_TYPE,
                              string.Empty,
                              new string[] { Utils.GetDocType(eventingDataStream) });
                }

                schemaCollection = docSpec.GetSchemaCollection();
            }
            #endregion

            // the most critical line within this component, assign an
            // XmlEventingValidationStream to ensure the inbound messagestream is validated
            // and events can be assigned which allow us to capture any erros that might occur
            XmlEventingValidationStream validatingStream = new XmlEventingValidationStream(eventingDataStream);

            // add the schemas we'd like to validate the inbound message against
            validatingStream.Schemas.Add(schemaCollection);

            // assign a validation event which will accumulate any errors within the inbound message
            validatingStream.ValidatingReader.ValidationEventHandler += new ValidationEventHandler(XmlMessageValidationCallBack);

            // and assign the AfterLastReadEvent, which fires upon reading the last piece of information
            // from the inbound message stream and pushes all accumulated error information out into
            // the eventviewer and onto the HAT context by throwing an exception which contains the errors
            validatingStream.AfterLastReadEvent += new AfterLastReadEventHandler(validatingStream_AfterLastReadEvent);

            // duplicate the inbound message part by creating a new one and copying it's properties
            IBaseMessageFactory messageFactory = pc.GetMessageFactory();
            IBaseMessagePart    messagePart    = messageFactory.CreateMessagePart();

            // if the inbound message exists and has a body part, copy the part properties
            // into the outbound messagepart
            if (inmsg != null && inmsg.BodyPart != null)
            {
                messagePart.PartProperties = PipelineUtil.CopyPropertyBag(inmsg.BodyPart.PartProperties, messageFactory);
            }

            // set the outbound charset
            messagePart.Charset = "UTF-8";

            // set the outbound content type
            messagePart.ContentType = "text/xml";

            // and assign the outbound datastream
            messagePart.Data = validatingStream;

            // finally, copy existing message parts
            CopyMessageParts(pc, inmsg, outmsg, messagePart, false);
        }
Exemple #15
0
 public Prober(MarkableForwardOnlyEventingReadStream stream)
 {
     Stream = stream ?? throw new ArgumentNullException(nameof(stream));
 }