Пример #1
0
        /// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message</param>
        /// <returns>Original input message</returns>
        /// <remarks>
        /// IComponent.Execute method is used to initiate
        /// the processing of the message in this pipeline component.
        /// </remarks>
        public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg)
        {
            int    PartCount    = inmsg.PartCount;
            string BodyPartName = inmsg.BodyPartName;

            string systemPropertiesNamespace = @"http://schemas.microsoft.com/BizTalk/2003/system-properties";

            try
            {
                for (int i = 0; i < inmsg.PartCount; i++)
                {
                    string           PartName;
                    IBaseMessagePart CurrentPart = inmsg.GetPartByIndex(i, out PartName);

                    if (!PartName.Equals(BodyPartName))
                    {
                        Stream CurrentPartSource = CurrentPart.GetOriginalDataStream();
                        byte[] CurrentPartBuffer = new byte[CurrentPartSource.Length];
                        CurrentPartSource.Read(CurrentPartBuffer, 0, CurrentPartBuffer.Length);

                        byte[] CompressedPartBuffer;
                        using (MemoryStream TempStream = new MemoryStream())
                        {
                            using (GZipStream CompressedStream = new GZipStream(TempStream, CompressionMode.Compress, true))
                            {
                                CompressedStream.Write(CurrentPartBuffer, 0, CurrentPartBuffer.Length);
                                CompressedStream.Close();
                            }
                            CompressedPartBuffer = TempStream.ToArray();
                        }

                        MemoryStream TempCompressedStream = new MemoryStream(CompressedPartBuffer);
                        inmsg.GetPartByIndex(i, out PartName).Data = TempCompressedStream;
                        string PropertyName   = "FileName";
                        string PropertySchema = "http://schemas.microsoft.com/BizTalk/2003/mime-properties";
                        string SourcePartName = inmsg.GetPartByIndex(i, out PartName).PartProperties.Read(PropertyName,
                                                                                                          PropertySchema).ToString();
                        SourcePartName += this.FileExtension;

                        inmsg.GetPartByIndex(i, out PartName).PartProperties.Write("FileName", PropertySchema, SourcePartName);
                    }
                }
            }
            catch
            {
                throw;
            }
            return(inmsg);
        }
Пример #2
0
        /// <summary>
        /// Executes the specified resolution policy and returns the results
        /// in an instance of a MessageContextAccessorResolver object.
        /// </summary>
        /// <param name="message">The IBaseMessage instace.</param>
        /// <returns>MessageContextAccessorResolver instance containing the resolution results.</returns>
        public MessageContextAccessorResolver Resolve(IBaseMessage message)
        {
            // extract context properties
            Dictionary <string, object> contextProperties = new Dictionary <string, object>();

            message.Context.ReadAll(contextProperties);
            for (int p = 0; p < message.PartCount; p++)
            {
                string partName = string.Empty;
                var    part     = message.GetPartByIndex(p, out partName);
                part.PartProperties.ReadAll(contextProperties);
            }

            // create a fact instance
            MessageContextAccessorResolver fact = new MessageContextAccessorResolver(contextProperties);

            if (string.IsNullOrEmpty(this.PolicyName))
            {
                return(fact);
            }

            // execute the schema resolution policy
            using (Policy policy = new Policy(this.PolicyName, this.MajorRevision, this.MinorRevision))
            {
                object[] facts = { fact };
                BRETrackingInterceptor interceptor = new BRETrackingInterceptor();
                policy.Execute(facts, interceptor);
                return(fact);
            }
        }
Пример #3
0
        /// <summary>
        /// Returns a part in a pipeline message.
        /// </summary>
        /// <param name="message">The pipeline message.</param>
        /// <param name="index">The index at which the part is located.</param>
        /// <returns>The part in a pipeline message.</returns>
        public static IBaseMessagePart Part(this IBaseMessage message, int index)
        {
            string partNameOut;
            var    inMsgPart = message.GetPartByIndex(index, out partNameOut);

            return(inMsgPart);
        }
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

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

            var cu = new CompressionUtil();

            for (var i = 0; i < pInMsg.PartCount; i++)
            {
                string partName;
                var part = pInMsg.GetPartByIndex(i, out partName);

                var fileName = GetFileName(part);

                cu.AddMessage(part.GetOriginalDataStream(), fileName);
            }

            var outMsg = pContext.GetMessageFactory().CreateMessage();
            outMsg.Context = pInMsg.Context;
            var bodyPart = pContext.GetMessageFactory().CreateMessagePart();
            bodyPart.Data = cu.GetZip();
            bodyPart.Charset = "utf-8";
            bodyPart.ContentType = "application/zip";

            outMsg.AddPart("Body",bodyPart,true);

            return outMsg;
        }
Пример #5
0
 public static void CloneAndAddMessageParts(IPipelineContext pipelineContext, IBaseMessage sourceMessage, IBaseMessage destinationMessage)
 {
     if (pipelineContext == null)
     {
         throw new ArgumentNullException("pipelineContext");
     }
     if (sourceMessage == null)
     {
         throw new ArgumentNullException("sourceMessage");
     }
     if (destinationMessage == null)
     {
         throw new ArgumentNullException("destinationMessage");
     }
     try
     {
         string bodyPartName = sourceMessage.BodyPartName;
         for (int index = 0; index < sourceMessage.PartCount; ++index)
         {
             string           partName    = (string)null;
             IBaseMessagePart partByIndex = sourceMessage.GetPartByIndex(index, out partName);
             IBaseMessagePart part        = MessageHelper.CloneMessagePart(pipelineContext, partByIndex);
             bool             bBody       = string.Compare(partName, bodyPartName, true, CultureInfo.CurrentCulture) == 0;
             destinationMessage.AddPart(partName, part, bBody);
         }
     }
     catch (Exception ex)
     {
         DECore.TraceProvider.Logger.TraceError(ex);
         throw;
     }
 }
