Ejemplo n.º 1
0
        /// <summary>
        /// If the BizTalk message in the _BREPipelineMetaInstructionCollection and/or it's body part are null then instantiate them and copy
        /// context over from the original message
        /// </summary>
        private void RecreateBizTalkMessageAndBodyPartIfNecessary(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            // If the BizTalk message has been nullified then create the message again and copy over the context from the original message
            if (_BREPipelineMetaInstructionCollection.InMsg == null)
            {
                TraceManager.PipelineComponent.TraceInfo("{0} - Instantiating the message since it was null and the pipeline component needs to assign the TypedXMLDocument to it.", callToken);
                _BREPipelineMetaInstructionCollection.InMsg = pc.GetMessageFactory().CreateMessage();
                _BREPipelineMetaInstructionCollection.InMsg.Context = PipelineUtil.CloneMessageContext(inmsg.Context);
            }

            // If the message body part is null then instantiate it again so we can assign the typed xml document stream to it
            if (_BREPipelineMetaInstructionCollection.InMsg.BodyPart == null)
            {
                TraceManager.PipelineComponent.TraceInfo("{0} - Instantiating the message body part since it was null and the pipeline component needs to assign the TypedXMLDocument to it.", callToken);
                IBaseMessagePart messageBodyPart = pc.GetMessageFactory().CreateMessagePart();
                _BREPipelineMetaInstructionCollection.InMsg.AddPart("Body", messageBodyPart, true);
            }
        }
        /// <summary>
        /// Method used to update BizTalk Pipeline message from the BRE Policy. BRE Policies work with Xml messages. BizTalk Messages are immutable. Thus if in order for the BRE Policy to update the BizTalk Message, a new message needs to be created, copied, or cloned containing the updated Xml content, along with the BizTalk Promoted properties from the context.
        /// </summary>
        /// <param name="xmlMessage">Message containing the modified content</param>
        /// <param name="pc">Pipeline context containing the current pipeline configuration</param>
        /// <param name="baseMsg">BizTalk BaseMessage which is to be cloned/copied/or modified</param>
        private static void UpdateMessage(string xmlMessage, IPipelineContext pc, ref IBaseMessage baseMsg)
        {
            if (pc == null || baseMsg == null)
            {
                return;
            }
            IBaseMessagePart bodyPart = pc.GetMessageFactory().CreateMessagePart();
            MemoryStream     omstrm   = new MemoryStream(Encoding.UTF8.GetBytes(xmlMessage));

            omstrm.Seek(0L, SeekOrigin.Begin);
            bodyPart.Data = omstrm;
            pc.ResourceTracker.AddResource(omstrm);
            IBaseMessage outMsg = pc.GetMessageFactory().CreateMessage();

            outMsg.AddPart("body", bodyPart, true);
            outMsg.Context = PipelineUtil.CloneMessageContext(baseMsg.Context);
            baseMsg        = outMsg;
        }