Пример #6
0
        /// <summary>
        /// copies all message parts part of the inbound message onto the outbound message
        /// </summary>
        /// <param name="pc">the <see cref="IPipelineContext"/> this message belongs to</param>
        /// <param name="inmsg">the inbound message</param>
        /// <param name="outmsg">the outbound message</param>
        /// <param name="bodyPart">the body part</param>
        /// <param name="allowUnrecognizeMessage">whether to allow unrecognized messages</param>
        public static void CopyMessageParts(
            IPipelineContext pc,
            IBaseMessage inmsg,
            IBaseMessage outmsg,
            IBaseMessagePart bodyPart,
            bool allowUnrecognizeMessage)
        {
            string text1 = inmsg.BodyPartName;

            for (int num1 = 0; num1 < inmsg.PartCount; num1++)
            {
                string           text2 = null;
                IBaseMessagePart part1 = inmsg.GetPartByIndex(num1, out text2);
                if ((part1 == null) && !allowUnrecognizeMessage)
                {
                    throw new ArgumentNullException("otherOutPart[" + num1 + "]");
                }
                if (text1 != text2)
                {
                    outmsg.AddPart(text2, part1, false);
                }
                else
                {
                    outmsg.AddPart(text1, bodyPart, true);
                }
            }
        }
Пример #7
0
        public void CanCreateMultipartFromStringsSimple()
        {
            IBaseMessage message = MessageHelper.Create(
                "<body>This is the body part (part1)</body>",
                "<body>This is the part2</body>",
                "<body>This is the part3</body>"
                );

            Assert.AreEqual(3, message.PartCount);

            string name = null;

            message.GetPartByIndex(0, out name);
            Assert.AreEqual("body", name);
            message.GetPartByIndex(1, out name);
            Assert.AreEqual("part1", name);
            message.GetPartByIndex(2, out name);
            Assert.AreEqual("part2", name);
        }
Пример #8
0
        private static void CloneParts(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart bodyPart)
        {
            for (int i = 0; i < inmsg.PartCount; i++)
            {
                string partName = null;

                IBaseMessagePart currentPart = inmsg.GetPartByIndex(i, out partName);

                if (currentPart == null) continue;

                outmsg.AddPart(partName, partName == inmsg.BodyPartName ? bodyPart : currentPart, partName == inmsg.BodyPartName);
            }
        }
Пример #9
0
        /// <summary>
        /// Initializes the Context Value collection with Message Context
        /// </summary>
        /// <param name="message">the IBaseMessage</param>
        public MessageContextAccessorResolver(IBaseMessage message)
        {
            // extract context properties
            Dictionary <string, object> _contextProperties = new Dictionary <string, object>();

            message.Context.ReadAll(_contextProperties);
            for (int p = 0; p < message.PartCount; p++)
            {
                string partName = string.Empty;
                var    part     = message.GetPartByIndex(p, out partName);
                part.PartProperties.ReadAll(_contextProperties);
            }

            this.contextProperties = ParseContextProperties(_contextProperties);
        }
Пример #10
0
        private static void CloneParts(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart bodyPart)
        {
            for (int i = 0; i < inmsg.PartCount; i++)
            {
                string partName = null;

                IBaseMessagePart currentPart = inmsg.GetPartByIndex(i, out partName);

                if (currentPart == null)
                {
                    continue;
                }

                outmsg.AddPart(partName, partName == inmsg.BodyPartName ? bodyPart : currentPart, partName == inmsg.BodyPartName);
            }
        }