Ejemplo n.º 3
0
        private void CreateOutgoingMessage(IPipelineContext pContext, String messageString, IBaseMessage pInMsg)
        {
            IBaseMessage outMsg;

            try
            {
                //create outgoing message
                outMsg = pContext.GetMessageFactory().CreateMessage();
                outMsg.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);

                byte[] bufferOoutgoingMessage = System.Text.ASCIIEncoding.ASCII.GetBytes(messageString);
                outMsg.BodyPart.Data = new MemoryStream(bufferOoutgoingMessage);
                outMsg.Context       = PipelineUtil.CloneMessageContext(pInMsg.Context);
                qOutputMsgs.Enqueue(outMsg);
            }

            catch (Exception ex)
            {
                throw new ApplicationException("Error in queueing outgoing messages: " + ex.Message);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a clone copy of the specified message.
        /// </summary>
        /// <param name="pipelineContext">Pipeline context.</param>
        /// <param name="message">Source message.</param>
        /// <returns>Clone message.</returns>



        public static IBaseMessage CreateCloneMessage(IPipelineContext pipelineContext, IBaseMessage message)
        {
            if (pipelineContext == null)
            {
                throw new ArgumentNullException("pipelineContext");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            try
            {
                IBaseMessage message1 = pipelineContext.GetMessageFactory().CreateMessage();
                message1.Context = PipelineUtil.CloneMessageContext(message.Context);
                MessageHelper.CopyMessageParts(message, message1);
                pipelineContext.ResourceTracker.AddResource((object)message1.BodyPart.Data);
                return(message1);
            }
            catch (Exception ex)
            {
                DECore.TraceProvider.Logger.TraceError(ex);
                throw;
            }
        }
Ejemplo n.º 5
0
        public static IBaseMessage DeepCloneMessage(IPipelineContext pipelineContext, IBaseMessage message, bool cloneItinerary)
        {
            if (pipelineContext == null)
            {
                throw new ArgumentNullException("pipelineContext");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            IBaseMessage message1 = pipelineContext.GetMessageFactory().CreateMessage();

            if (cloneItinerary)
            {
                message1.Context = PipelineUtil.CloneMessageContext(message.Context);
            }
            else
            {
                message1.Context = CloneAndExcludeESBProperties(pipelineContext, message);
            }
            MessageHelper.CloneAndAddMessageParts(pipelineContext, message, message1);
            pipelineContext.ResourceTracker.AddResource((object)message1.BodyPart.Data);
            return(message1);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
        public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

            if (!Validate(out errorMessage))
            {
                var ex = new ArgumentException(errorMessage);
                _instrumentationHelper.TrackComponentError(ex);
                throw ex;
            }

            var data = pInMsg.BodyPart.GetOriginalDataStream();

            //Determine of the request body has any data. GET request will not have any body.
            var hasData = HasData(data);

            //Get a reference to the BizTalk schema.
            DocumentSpec documentSpec;

            try
            {
                documentSpec = (DocumentSpec)pContext.GetDocumentSpecByName(DocumentSpecName);
            }
            catch (COMException cex)
            {
                _instrumentationHelper.TrackComponentError(cex);
                throw cex;
            }

            //Get a list of properties defined in the schema.
            var annotations = documentSpec.GetPropertyAnnotationEnumerator();
            var doc         = new XmlDocument();
            var sw          = new StringWriter(new StringBuilder());

            //Create a new instance of the schema.
            doc.Load(documentSpec.CreateXmlInstance(sw));
            sw.Dispose();

            //Write all properties to the message body.
            while (annotations.MoveNext())
            {
                var    annotation = (IPropertyAnnotation)annotations.Current;
                var    node       = doc.SelectSingleNode(annotation.XPath);
                object propertyValue;

                if (pInMsg.Context.TryRead(new ContextProperty(annotation.Name, annotation.Namespace), out propertyValue))
                {
                    node.InnerText = propertyValue.ToString();
                }
            }

            var ms = new MemoryStream();

            doc.Save(ms);
            ms.Seek(0, SeekOrigin.Begin);

            var outMsg = pInMsg;

            //If the request has a body it should be preserved an the query parameters should be written to it's own message part.
            if (hasData)
            {
                string msgType = GetMessageType(MakeMarkable(pInMsg.BodyPart.Data));

                outMsg = pInMsg;
                outMsg.BodyPart.Data = pInMsg.BodyPart.Data;

                outMsg.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);
                outMsg.Context.Promote(new ContextProperty(SystemProperties.MessageType), msgType);
                var factory   = pContext.GetMessageFactory();
                var queryPart = factory.CreateMessagePart();
                queryPart.Data = ms;

                outMsg.AddPart("querypart", queryPart, false);
            }
            else
            {
                outMsg.BodyPart.Data = ms;
                //Promote message type and SchemaStrongName
                outMsg.Context.Promote(new ContextProperty(SystemProperties.MessageType), documentSpec.DocType);
                outMsg.Context.Promote(new ContextProperty(SystemProperties.SchemaStrongName), documentSpec.DocSpecStrongName);
            }

            _outputQueue.Enqueue(outMsg);
            _instrumentationHelper.TrackComponentSuccess();
        }
        private IBaseMessage BuildResponseMessage(IBaseMessage message, IBaseMessageContext context, LoopBackTransmitProperties props)
        {
            Guid callToken  = TraceManager.CustomComponent.TraceIn();
            long startScope = TraceManager.CustomComponent.TraceStartScope("BuildResponseMessage", callToken);

            IBaseMessageFactory messageFactory = _transportProxy.GetMessageFactory();
            IBaseMessage        btsResponse    = messageFactory.CreateMessage();

            TraceManager.CustomComponent.TraceInfo("PropertyCopy: {0}", props.PropertyCopy);
            if (props.PropertyCopy)
            {
                btsResponse.Context = PipelineUtil.CloneMessageContext(context);
            }
            TraceManager.CustomComponent.TraceInfo("CustomPropertyCopy: {0}", props.CustomPropertyCopy);
            if (props.CustomPropertyCopy)
            {
                btsResponse.Context = messageFactory.CreateMessageContext();
                for (int i = 0; i < context.CountProperties; i++)
                {
                    string strName;
                    string strNamespace;
                    object oValue = context.ReadAt(i, out strName, out strNamespace);
                    if (!strNamespace.StartsWith("http://schemas.microsoft.com/BizTalk"))
                    {
                        if (context.IsPromoted(strName, strNamespace))
                        {
                            TraceManager.CustomComponent.TraceInfo("Promoted into context: {1}#{0}={2}", strName, strNamespace, oValue);
                            btsResponse.Context.Promote(strName, strNamespace, oValue);
                        }
                        else
                        {
                            TraceManager.CustomComponent.TraceInfo("Copied into context: {1}#{0}={2}", strName, strNamespace, oValue);
                            btsResponse.Context.Write(strName, strNamespace, oValue);
                        }
                    }
                }
            }
            TraceManager.CustomComponent.TraceInfo("PartCount: {0}", message.PartCount);
            for (int i = 0; i < message.PartCount; i++)
            {
                string        str;
                VirtualStream stream = new VirtualStream();
                StreamReader  rdr    = new StreamReader(message.GetPartByIndex(i, out str).GetOriginalDataStream(), true);
                StreamWriter  wrtr   = new StreamWriter(stream, rdr.CurrentEncoding);
                wrtr.Write(rdr.ReadToEnd());
                rdr.Close();
                wrtr.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                IBaseMessagePart part = messageFactory.CreateMessagePart();
                if (props.PropertyCopy)
                {
                    part.Charset        = message.GetPart(str).Charset;
                    part.ContentType    = message.GetPart(str).ContentType;
                    part.PartProperties = PipelineUtil.CopyPropertyBag(message.GetPart(str).PartProperties, messageFactory);
                }
                btsResponse.AddPart(str, part, message.GetPart(str).PartID.Equals(message.BodyPart.PartID));
                btsResponse.GetPart(str).Data = stream;
            }

            TraceManager.CustomComponent.TraceEndScope("BuildResponseMessage", startScope, callToken);
            TraceManager.CustomComponent.TraceOut(callToken);

            return(btsResponse);
        }