Пример #11
0
        /// <summary>
        /// Copy message parts from source to destination message.
        /// </summary>
        /// <param name="sourceMessage">Source message</param>
        /// <param name="destinationMessage">Destination message</param>
        /// <param name="newBodyPart">New message body part</param>
        private void CopyMessageParts(IBaseMessage sourceMessage, IBaseMessage destinationMessage, IBaseMessagePart newBodyPart)
        {
            string bodyPartName = sourceMessage.BodyPartName;

            for (int c = 0; c < sourceMessage.PartCount; ++c)
            {
                string           partName    = null;
                IBaseMessagePart messagePart = sourceMessage.GetPartByIndex(c, out partName);
                if (partName != bodyPartName)
                {
                    destinationMessage.AddPart(partName, messagePart, false);
                }
                else
                {
                    destinationMessage.AddPart(bodyPartName, newBodyPart, true);
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Copies all the message parts from the source message into the destination message.
        /// </summary>
        /// <param name="sourceMessage">Source message.</param>
        /// <param name="destinationMessage">Destination message.</param>
        public static void CopyMessageParts(IBaseMessage sourceMessage, IBaseMessage destinationMessage)
        {
            if (sourceMessage == null)
            {
                throw new ArgumentNullException("sourceMessage");
            }
            if (destinationMessage == null)
            {
                throw new ArgumentNullException("destinationMessage");
            }

            string bodyPartName = sourceMessage.BodyPartName;

            for (int index = 0; index < sourceMessage.PartCount; ++index)
            {
                string           partName    = null;
                IBaseMessagePart partByIndex = sourceMessage.GetPartByIndex(index, out partName);
                bool             isBodyPart  = string.Compare(partName, bodyPartName, true, CultureInfo.CurrentCulture) == 0;
                destinationMessage.AddPart(partName, partByIndex, isBodyPart);
            }
        }
Пример #13
0
        /// <summary>
        /// Copy over all parts of the message from a source message to a destination message, choosing which part should be the body part
        /// </summary>
        private void CopyMessageParts(IBaseMessage sourceMessage, IBaseMessage destinationMessage, IBaseMessagePart newBodyPart)
        {
            //Explicitly clear the collection in case this has gone through a disassembler with multiple messages and there are leftovers from the last time
            partNames.Clear();
            
            string bodyPartName = sourceMessage.BodyPartName;
            for (int partCounter = 0; partCounter < sourceMessage.PartCount; ++partCounter)
            {
                string partName = null;
                IBaseMessagePart messagePart = sourceMessage.GetPartByIndex(partCounter, out partName);
                partNames.Add(partCounter, partName);

                if (partName != bodyPartName)
                {
                    destinationMessage.AddPart(partName, messagePart, false);
                }
                else
                {
                    destinationMessage.AddPart(bodyPartName, newBodyPart, true);
                }
            }
        }
Пример #14
0
        public static void CopyMessageParts(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart bodyPart, bool allowUnrecognizeMessage)
        {
            string bodyPartName = inmsg.BodyPartName;

            for (int i = 0; i < inmsg.PartCount; i++)
            {
                string           partName    = null;
                IBaseMessagePart partByIndex = inmsg.GetPartByIndex(i, out partName);
                if ((partByIndex == null) && !allowUnrecognizeMessage)
                {
                    throw new ArgumentNullException("otherOutPart[" + i + "]");
                }
                if (bodyPartName != partName)
                {
                    outmsg.AddPart(partName, partByIndex, false);
                }
                else
                {
                    outmsg.AddPart(bodyPartName, bodyPart, true);
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Gets the body part, if it exists, or the first part, or returns a null value
        /// if no part is found.
        /// </summary>
        /// <param name="message">The pipeline message.</param>
        /// <returns>The body part, or the first part if no body part is designated, or null if no part exists.</returns>
        public static IBaseMessagePart BodyOrFirstPartOrDefault(this IBaseMessage message)
        {
            try
            {
                IBaseMessagePart part;

                if (message.BodyPart == null)
                {
                    string partName;
                    part = message.GetPartByIndex(0, out partName);
                }
                else
                {
                    part = message.BodyPart;
                }

                return(part.WithStreamAtStart());
            }
            catch
            {
                return(null);
            }
        }
Пример #16
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

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

            var outMsg = pContext.GetMessageFactory().CreateMessage();

            outMsg.Context = pInMsg.Context;
            var bodyPart = pContext.GetMessageFactory().CreateMessagePart();

            using (var compressionUtil = new CompressionUtil())
            {
                for (var i = 0; i < pInMsg.PartCount; i++)
                {
                    string partName;
                    var    part = pInMsg.GetPartByIndex(i, out partName);


                    var fileName = GetFileName(part);

                    compressionUtil.AddMessage(part.GetOriginalDataStream(), fileName);
                }

                bodyPart.Data = compressionUtil.GetZip();
                pContext.ResourceTracker.AddResource(bodyPart.Data);
                bodyPart.Charset     = "utf-8";
                bodyPart.ContentType = "application/zip";
            }

            outMsg.AddPart("Body", bodyPart, true);

            return(outMsg);
        }
        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);
        }
Пример #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pipelineContext"></param>
        /// <param name="message"></param>
        /// <param name="tag"></param>
        public ArchiveBizTalkMessage(IPipelineContext pipelineContext, IBaseMessage message, ArchiveTag tag)
        {
            this.Message           = new Message();
            this.MessageProperties = new List <MessageProperty>();
            this.Parts             = new List <Part>();
            this.PartsProperties   = new List <PartProperty>();

            Guid messageId = Guid.NewGuid();

            try
            {
                //-------------------------------------------------------------------------
                // Add message.
                //-------------------------------------------------------------------------
                this.Message.MessageId = messageId;
                if (tag.ArchiveType.Id >= 0)
                {
                    this.Message.ArchiveTypeId = tag.ArchiveType.Id;
                }

                this.Message.Tag = tag.Tag;

                if (tag.SourceSystem.Id >= 0)
                {
                    this.Message.SourceSystemId = tag.SourceSystem.Id;
                }

                if (tag.TargetSystem.Id >= 0)
                {
                    this.Message.TargetSystemId = tag.TargetSystem.Id;
                }

                this.Message.Description  = tag.Description;
                this.Message.InsertedDate = DateTime.UtcNow;

                //-------------------------------------------------------------------------
                // Add the parts.
                //-------------------------------------------------------------------------
                int partCount = message.PartCount;

                for (int partIndex = 0; partIndex < partCount; partIndex++)
                {
                    string           partName = string.Empty;
                    IBaseMessagePart part     = message.GetPartByIndex(partIndex, out partName);
                    Part             prt      = GetMessagePart(messageId, partIndex, pipelineContext, part, partName);
                    if (prt != null)
                    {
                        this.Parts.Add(prt);
                        //-------------------------------------------------------------------------
                        // Add the parts properties.
                        //-------------------------------------------------------------------------
                        List <PartProperty> prtProperties = GetPartProperties(prt.PartId, part);
                        foreach (PartProperty p in prtProperties)
                        {
                            this.PartsProperties.Add(p);
                        }
                    }
                }
                //-------------------------------------------------------------------------
                // Add the message properties.
                //-------------------------------------------------------------------------
                int             propertyCount = (int)message.Context.CountProperties;
                MessageProperty msgProperties = new MessageProperty();
                msgProperties.MessageId = messageId;
                XElement      ContextData             = new XElement("ContextData");
                List <string> listOfContextProperties = new List <string>();
                listOfContextProperties = GetListOfContextProperties();
                for (int propertyIndex = 0; propertyIndex < propertyCount; propertyIndex++)
                {
                    string propertyName      = null;
                    string propertyNamespace = null;
                    object propertyValue     = message.Context.ReadAt(propertyIndex, out propertyName, out propertyNamespace);
                    if (listOfContextProperties.Contains(propertyName))
                    {
                        ContextData.Add(
                            new XElement("Property", new XAttribute("Name", propertyName),
                                         new XAttribute("Namespace", propertyNamespace),
                                         new XAttribute("Value", propertyValue.ToString())));
                    }

                    if (propertyNamespace == "http://schemas.microsoft.com/BizTalk/2003/system-properties")
                    {
                        if (propertyName == "InterchangeID")
                        {
                            string value = propertyValue.ToString().Trim();
                            this.Message.InterchangeId = GetGUIDWithoutBraces(value);
                        }
                        else if (propertyName == "MessageType")
                        {
                            this.Message.MessageType = propertyValue.ToString();
                        }
                    }
                    else if (propertyNamespace == "http://schemas.microsoft.com/BizTalk/2003/messagetracking-properties")
                    {
                        if (propertyName == "ActivityIdentity")
                        {
                            string value = propertyValue.ToString().Trim();
                            this.Message.ActivityId = GetGUIDWithoutBraces(value);
                        }
                    }
                }
                msgProperties.ContextData = ContextData.ToString();
                this.MessageProperties.Add(msgProperties);
                // If the message type is still unknown, try to get it from part[0].
                if (string.IsNullOrEmpty(this.Message.MessageType) || this.Message.MessageType == "Unknown")
                {
                    if (!string.IsNullOrEmpty(partType))
                    {
                        this.Message.MessageType = partType;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteTrace(string.Format("Error constructing BizTalkMessage from IBaseMessage {0} \r\n Details: {1}", this.GetType().Name, ex.ToString()));
                throw ex;
            }
        }
Пример #19
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            if (!Enabled)
            {
                return(pInMsg);
            }
            string errorMessage;

            if (!Validate(out errorMessage))
            {
                throw new ArgumentException(errorMessage);
            }
            IBaseMessageFactory messageFactory = pContext.GetMessageFactory();
            IBaseMessage        newMsg         = messageFactory.CreateMessage();

            newMsg.Context = pInMsg.Context;
            MemoryStream ms = new MemoryStream();

            //Create Html body
            IBaseMessagePart bodyPart = messageFactory.CreateMessagePart();

            if (ApplyXsltOnBodyPart)
            {
                if (string.IsNullOrEmpty(XSLTFilePath))
                {
                    throw new ArgumentNullException("XsltFilePath is null");
                }
                if (!File.Exists(XSLTFilePath))
                {
                    throw new FileNotFoundException(string.Format("Cannot find the xslt file '{0}'.", XSLTFilePath));
                }
                XslCompiledTransform transform = new XslCompiledTransform();
                transform.Load(XSLTFilePath);
                Stream originalStream = pInMsg.BodyPart.GetOriginalDataStream();
                if (!originalStream.CanSeek || !originalStream.CanRead)
                {
                    originalStream = new ReadOnlySeekableStream(originalStream);
                }
                XmlReader reader = XmlReader.Create(originalStream);
                transform.Transform(reader, null, ms);
                originalStream.Seek(0, SeekOrigin.Begin);
                pInMsg.BodyPart.Data = originalStream;
            }
            else
            {
                byte[] buff = Encoding.UTF8.GetBytes(EmailBody);
                ms.Write(buff, 0, buff.Length);
            }
            ms.Seek(0, SeekOrigin.Begin);
            bodyPart.Data        = ms;
            bodyPart.Charset     = "UTF-8";
            bodyPart.ContentType = "text/html";
            newMsg.AddPart("body", bodyPart, true);

            //Add all message parts as attachments
            int i = 0;

            string[] filenames = FileNames.Split('|');
            while (i < pInMsg.PartCount & i < filenames.Length)
            {
                if (!string.IsNullOrEmpty(filenames[i]))
                {
                    string           partName = "";
                    IBaseMessagePart part     = pInMsg.GetPartByIndex(i, out partName),
                                     newPart  = messageFactory.CreateMessagePart();
                    Stream originalStream     = part.GetOriginalDataStream();
                    newPart.Data        = originalStream;
                    newPart.Charset     = part.Charset;
                    newPart.ContentType = "text/xml";
                    newPart.PartProperties.Write("FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", filenames[i]);
                    newMsg.AddPart(filenames[i], newPart, false);
                }
                i++;
            }
            return(newMsg);
        }
Пример #20
0
        public static bool PerformMessageLookup(Guid messageInstanceID, List <ControlProperty> contextProps, List <ControlField> xpathProps, TrackingDatabase dta, BizTalkOperations operations)
        {
            bool result = true;

            try
            {
                /// NOTE :
                /// Following instruction will throw an exception if the corresponding message was not found in the DTA Db
                IBaseMessage message = operations.GetTrackedMessage(messageInstanceID, dta);
                Logger.CurrentLogger.Write(2, "Testing message {0}", System.Diagnostics.EventLogEntryType.Information, messageInstanceID);
                //BizTalkMessage btsMsg = (BizTalkMessage)rawMessage;

                foreach (ControlProperty prop in contextProps)
                {
                    string expectedValue = prop.Value;
                    string foundValue    = (string)message.Context.Read(
                        prop.Property,
                        prop.Namespace);

                    if (expectedValue != foundValue)
                    {
                        Logger.CurrentLogger.Write(3, "[KO] Prop '{0}/{1}' : mismatch - Expected {2}, found {3}.", System.Diagnostics.EventLogEntryType.Information,
                                                   prop.Namespace,
                                                   prop.Property,
                                                   expectedValue,
                                                   foundValue);
                        result = false;
                    }
                    else
                    {
                        Logger.CurrentLogger.Write(3, "[OK] Prop '{0}/{1}' : match - Expected {2}, found {3}.", System.Diagnostics.EventLogEntryType.Information,
                                                   prop.Namespace,
                                                   prop.Property,
                                                   expectedValue,
                                                   foundValue);
                    }
                }

                if (xpathProps.Count > 0)
                {
                    List <ControlField> tmpXpathProps = xpathProps.ToList <ControlField>();
                    for (int i = 0; i < message.PartCount; i++)
                    {
                        string body     = string.Empty;
                        string partName = string.Empty;
                        using (StreamReader streamReader = new StreamReader(message.GetPartByIndex(i, out partName).Data))
                        {
                            Logger.CurrentLogger.Write(3, "Testing part {0}", System.Diagnostics.EventLogEntryType.Information, partName);

                            Logger.CurrentLogger.Write(3, "Retrieving body...", System.Diagnostics.EventLogEntryType.Information);
                            body = streamReader.ReadToEnd();
                            Logger.CurrentLogger.Write(3, "Body retrieved successfully : Length={0}", System.Diagnostics.EventLogEntryType.Information, body.Length);
                            XmlDocument testedMsg = new XmlDocument();
                            testedMsg.LoadXml(body);

                            foreach (ControlField field in xpathProps)
                            {
                                string  expectedValue = field.Value;
                                XmlNode tmpNode       = testedMsg.SelectSingleNode(field.XPath);
                                if (tmpNode != null)
                                {
                                    string foundValue = tmpNode.InnerText;

                                    if (expectedValue != foundValue)
                                    {
                                        Logger.CurrentLogger.Write(3, "[KO] XPath '{0}' : mismatch - Expected {1}, found {2}.", System.Diagnostics.EventLogEntryType.Information,
                                                                   field.XPath,
                                                                   expectedValue,
                                                                   foundValue);
                                    }
                                    else
                                    {
                                        Logger.CurrentLogger.Write(3, "[OK] XPath '{0}' : match - Expected {1}, found {2}.", System.Diagnostics.EventLogEntryType.Information,
                                                                   field.XPath,
                                                                   expectedValue,
                                                                   foundValue);
                                        tmpXpathProps.Remove(tmpXpathProps.Find(tmpField => tmpField.XPath == field.XPath && tmpField.Value == field.Value));
                                    }
                                }
                            }

                            if (tmpXpathProps.Count == 0)
                            {
                                break;
                            }
                        }
                    }

                    if (tmpXpathProps.Count == 0)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                Logger.CurrentLogger.Write(2, "Error when retrieving message {0} from DTA Db : {1}", System.Diagnostics.EventLogEntryType.Error, messageInstanceID, ex.Message);
                return(false);
            }
        }
Пример #21
0
        public static MessageInfo CreateMessageInfo(IBaseMessage message, string destination)
        {
            var mc = (MessageContext)message.Context;

            var miciapael = new List<MessageInfoContextInfoArrayPropertyArrayElement1>(message.PartCount);
            var mipimpl = new List<MessageInfoPartInfoMessagePart>(message.PartCount);
            for (int partIndex = 0; partIndex < message.PartCount; partIndex++)
            {
                string partName = string.Empty;
                var mp = message.GetPartByIndex(partIndex, out partName);

                var miciapae = new MessageInfoContextInfoArrayPropertyArrayElement1 {Value = partName};
                miciapael.Add(miciapae);

                var mipimp = new MessageInfoPartInfoMessagePart {Charset = mp.Charset, ContentType = mp.ContentType};
                if (null != destination)
                {
                    mipimp.FileName = destination;
                }
                mipimp.ID = mp.PartID.ToString();
                mipimp.Name = partName;
                mipimpl.Add(mipimp);
            }

            var micipl = new List<MessageInfoContextInfoProperty>(mc.Properties.Count);
            foreach (DictionaryEntry pde in mc.Properties)
            {
                string key = pde.Key.ToString();
                string val = pde.Value.ToString();
                int at = key.IndexOf('@');

                var micip = new MessageInfoContextInfoProperty
                                {
                                    Name = key.Substring(0, at),
                                    Namespace = key.Substring(at + 1),
                                    Value = val
                                };
                micip.Promoted = mc.IsPromoted(micip.Name, micip.Namespace);
                micip.PromotedSpecified = true;

                micipl.Add(micip);
            }

            var miciap = new MessageInfoContextInfoArrayProperty
                             {
                                 Name = "PartNames",
                                 Namespace = "http://schemas.microsoft.com/BizTalk/2003/messageagent-properties",
                                 ArrayElement1 = miciapael.ToArray()
                             };

            var mici = new MessageInfoContextInfo
                           {
                               PropertiesCount = message.Context.CountProperties.ToString(),
                               ArrayProperty = new MessageInfoContextInfoArrayProperty[] {miciap},
                               Property = micipl.ToArray()
                           };

            var mipi = new MessageInfoPartInfo
                           {
                               PartsCount = message.PartCount.ToString(),
                               MessagePart = mipimpl.ToArray()
                           };

            var items = new ArrayList {mici, mipi};

            var mi = new MessageInfo {Items = items.ToArray()};
            return mi;
        }
Пример #22
0
        public static MessageInfo CreateMessageInfo(IBaseMessage message, string destination)
        {
            var mc = (MessageContext)message.Context;

            var miciapael = new List <MessageInfoContextInfoArrayPropertyArrayElement1>(message.PartCount);
            var mipimpl   = new List <MessageInfoPartInfoMessagePart>(message.PartCount);

            for (int partIndex = 0; partIndex < message.PartCount; partIndex++)
            {
                string partName = string.Empty;
                var    mp       = message.GetPartByIndex(partIndex, out partName);

                var miciapae = new MessageInfoContextInfoArrayPropertyArrayElement1 {
                    Value = partName
                };
                miciapael.Add(miciapae);

                var mipimp = new MessageInfoPartInfoMessagePart {
                    Charset = mp.Charset, ContentType = mp.ContentType
                };
                if (null != destination)
                {
                    mipimp.FileName = destination;
                }
                mipimp.ID   = mp.PartID.ToString();
                mipimp.Name = partName;
                mipimpl.Add(mipimp);
            }

            var micipl = new List <MessageInfoContextInfoProperty>(mc.Properties.Count);

            foreach (DictionaryEntry pde in mc.Properties)
            {
                string key = pde.Key.ToString();
                string val = pde.Value.ToString();
                int    at  = key.IndexOf('@');

                var micip = new MessageInfoContextInfoProperty
                {
                    Name      = key.Substring(0, at),
                    Namespace = key.Substring(at + 1),
                    Value     = val
                };
                micip.Promoted          = mc.IsPromoted(micip.Name, micip.Namespace);
                micip.PromotedSpecified = true;

                micipl.Add(micip);
            }

            var miciap = new MessageInfoContextInfoArrayProperty
            {
                Name          = "PartNames",
                Namespace     = "http://schemas.microsoft.com/BizTalk/2003/messageagent-properties",
                ArrayElement1 = miciapael.ToArray()
            };

            var mici = new MessageInfoContextInfo
            {
                PropertiesCount = message.Context.CountProperties.ToString(),
                ArrayProperty   = new MessageInfoContextInfoArrayProperty[] { miciap },
                Property        = micipl.ToArray()
            };

            var mipi = new MessageInfoPartInfo
            {
                PartsCount  = message.PartCount.ToString(),
                MessagePart = mipimpl.ToArray()
            };

            var items = new ArrayList {
                mici, mipi
            };

            var mi = new MessageInfo {
                Items = items.ToArray()
            };

            return(mi);
        }
Пример #23
0
        public static MultipartMessageDefinition GenerateFromMessage(IBaseMessage pInMsg)
        {
            MultipartMessageDefinition tempMessage = new MultipartMessageDefinition();
            List <ContextProperty>     propList    = new List <ContextProperty>();

            List <Part> partList = new List <Part>();

            for (int i = 0; i < pInMsg.PartCount; i++)
            {
                string           partName = String.Empty;
                IBaseMessagePart msgPart  = pInMsg.GetPartByIndex(i, out partName);

                Part mockPart = new Part();
                mockPart.ContentType = msgPart.ContentType;
                mockPart.PartName    = partName;
                mockPart.PartNumber  = i;
                mockPart.IsBodyPart  = (pInMsg.BodyPart.PartID == msgPart.PartID);
                mockPart.Data        = null;

                try
                {
                    XmlDocument tempXML = new XmlDocument();
                    tempXML.Load(msgPart.Data);
                    mockPart.Data = tempXML.DocumentElement;

                    //ContextProperty performXMLdsm = new ContextProperty();
                    //performXMLdsm.Name = BTSProperties.emulateXMLDisassembler.Name.Name;
                    //performXMLdsm.Namespace = BTSProperties.emulateXMLDisassembler.Name.Namespace;
                    //performXMLdsm.Value = "true";
                    //propList.Add(performXMLdsm);
                }
                catch
                {
                    XmlTextReader rawStreamReader = new XmlTextReader(msgPart.Data);
                    mockPart.RawData = rawStreamReader.ReadContentAsString(); // String.Format("<![CDATA[{0}]]>", rawStreamReader.ReadContentAsString());
                }
                //msgPart.Data.Seek(0, System.IO.SeekOrigin.Begin);
                //msgPart.Data.Position = 0;

                partList.Add(mockPart);
            }
            tempMessage.Parts = partList.ToArray();

            for (uint iProp = 0; iProp < pInMsg.Context.CountProperties; iProp++)
            {
                string propName;
                string propNamespace;
                object value = pInMsg.Context.ReadAt((int)iProp, out propName, out propNamespace);

                ContextProperty prop = new ContextProperty();
                prop.Name      = propName;
                prop.Namespace = propNamespace;
                prop.Value     = value.ToString();
                prop.Promoted  = pInMsg.Context.IsPromoted(propName, propNamespace);

                propList.Add(prop);
            }
            tempMessage.PropertyBag = propList.ToArray();

            return(tempMessage);
        }
        /// <summary>
        /// Resolve implementation for use within a Pipeline component. This method is typically used with one of the ESB Pipeline components such as the Itinerary Selector, or ESB Dispatcher to resolve entities, such as itinerary, maps and endpoint addresses. This method invokes the BRE Policies that were configured through the Config and Resolver connection string values.
        /// </summary>
        /// <param name="config">string containing name, value property values</param>
        /// <param name="resolver">Resolver connection string</param>
        /// <param name="message">BizTalk IBaseMessage class which is used to pass to the BRE policies if configured properly</param>
        /// <param name="pipelineContext">BizTalk Pipeline configuration</param>
        /// <returns>Resolver Dictionary Collection containing resolved entries, such as itinerary name, map name, and endpoint address resolution values</returns>
        Dictionary <string, string> IResolveProvider.Resolve(string config, string resolver, IBaseMessage message, IPipelineContext pipelineContext)
        {
            Dictionary <string, string> dictionary;

            if (string.IsNullOrEmpty(config))
            {
                throw new ArgumentNullException("config");
            }
            if (string.IsNullOrEmpty(resolver))
            {
                throw new ArgumentNullException("resolver");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (pipelineContext == null)
            {
                throw new ArgumentNullException("pipelineContext");
            }
            Resolution  resolution = new Resolution();
            XmlDocument document   = new XmlDocument();

            try
            {
                ResolverMgr.SetContext(resolution, message, pipelineContext);
                BRE bre = this.CreateResolverDescriptor(config, resolver);

                Stream originalDataStream = message.BodyPart.GetOriginalDataStream();
                if (!originalDataStream.CanSeek)
                {
                    ReadOnlySeekableStream stream2 = new ReadOnlySeekableStream(originalDataStream);
                    message.BodyPart.Data = stream2;
                    pipelineContext.ResourceTracker.AddResource(stream2);
                    originalDataStream = stream2;
                }
                if (originalDataStream.Position != 0L)
                {
                    originalDataStream.Position = 0L;
                }
                document.Load(originalDataStream);
                originalDataStream.Position = 0L;

                if (bre.useMsg && (message.BodyPart != null))
                {
                    if (bre.useMsgCtxt)
                    {
                        // Check for Message Context values
                        string strMsgCtxtValues = bre.msgCtxtValues;
                        if (string.IsNullOrEmpty(strMsgCtxtValues))
                        {
                            // get all context values
                            object objValue = null;
                            ctxtValues.Clear();
                            IBaseMessageContext bmCtxt = message.Context;

                            for (int i = 0; i < bmCtxt.CountProperties; i++)
                            {
                                string strName      = string.Empty;
                                string strNamespace = string.Empty;
                                string key          = string.Empty;
                                try
                                {
                                    objValue = bmCtxt.ReadAt(i, out strName, out strNamespace);
                                    key      = string.Format("{0}#{1}", strNamespace, strName);
                                    if (objValue != null)
                                    {
                                        // check to see if already in collection
                                        if (!ctxtValues.ContainsKey(key))
                                        {
                                            ctxtValues.Add(key, objValue.ToString());
                                        }
                                        else
                                        {
                                            ctxtValues[key] = objValue.ToString();
                                        }
                                    }
                                    else
                                    {
                                        if (!ctxtValues.ContainsKey(key))
                                        {
                                            ctxtValues.Add(key, string.Empty);
                                        }
                                        else
                                        {
                                            ctxtValues[key] = string.Empty;
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    EventLogger.LogMessage(string.Format("Namespace: {0}\nName: {1}\n caused an exception:\n{2}\nThis item was not added to the collection.", strNamespace, strName, ex.Message), EventLogEntryType.Error, 1000);
                                }
                            }

                            // Now ready body part properties

                            for (int p = 0; p < message.PartCount; p++)
                            {
                                string partName = string.Empty;
                                var    part     = message.GetPartByIndex(p, out partName);

                                for (int pp = 0; pp < part.PartProperties.CountProperties; pp++)
                                {
                                    string strName      = string.Empty;
                                    string strNamespace = string.Empty;
                                    string key          = string.Empty;
                                    try
                                    {
                                        objValue = part.PartProperties.ReadAt(pp, out strName, out strNamespace);
                                        key      = string.Format("{0}#{1}", strNamespace, strName);
                                        if (objValue != null)
                                        {
                                            // check to see if already in collection
                                            if (!ctxtValues.ContainsKey(key))
                                            {
                                                ctxtValues.Add(key, objValue.ToString());
                                            }
                                            else
                                            {
                                                ctxtValues[key] = objValue.ToString();
                                            }
                                        }
                                        else
                                        {
                                            if (!ctxtValues.ContainsKey(key))
                                            {
                                                ctxtValues.Add(key, string.Empty);
                                            }
                                            else
                                            {
                                                ctxtValues[key] = string.Empty;
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        EventLogger.LogMessage(
                                            string.Format(
                                                "Namespace: {0}\nName: {1}\n caused an exception:\n{2}\nThis item was not added to the collection.",
                                                strNamespace, strName, ex.Message), EventLogEntryType.Error, 1000);
                                    }
                                }
                            }
                        }
                        else
                        {
                            // otherwise get specific context values by checking for |
                            bool     hasPipeDelimiter = strMsgCtxtValues.Contains("|");
                            string[] msgCtxtValues    = null;
                            string   msgCtxtValue     = string.Empty;
                            if (hasPipeDelimiter)
                            {
                                msgCtxtValues = strMsgCtxtValues.Split('|');
                                object objValue = null;
                                ctxtValues.Clear();
                                string key;
                                foreach (string str in msgCtxtValues)
                                {
                                    string[] ns_values = str.Split('#');
                                    try
                                    {
                                        objValue = message.Context.Read(ns_values[1], ns_values[0]);
                                        key      = str;
                                        if (objValue != null)
                                        {
                                            if (!ctxtValues.ContainsKey(key))
                                            {
                                                ctxtValues.Add(key, objValue.ToString());
                                            }
                                            else
                                            {
                                                ctxtValues[key] = objValue.ToString();
                                            }
                                        }
                                        else
                                        {
                                            if (!ctxtValues.ContainsKey(key))
                                            {
                                                ctxtValues.Add(key, string.Empty);
                                            }
                                            else
                                            {
                                                ctxtValues[key] = string.Empty;
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        EventLogger.LogMessage(string.Format("Namespace: {0}\nName: {1}\n caused an exception:\n{2}\nThis item was not added to the collection.", ns_values[0], ns_values[1], ex.Message), EventLogEntryType.Error, 1000);
                                    }
                                }
                            }
                            else
                            {
                                object   objValue;
                                string   key;
                                string[] ns_Values = new string[] { string.Empty, string.Empty };
                                try
                                {
                                    ns_Values = strMsgCtxtValues.Split('#');
                                    objValue  = message.Context.Read(ns_Values[1], ns_Values[0]);
                                    key       = strMsgCtxtValues;
                                    if (objValue != null)
                                    {
                                        if (!ctxtValues.ContainsKey(key))
                                        {
                                            ctxtValues.Add(key, objValue.ToString());
                                        }
                                    }
                                    else
                                    {
                                        if (!ctxtValues.ContainsKey(key))
                                        {
                                            ctxtValues.Add(key, string.Empty);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    EventLogger.LogMessage(string.Format("Namespace: {0}\nName: {1}\n caused an exception:\n{2}\nThis item was not added to the collection.", ns_Values[0], ns_Values[1], ex.Message), EventLogEntryType.Error, 1000);
                                }
                            }
                        }
                    }
                }
                dictionary = ResolveRules(config, resolver, document, resolution, bre, ctxtValues, pipelineContext, ref message);
            }
            catch (Exception exception)
            {
                EventLogger.Write(MethodBase.GetCurrentMethod(), exception);
                throw;
            }
            finally
            {
                if (resolution != null)
                {
                    resolution = null;
                }
            }
            return(dictionary);
        }
Пример #25
0
        /// <summary>
        /// Clones a pipeline message creating an entirely independent and seekable copy.
        /// </summary>
        /// <param name="message">The message to be cloned.</param>
        /// <param name="pc">The pipeline context.</param>
        /// <returns>The cloned message.</returns>
        public static IBaseMessage Clone(this IBaseMessage message, IPipelineContext pc)
        {
            // Create the cloned message
            var messageFactory = pc.GetMessageFactory();
            var clonedMessage  = messageFactory.CreateMessage();

            // Clone each part
            for (var partNo = 0; partNo < message.PartCount; partNo++)
            {
                string partName;
                var    part = message.GetPartByIndex(partNo, out partName);

                // Create and initilialize the new part
                var newPart = messageFactory.CreateMessagePart();
                newPart.Charset     = part.Charset;
                newPart.ContentType = part.ContentType;

                // Get the original uncloned data stream
                var originalStream = part.GetOriginalDataStream();

                // If the original data stream is non-seekable, check the clone
                // returned by the Data property, and failing that, or if the
                // clone is not seekablem manufacture a seekable stream.
                if (!originalStream.CanSeek)
                {
                    Stream candidateSeekableStream;

                    try
                    {
                        candidateSeekableStream = part.Data;
                    }
                    catch (NotSupportedException)
                    {
                        // Some streams (e.g. ICSharpCode.SharpZipLib.Zip.ZipInputStream) throw
                        // a System.NotSupportedException when an attempt is made to clone them
                        candidateSeekableStream = null;
                    }

                    if (candidateSeekableStream != null && !candidateSeekableStream.Equals(originalStream))
                    {
                        if (candidateSeekableStream.CanSeek)
                        {
                            originalStream = candidateSeekableStream;
                        }
                        else
                        {
                            originalStream = new ReadOnlySeekableStream(candidateSeekableStream);
                        }
                    }
                    else
                    {
                        originalStream = new ReadOnlySeekableStream(originalStream);
                    }
                }

                // Add the original stream to the Resource tracker to prevent it being
                // disposed, in case we need to clone the same stream multiple times.
                pc.ResourceTracker.AddResource(originalStream);
                originalStream.StreamAtStart();

                // Create the new part with a Virtual Stream, and add the the resource tracker
                newPart.Data = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);
                pc.ResourceTracker.AddResource(newPart.Data);

                // Clone the stream, and seek back to the beginning
                originalStream.CopyTo(newPart.Data);
                originalStream.StreamAtStart();

                // Create and populate the property bag for the new message part.
                newPart.Data.StreamAtStart();
                newPart.PartProperties = messageFactory.CreatePropertyBag();
                var partPoperties = part.PartProperties;

                for (var propertyNo = 0; propertyNo < partPoperties.CountProperties; propertyNo++)
                {
                    string propertyName, propertyNamespace;
                    var    property = partPoperties.ReadAt(propertyNo, out propertyName, out propertyNamespace);
                    newPart.PartProperties.Write(propertyName, propertyNamespace, property);
                }

                // Add the new part to the cloned message
                clonedMessage.AddPart(partName, newPart, partName == message.BodyPartName);
            }

            // Copy the context from old to new
            clonedMessage.Context = message.Context;

            return(clonedMessage);
        }