/// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message.</param>
        /// <returns>Processed input message with appended or prepended data.</returns>
        /// <remarks>
        /// Converts xsl-fo transformed messages to pdf
        /// </remarks>
        public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg)
        {
            IBaseMessagePart bodyPart = inmsg.BodyPart;

            if (bodyPart.Data != null)
            {
                VirtualStream vtstm = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);

                FonetDriver driver = FonetDriver.Make();
                driver.CloseOnExit = false;//important for biztalk to work ... set position = 0

                PdfRendererOptions options = new PdfRendererOptions();
                options.Title        = Title;
                options.Subject      = Subject;
                options.UserPassword = Password;

                driver.Options = options;

                Stream stm = bodyPart.GetOriginalDataStream();
                stm.Seek(0, SeekOrigin.Begin);

                driver.Render(stm, vtstm);

                vtstm.Seek(0, SeekOrigin.Begin);

                bodyPart.Data = vtstm;
            }
            return(inmsg);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Populates a body part with content from an XML document.  If no body part exists, a new one
        /// is created.
        /// </summary>
        /// <param name="message">The massage to which the body part will be added.</param>
        /// <param name="part">The existing part</param>
        /// <param name="pc">The pipeline context.</param>
        /// <returns>A message with a body part populated by the XML document content.</returns>
        public static bool PopulateBodyPartFromExistingPart(this IBaseMessage message, IBaseMessagePart part, IPipelineContext pc)
        {
            if (message == null || part == null)
            {
                return(false);
            }

            Func <IBaseMessagePart> clonedPart = () =>
            {
                var newPart = pc.GetMessageFactory().CreateMessagePart();
                newPart.Data = part.GetOriginalDataStream().Clone();
                return(newPart);
            };

            var outPart = part.IsMutable
                ? clonedPart()
                : part.WithStreamAtStart();

            // Add a body part if none exists.
            if (message.BodyPart == null)
            {
                message.AddPart("Body", outPart, true);
            }

            return(true);
        }
Exemplo n.º 3
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

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

            String value = null;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;

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

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

            xPathCollection.Add(XPath);

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

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

                    break;
                }
            }

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

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

            return(pInMsg);
        }
Exemplo n.º 4
0
        public void SubmitMessage(IBaseMessage message, object userData = null)
        {
            if (_submitResponseMessageArray != null)
            {
                throw new InvalidOperationException("SubmitResponseMessage and SubmitMessage operations cannot be in the same batch");
            }

            // We need to have data (body part) to handle batch failures.
            IBaseMessagePart bodyPart = message.BodyPart;

            if (bodyPart == null)
            {
                throw new InvalidOperationException("The message doesn't contain body part");
            }

            Stream stream = bodyPart.GetOriginalDataStream();

            if (stream == null || stream.CanSeek == false)
            {
                throw new InvalidOperationException("Cannot submit empty body or body with non-seekable stream");
            }

            _transportBatch.SubmitMessage(message);
            if (null == _submitArray)
            {
                _submitArray = new List <BatchMessage>();
            }
            _submitArray.Add(new BatchMessage(message, userData));

            _workToBeDone = true;
        }
        IBaseMessage IComponent.Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            Trace.WriteLine("DotNetTypesToJsonConverter Pipeline - Entered Execute()");
            Trace.WriteLine("DotNetTypesToJsonConverter Pipeline - TypeName is set to: " + TypeName);

            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            if (bodyPart != null)
            {
                Stream originalStream = bodyPart.GetOriginalDataStream();
                if (originalStream != null)
                {
                    Type myClassType = Type.GetType(TypeName);

                    object reqObj = PcHelper.FromXml(originalStream, myClassType);

                    string jsonText = JsonConvert.SerializeObject(reqObj, myClassType, Formatting.None,
                                                                  new JsonSerializerSettings());
                    Trace.WriteLine("DotNetTypesToJsonConverter output: " + jsonText);

                    byte[] outBytes = Encoding.ASCII.GetBytes(jsonText);

                    var memStream = new MemoryStream();
                    memStream.Write(outBytes, 0, outBytes.Length);
                    memStream.Position = 0;

                    bodyPart.Data = memStream;
                    pContext.ResourceTracker.AddResource(memStream);
                }
            }
            Trace.WriteLine("DotNetTypesToJsonConverter Pipeline - Exited Execute()");
            return(pInMsg);
        }
Exemplo n.º 6
0
        public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            if (bodyPart != null)
            {
                Stream originalStream = bodyPart.GetOriginalDataStream();

                if (originalStream != null)
                {
                    using (ZipInputStream zipInputStream = new ZipInputStream(originalStream))
                    {
                        if (_password != null && _password.Length > 0)
                        {
                            zipInputStream.Password = _password;
                        }

                        ZipEntry entry = zipInputStream.GetNextEntry();

                        while (entry != null)
                        {
                            MemoryStream memStream = new MemoryStream();
                            byte[]       buffer    = new Byte[1024];

                            int bytesRead = 1024;
                            while (bytesRead != 0)
                            {
                                bytesRead = zipInputStream.Read(buffer, 0, buffer.Length);
                                memStream.Write(buffer, 0, bytesRead);
                            }

                            string fileName  = entry.FileName.ToString();   //file name in zip file
                            string extension = Path.GetExtension(fileName);

                            IBaseMessage outMessage;
                            outMessage = pContext.GetMessageFactory().CreateMessage();
                            outMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);
                            memStream.Position       = 0;
                            outMessage.BodyPart.Data = memStream;


                            IBaseMessageContext context = pInMsg.Context;
                            string receivePortName      = context.Read("ReceivePortName", "http://schemas.microsoft.com/BizTalk/2003/system-properties").ToString();
                            string fullPath             = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();
                            string filePath             = Path.GetDirectoryName(fullPath);

                            outMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);
                            outMessage.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", fileName);
                            outMessage.Context.Promote("ReceivePortName", "http://schemas.microsoft.com/BizTalk/2003/system-properties", receivePortName);

                            _qOutMessages.Enqueue(outMessage);

                            entry = zipInputStream.GetNextEntry();
                        }
                    }
                }
            }
        }
        /// <summary>
        /// called by the messaging engine when a new message arrives
        /// </summary>
        /// <param name="pc">the pipeline context</param>
        /// <param name="inmsg">the actual message</param>
        public void Disassemble(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            //
            // TODO: implement message retrieval logic
            IBaseMessagePart Body = inmsg.BodyPart;

            if (Body != null)
            {
                Stream originalStream = Body.GetOriginalDataStream();
                if (originalStream != null)
                {
                    var xml         = XElement.Load(originalStream);
                    var rootElement = xml.Name;
                    // Child elements from source file to split by.
                    var childNodes = xml.Descendants(this.DescendantElement);

                    // This is the total number of elements to be sliced up into
                    // separate files.
                    int cnt = childNodes.Count();

                    var skip   = 0;
                    var take   = this.BatchSize;
                    var fileno = 0;

                    // Split elements into chunks and save to disk.
                    while (skip < cnt)
                    {
                        // Extract portion of the xml elements.
                        var c1 = childNodes
                                 .Skip(skip)
                                 .Take(take);

                        // Setup number of elements to skip on next iteration.
                        skip += take;
                        // File sequence no for split file.
                        fileno += 1;
                        // Filename for split file.
                        // Create a partial xml document.
                        XElement frag = new XElement(rootElement, c1);
                        // Save to disk.
                        var newStream = new MemoryStream();
                        frag.Save(newStream);
                        newStream.Position = 0;
                        pc.ResourceTracker.AddResource(newStream);
                        IBaseMessage newmsg = pc.GetMessageFactory().CreateMessage();
                        newmsg.AddPart("Body", pc.GetMessageFactory().CreateMessagePart(), true);
                        newmsg.BodyPart.Data = newStream;
                        newmsg.Context       = PipelineUtil.CloneMessageContext(inmsg.Context);
                        //outMsg.Context.Promote("MessageType",  "http://schemas.microsoft.com/BizTalk/2003/system-properties",      "Namespace#Root");
                        var msgtype = (string.IsNullOrEmpty(rootElement.Namespace.NamespaceName)?"" : rootElement.Namespace.NamespaceName + "#") + rootElement.LocalName;
                        newmsg.Context.Write("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", msgtype);
                        newmsg.Context.Promote("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", msgtype);

                        _msgs.Enqueue(newmsg);
                    }
                }
            }
        }
 /// <summary>
 /// Return the content of a claim token message, either <see cref="Claim.Check"/>, <see cref="Claim.CheckIn"/>, or
 /// <see cref="Claim.CheckOut"/>, as a <see cref="MessageBodyCaptureDescriptor"/> filled in according to the
 /// content of the claim token.
 /// </summary>
 /// <param name="messagePart">
 /// The part whose stream contains a claim token.
 /// </param>
 /// <returns>
 /// The <see cref="MessageBodyCaptureDescriptor"/> corresponding to the content of the claim token.
 /// </returns>
 internal static MessageBodyCaptureDescriptor AsMessageBodyCaptureDescriptor(this IBaseMessagePart messagePart)
 {
     // Claim.Check, Claim.CheckIn, and Claim.CheckOut are all in the same XML Schema: any one can be used to
     // reference the XML Schema to use to validate a token message, whatever its specific type
     using (var reader = ValidatingXmlReader.Create <Claim.CheckOut>(messagePart.GetOriginalDataStream(), XmlSchemaContentProcessing.Lax))
     {
         return(reader.AsMessageBodyCaptureDescriptor());
     }
 }
Exemplo n.º 9
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            String value   = null;
            bool   suspend = false;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;



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

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

            xPathCollection.Add(XPath);

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

                    break;
                }
            }


            suspend = ScriptExpressionHelper.ValidateExpression(value, Expression);

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

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


            return(pInMsg);
        }
        /// <summary>
        /// Set property from XPath
        /// </summary>
        /// <param name="pContext"></param>
        /// <param name="pInMsg"></param>
        /// <returns></returns>
        public IBaseMessage ExecuteTwo(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

            //this error Message can be got from validate the message
            //if (!XmlHelper.Validate(out errorMessage))
            //{
            //    throw new ArgumentException(errorMessage);
            //}

            String value = null;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;

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

            XmlTextReader xmlTextReader = new XmlTextReader(readOnlySeekableStream);

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

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

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

            //        //break;
            //    }
            //}

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

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

            return(pInMsg);
        }
Exemplo n.º 11
0
        //https://docs.microsoft.com/en-us/biztalk/core/how-to-use-message-context-properties
        //https://docs.microsoft.com/en-us/biztalk/core/file-adapter-property-schema-and-properties
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessageContext context = pInMsg.Context;
            object obj = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties");
            //fileName = ((string)obj).Substring(((string)obj).LastIndexOf("\\") + 1);
            string fullPath = Path.GetFullPath((string)obj);
            string fileName = Path.GetFileName(fullPath);
            string filePath = Path.GetDirectoryName(fullPath);

            Byte[]           TextFileBytes = null;
            IBaseMessagePart msgBodyPart   = pInMsg.BodyPart;

            //Creating outMessage
            IBaseMessage outMessage;

            outMessage = pContext.GetMessageFactory().CreateMessage();

            if (msgBodyPart != null)
            {
                outMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);
                Stream msgBodyPartStream = msgBodyPart.GetOriginalDataStream();
                TextFileBytes = StreamToByteArray(msgBodyPartStream);
                outMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);


                IDictionary <string, Byte[]> lst = new Dictionary <string, Byte[]>();
                lst.Add(fileName, TextFileBytes);

                MemoryStream ms = new MemoryStream();
                ms.Seek(0, SeekOrigin.Begin);

                using (ZipFile zip = new ZipFile())
                {
                    //zip.Password = _password;
                    if (_password != null)
                    {
                        zip.Password = _password;
                    }
                    zip.Encryption       = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

                    foreach (KeyValuePair <string, Byte[]> item in (IDictionary <string, Byte[]>)lst)
                    {
                        zip.AddEntry(item.Key, item.Value); //Key:fileName, Value:TextFileBytes
                    }
                    zip.Save(ms);
                }

                ms.Position = 0;
                outMessage.BodyPart.Data = ms;
                outMessage.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", fileName.Substring(0, fileName.IndexOf(".")));
            }
            return(outMessage);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Reads the response message from the server
        /// </summary>
        /// <param name="msg">Response message from the server</param>
        /// <returns>Flag to delete message from the server or not</returns>
        public bool TransmitMessage(IBaseMessage msg)
        {
            // Note: We need to read the stream which will execute the
            // pipeline, we then replace the stream with the one we
            // have created
            IBaseMessagePart bodyPart = msg.BodyPart;
            Stream           s        = null;

            if (bodyPart != null)
            {
                s = bodyPart.GetOriginalDataStream();
            }

            // Create a memory stream to copy the data into
            Stream memStrm = new MemoryStream();

            byte[] buff = new byte[4096];
            int    dataRead = 0, readOffSet = 0, writeOffSet = 0;

            if (s != null)
            {
                s.Seek(0, SeekOrigin.Begin);

                // Copy the data from the src stream
                do
                {
                    dataRead = s.Read(buff, readOffSet, 4096);
                    memStrm.Write(buff, writeOffSet, dataRead);
                } while (dataRead > 0);
            }

            // Create a new message
            IBaseMessage response = BizTalkMessaging._mf.CreateMessage();

            // Copy over the context
            response.Context = msg.Context;

            // Copy over the body part, note, only support single part messages
            IBaseMessagePart messageBodyPart = BizTalkMessaging._mf.CreateMessagePart();

            messageBodyPart.Data = memStrm;

            memStrm.Seek(0, SeekOrigin.Begin);
            response.AddPart(msg.BodyPartName, messageBodyPart, true);

            _msg = response;

            ThreadPool.QueueUserWorkItem(DeleteTransmitMessage, msg);

            // Return false.
            // We'll issue a Batch.DeleteMessage() later.
            return(false);
        }
Exemplo n.º 13
0
        IBaseMessage IComponent.Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            Trace.WriteLine("JsonToXmlConverter Pipeline - Entered Execute()");
            Trace.WriteLine("JsonToXmlConverter Pipeline - RemoveAtTheRateChar is set to: " + RemoveAtTheRateChar);
            Trace.WriteLine("JsonToXmlConverter Pipeline - OmitRootObject is set to: " + OmitRootObject);

            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            if (bodyPart != null)
            {
                Stream originalStream = bodyPart.GetOriginalDataStream();
                if (originalStream != null)
                {
                    var xdoc = new XmlDocument();
                    xdoc.Load(originalStream);

                    if (xdoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        xdoc.RemoveChild(xdoc.FirstChild);
                    }

                    string jsonText;
                    if (OmitRootObject)
                    {
                        jsonText = JsonConvert.SerializeXmlNode(xdoc, Formatting.Indented, true);
                    }
                    else
                    {
                        jsonText = JsonConvert.SerializeXmlNode(xdoc, Formatting.Indented, false);
                    }

                    if (RemoveAtTheRateChar)
                    {
                        jsonText = Regex.Replace(jsonText, "(?<=\")(@)(?!.*\":\\s )", String.Empty,
                                                 RegexOptions.IgnoreCase);
                        Trace.WriteLine("JsonToXmlConverter Pipeline - Removed the '@' Character");
                    }
                    Trace.WriteLine("JsonToXmlConverter output: " + jsonText);

                    byte[] outBytes = Encoding.ASCII.GetBytes(jsonText);

                    var memStream = new MemoryStream();
                    memStream.Write(outBytes, 0, outBytes.Length);
                    memStream.Position = 0;

                    bodyPart.Data = memStream;
                    pContext.ResourceTracker.AddResource(memStream);
                }
            }
            Trace.WriteLine("JsonToXmlConverter Pipeline - Exited Execute()");
            return(pInMsg);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Returns a seekable version of a message's data stream. The stream will be wrapped in a ReadOnlySeekableDataStream if needed.
        /// </summary>
        /// <param name="pipelineContext">The pipeline context of the message.</param>
        /// <param name="messagePart">The message part for which a seekable stream is required.</param>
        /// <returns>A seekable version of the message stream.</returns>
        public static Stream GetReadOnlySeekableDataStream(IPipelineContext pipelineContext, IBaseMessagePart messagePart)
        {
            Stream dataStream = messagePart.GetOriginalDataStream();

            if (!dataStream.CanSeek)
            {
                ReadOnlySeekableStream seekableStream = new ReadOnlySeekableStream(dataStream);
                messagePart.Data = seekableStream;
                pipelineContext.ResourceTracker.AddResource(seekableStream);
                dataStream = seekableStream;
            }
            return(dataStream);
        }
Exemplo n.º 15
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);
        }
        public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            if (bodyPart != null)
            {
                Stream       originalStream = bodyPart.GetOriginalDataStream();
                MemoryStream memStream      = new MemoryStream();
                byte[]       buffer         = new Byte[1024];
                int          bytesRead      = 1024;

                while (bytesRead != 0)
                {
                    bytesRead = originalStream.Read(buffer, 0, buffer.Length);
                    memStream.Write(buffer, 0, bytesRead);
                }

                memStream.Position = 0;

                if (originalStream != null)
                {
                    using (ZipArchive zipArchive = new ZipArchive(memStream, ZipArchiveMode.Read))
                    {
                        foreach (ZipArchiveEntry entry in zipArchive.Entries)
                        {
                            MemoryStream entryStream           = new MemoryStream();
                            byte[]       entrybuffer           = new Byte[1024];
                            int          entryBytesRead        = 1024;
                            Stream       zipArchiveEntryStream = entry.Open();
                            while (entryBytesRead != 0)
                            {
                                entryBytesRead = zipArchiveEntryStream.Read(entrybuffer, 0, entrybuffer.Length);
                                entryStream.Write(entrybuffer, 0, entryBytesRead);
                            }

                            IBaseMessage outMessage;
                            outMessage = pContext.GetMessageFactory().CreateMessage();
                            outMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);
                            entryStream.Position     = 0;
                            outMessage.BodyPart.Data = entryStream;

                            pInMsg.Context.Promote(new ContextProperty(FileProperties.ReceivedFileName), entry.Name);
                            outMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);
                            _qOutMessages.Enqueue(outMessage);
                        }
                    }
                }
            }
        }
Exemplo n.º 17
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 Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            Stream       originalStrm = null;
            FileStream   fileArchive  = null;
            BinaryWriter binWriter    = null;
            const int    bufferSize   = 1024;

            try
            {
                IBaseMessagePart bodyPart = inmsg.BodyPart;

                if (bodyPart != null)
                {
                    string path = filePath + "." + fileExtension;
                    path = path.Replace("%MessageID%", inmsg.MessageID.ToString());

                    originalStrm = bodyPart.GetOriginalDataStream();

                    fileArchive = new FileStream(path, FileMode.Create, FileAccess.Write);
                    binWriter   = new BinaryWriter(fileArchive);

                    byte[] buffer   = new byte[bufferSize];
                    int    sizeRead = 0;

                    while ((sizeRead = originalStrm.Read(buffer, 0, bufferSize)) != 0)
                    {
                        binWriter.Write(buffer, 0, sizeRead);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(ex.Source, ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
            }
            finally
            {
                if (binWriter != null)
                {
                    binWriter.Flush();
                    binWriter.Close();
                }
                originalStrm.Seek(0, SeekOrigin.Begin);
            }
            return(inmsg);
        }
Exemplo n.º 18
0
        public override sealed void SubmitResponseMessage(IBaseMessage solicitDocSent, IBaseMessage responseDocToSubmit)
        {
            IBaseMessagePart bodyPart = responseDocToSubmit.BodyPart;

            if (bodyPart == null)
            {
                throw new InvalidOperationException("The message does not contain body part");
            }

            Stream stream = bodyPart.GetOriginalDataStream();

            if (stream == null || stream.CanSeek == false)
            {
                throw new InvalidOperationException("Message body stream is null or it is not seekable");
            }

            base.SubmitResponseMessage(solicitDocSent, responseDocToSubmit, solicitDocSent);
        }
        /// <summary>
        /// Seeks back to the origin of a stream.
        /// </summary>
        /// <param name="messagePart">A pipeline messagePart part.</param>
        /// <returns>A seekable stream set at its origin.</returns>
        // ReSharper disable once UnusedMethodReturnValue.Local
        public static IBaseMessagePart WithStreamAtStart(this IBaseMessagePart messagePart)
        {
            // Obtain a reference to the original message stream
            var originalDataStream = messagePart.GetOriginalDataStream();

            // If the original data stream is seekable, then return it as the caller can simply reset
            // the position once it's been read
            if (originalDataStream.CanSeek)
            {
                messagePart.Data = originalDataStream.StreamAtStart();
            }
            else
            {
                // Attempt to obtain a reference to a clone of the original message stream.
                Stream clonedStream;

                try
                {
                    clonedStream = messagePart.Data;
                }
                catch
                {
                    // Some streams throw an exception (e.g., a System.NotSupportedException)
                    // when an attempt is made to clone them.
                    clonedStream = null;
                }

                // If the theoretical clone is a true clone, then use it.
                if (clonedStream != null && clonedStream.Equals(originalDataStream) == false)
                {
                    clonedStream.Position = 0;
                    messagePart.Data      = clonedStream.StreamAtStart();
                }
                else
                {
                    // Otherwise, we need to replace the stream with one which is seekable
                    messagePart.Data = originalDataStream.StreamAtStart();
                }
            }

            return(messagePart);
        }
        public Microsoft.BizTalk.Message.Interop.IBaseMessage ExecuteThree(IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
        {
            IBaseMessagePart       bodyPart               = pInMsg.BodyPart;
            Stream                 inboundStream          = bodyPart.GetOriginalDataStream();
            VirtualStream          virtualStream          = new VirtualStream(0x280, 0x100000);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream, 0x280);
            XmlTextReader          xmlTextReader          = new XmlTextReader(readOnlySeekableStream);
            //XPathCollection xPathCollection = new XPathCollection();
            //xPathCollection.Add("/*[local-name()='LFT' and namespace-uri()='http://Codit.LFT.Schemas']/*[local-name()='TempFile' and namespace-uri()='']");
            //XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection);
            bool   ok  = false;
            string val = string.Empty;

            //while (xPathReader.ReadUntilMatch())
            //{
            //    if (xPathReader.Match(0) && !ok)
            //    {
            //        val = xPathReader.ReadString();
            //        ok = true;
            //    }
            //}
            if (ok)
            {
                VirtualStream outboundStream = new VirtualStream(0x280, 0xA00000);
                using (FileStream fs = new FileStream(val, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    byte[] buffer    = new byte[4096];
                    int    bytesRead = fs.Read(buffer, 0, buffer.Length);
                    while (bytesRead != 0)
                    {
                        outboundStream.Write(buffer, 0, bytesRead);
                        outboundStream.Flush();
                        bytesRead = fs.Read(buffer, 0, buffer.Length);
                    }
                }
                outboundStream.Position = 0;
                bodyPart.Data           = outboundStream;
            }

            return(pInMsg);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message.</param>
        /// <returns>Processed input message with appended or prepended data.</returns>
        /// <remarks>
        /// IComponent.Execute method is used to initiate
        /// the processing of the message in pipeline component.
        /// </remarks>
        public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg)
        {
            IBaseMessagePart bodyPart = inmsg.BodyPart;

            if (bodyPart != null)
            {
                byte[] prependByteData = ConvertToBytes(prependData);
                byte[] appendByteData  = ConvertToBytes(appendData);
                Stream originalStrm    = bodyPart.GetOriginalDataStream();
                Stream strm            = null;

                if (originalStrm != null)
                {
                    strm          = new FixMsgStream(originalStrm, prependByteData, appendByteData, resManager);
                    bodyPart.Data = strm;
                    pc.ResourceTracker.AddResource(strm);
                }
            }

            return(inmsg);
        }
Exemplo n.º 22
0
        // This is for submit-response
        protected override void SubmitSuccess(IBaseMessage message, Int32 hrStatus, object userData)
        {
            if (this.batchFailed)
            {
                // Previous submit operation might have moved the stream position
                // Seek the stream position back to zero before submitting again!
                IBaseMessage solicit = userData as IBaseMessage;
                if (solicit == null)
                {
                    throw new InvalidOperationException("Response message does not have corresponding request message");
                }

                IBaseMessagePart responseBodyPart = message.BodyPart;

                if (responseBodyPart != null)
                {
                    Stream stream = responseBodyPart.GetOriginalDataStream();
                    stream.Position = 0;
                }
                this.batch.SubmitResponseMessage(solicit, message);
            }
        }
        /// <summary>
        /// Wraps this message part's original data stream in another stream returned by the <paramref name="wrapper"/>
        /// delegate.
        /// </summary>
        /// <param name="messagePart">
        /// The part whose original data stream is wrapped.
        /// </param>
        /// <param name="wrapper">
        /// A delegate, or stream factory, that returns the stream wrapping the original one.
        /// </param>
        /// <param name="tracker">
        /// Pipeline's resource tracker to which to report the newly created wrapping stream.
        /// </param>
        /// <returns>
        /// The new wrapping <see cref="Stream"/> if it is not the same instance as the original one. The original <see
        /// cref="Stream"/> otherwise.
        /// </returns>
        public static T WrapOriginalDataStream <T>(this IBaseMessagePart messagePart, Func <Stream, T> wrapper, IResourceTracker tracker) where T : Stream
        {
            // TODO ?consider providing an overload when there is no IResourceTracker as this is necessary only for unmanaged objects/resources?

            if (messagePart == null)
            {
                throw new ArgumentNullException("messagePart");
            }
            if (wrapper == null)
            {
                throw new ArgumentNullException("wrapper");
            }
            if (tracker == null)
            {
                throw new ArgumentNullException("tracker");
            }

            var originalDataStream = messagePart.GetOriginalDataStream();

            if (originalDataStream == null)
            {
                return(null);
            }

            var wrappingStream = wrapper(originalDataStream);

            if (ReferenceEquals(originalDataStream, wrappingStream))
            {
                return((T)originalDataStream);
            }

            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat("Wrapping message part's original data stream in a '{0}' stream.", wrappingStream.GetType().FullName);
            }
            messagePart.SetDataStream(wrappingStream, tracker);
            return(wrappingStream);
        }
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            bool terminate = true;

            IBaseMessagePart bodyPart = pInMsg.BodyPart;



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

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

            xPathCollection.Add(XPath);

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


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


            return(pInMsg);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Wraps this message part's original data stream in another stream returned by the <paramref name="wrapper"/>
        /// delegate.
        /// </summary>
        /// <param name="messagePart">
        /// The part whose original data stream is wrapped.
        /// </param>
        /// <param name="wrapper">
        /// A delegate, or stream factory, that returns the stream wrapping the original one.
        /// </param>
        /// <param name="tracker">
        /// Pipeline's resource tracker to which to report the newly created wrapping stream.
        /// </param>
        /// <returns>
        /// The new wrapping <see cref="Stream"/> if it is not the same instance as the original one. The original <see
        /// cref="Stream"/> otherwise.
        /// </returns>
        public static T WrapOriginalDataStream <T>(this IBaseMessagePart messagePart, Func <Stream, T> wrapper, IResourceTracker tracker) where T : Stream
        {
            if (messagePart == null)
            {
                throw new ArgumentNullException(nameof(messagePart));
            }
            if (wrapper == null)
            {
                throw new ArgumentNullException(nameof(wrapper));
            }
            if (tracker == null)
            {
                throw new ArgumentNullException(nameof(tracker));
            }

            var originalDataStream = messagePart.GetOriginalDataStream();

            if (originalDataStream == null)
            {
                return(null);
            }

            var wrappingStream = wrapper(originalDataStream);

            if (ReferenceEquals(originalDataStream, wrappingStream))
            {
                return((T)originalDataStream);
            }

            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat("Wrapping message part's original data stream in a '{0}' stream.", wrappingStream.GetType().FullName);
            }
            messagePart.SetDataStream(wrappingStream, tracker);
            return(wrappingStream);
        }
        /// <summary>
        /// Output new IBaseMessage output from a file.
        /// </summary>
        /// <param name="pContext"></param>
        /// <param name="pInMsg"></param>
        /// <returns></returns>
        public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
        {
            IBaseMessagePart       bodyPart               = pInMsg.BodyPart;
            Stream                 inboundStream          = bodyPart.GetOriginalDataStream();
            VirtualStream          virtualStream          = new VirtualStream(0x280, 0x100000);
            ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream, 0x280);
            string                 tempFile               = Path.GetTempFileName();

            using (FileStream fs = new FileStream(tempFile, FileMode.Open, FileAccess.Write, FileShare.Read))
            {
                byte[] buffer    = new byte[0x280];
                int    bytesRead = readOnlySeekableStream.Read(buffer, 0, buffer.Length);
                while (bytesRead != 0)
                {
                    fs.Write(buffer, 0, bytesRead);
                    fs.Flush();
                    bytesRead = readOnlySeekableStream.Read(buffer, 0, buffer.Length);
                }
            }

            VirtualStream outputStream = new VirtualStream();

            using (XmlWriter xw = XmlWriter.Create(outputStream))
            {
                const string NameSpace = "http://Codit.LFT.Schemas";
                xw.WriteStartDocument();
                xw.WriteStartElement("ns0", "LFT", NameSpace);
                xw.WriteElementString("TempFile", tempFile);
                xw.WriteEndDocument();
            }

            outputStream.Position = 0;
            pContext.ResourceTracker.AddResource(outputStream);
            pInMsg.BodyPart.Data = outputStream;
            return(pInMsg);
        }
Exemplo n.º 27
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);
        }
        /// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message.</param>
        /// <returns>Processed input message with appended or prepended data.</returns>
        /// <remarks>
        /// IComponent.Execute method is used to initiate
        /// the processing of the message in pipeline component.
        /// </remarks>
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            if (Enabled == false)
            {
                return(pInMsg);
            }

            if (null == pContext)
            {
                throw new ArgumentNullException("PC is null");
            }
            if (null == pInMsg)
            {
                throw new ArgumentNullException("pInMsg is null");
            }

            IBaseMessageContext messageContext = pInMsg.Context;

            if (pInMsg.BodyPart == null)
            {
                return(pInMsg);
            }
            IBaseMessagePart bodyPart = pInMsg.BodyPart;


            // send or receive
            string pipelineType = "";

            switch (pContext.StageID.ToString())
            {
            case CategoryTypes.CATID_Decoder:     // should only be here on receive
            case CategoryTypes.CATID_DisassemblingParser:
            case CategoryTypes.CATID_Validate:
            case CategoryTypes.CATID_PartyResolver:
                pipelineType = "Receive";
                break;

            case CategoryTypes.CATID_Encoder:     // should only be here on send
            case CategoryTypes.CATID_Transmitter:
            case CategoryTypes.CATID_AssemblingSerializer:
                pipelineType = "Send";
                break;

            default:
                pipelineType = "Unknown Pipeline Stage - " + pContext.StageID.ToString();
                break;
            }

            if (pipelineType.StartsWith("Unknown"))
            {
                throw new ApplicationException(pipelineType);
            }

            if (pipelineType == "Receive")
            {
                // do Receive
                string relativeURI = "";
                string fullURI     = "";

                Stream originalStrm = bodyPart.GetOriginalDataStream();

                if (originalStrm != null)
                {
                    StreamReader sr   = new StreamReader(originalStrm);
                    string       body = sr.ReadToEnd();

                    AzureClaimCheckPipelineComponentHelper.ParseInboundBody(body, ref fullURI, ref relativeURI);

                    string _storageAccount = "";
                    // if it is relative URI, storage account name must be in pipeline configuraion
                    if (!string.IsNullOrEmpty(relativeURI))
                    {
                        if (!string.IsNullOrEmpty(StorageAccountName))
                        {
                            _storageAccount = StorageAccountName;
                        }
                        else
                        {
                            throw new ApplicationException(string.Format("StorageAccountName not found, required with RelativeURI"));
                        }
                    }

                    // if fullURI then storage account name can be derived
                    if (!string.IsNullOrEmpty(fullURI))
                    {
                        Uri    blobLocation = new Uri(fullURI);
                        string hostURI      = blobLocation.Host;
                        if (!string.IsNullOrEmpty(StorageAccountName))
                        {
                            _storageAccount = hostURI.Substring(0, hostURI.IndexOf("."));
                        }
                        relativeURI = blobLocation.PathAndQuery;
                    }

                    // get SB Properties in not specified in pipeline configuration
                    if (string.IsNullOrEmpty(ClientId))
                    {
                        ClientId = AzureClaimCheckPipelineComponentHelper.GetContextProperty(messageContext, "ClientId", "https://AzureClaimCheck.AzureClaimCheckSBProperties");
                    }
                    if (string.IsNullOrEmpty(MessageTypeId))
                    {
                        MessageTypeId = AzureClaimCheckPipelineComponentHelper.GetContextProperty(messageContext, "MessageTypeId", "https://AzureClaimCheck.AzureClaimCheckSBProperties");
                    }

                    // get ClientId & MessageTypeId from relativeURI in not found in SB Properties or in pipeline configuration
                    // relativeURI should be /ClientId/MessageTypeId/filename
                    string tempRelativeURI = relativeURI;
                    if (string.IsNullOrEmpty(MessageTypeId))
                    {
                        try
                        {
                            tempRelativeURI = tempRelativeURI.Substring(0, tempRelativeURI.LastIndexOf('/'));
                            MessageTypeId   = tempRelativeURI.Substring(tempRelativeURI.LastIndexOf('/') + 1);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    if (string.IsNullOrEmpty(ClientId))
                    {
                        try
                        {
                            tempRelativeURI = tempRelativeURI.Substring(0, tempRelativeURI.LastIndexOf('/'));
                            ClientId        = tempRelativeURI.Substring(tempRelativeURI.LastIndexOf('/') + 1);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    bool bHaveStorageKey = false;
                    if (!string.IsNullOrEmpty(StorageAccountKey))
                    {
                        bHaveStorageKey = true;
                    }

                    // check key vault properties
                    if (!bHaveStorageKey)
                    {
                        if (!string.IsNullOrEmpty(KeyVaultURL))
                        {
                            if (!string.IsNullOrEmpty(KeyVaultClientId))
                            {
                                if (!string.IsNullOrEmpty(KeyVaultClientSecret))
                                {
                                    string keyVaultSecret = string.IsNullOrEmpty(ClientId) ? "" : ClientId;
                                    keyVaultSecret += string.IsNullOrEmpty(MessageTypeId) ? "" : MessageTypeId;
                                    keyVaultSecret += string.IsNullOrEmpty(_KeyVaultSecretSufix) ? "" : _KeyVaultSecretSufix;

                                    string StorageAccountKeyTemp = AzureClaimCheckPipelineComponentHelper.GetKeyVaultSecret(KeyVaultURL, KeyVaultClientId, KeyVaultClientSecret, keyVaultSecret).GetAwaiter().GetResult();
                                    StorageAccountKey = StorageAccountKeyTemp;
                                }
                            }
                        }
                    }

                    // find the container, reletive filename & filename
                    string container          = "";
                    string inFileNameRelative = "";
                    string inFileName         = "";

                    tempRelativeURI = relativeURI;
                    if (tempRelativeURI.StartsWith("/"))
                    {
                        tempRelativeURI = tempRelativeURI.Substring(1);
                    }
                    container          = tempRelativeURI.Substring(0, tempRelativeURI.IndexOf("/"));
                    inFileNameRelative = tempRelativeURI.Substring(tempRelativeURI.IndexOf("/") + 1);
                    inFileName         = inFileNameRelative.Substring(inFileNameRelative.LastIndexOf("/") + 1);

                    // check for storage key
                    if (!bHaveStorageKey)
                    {
                        if (string.IsNullOrEmpty(StorageAccountName))
                        {
                            throw new ApplicationException(string.Format("StorageAccountName not found"));
                        }
                        if (string.IsNullOrEmpty(StorageAccountKey))
                        {
                            throw new ApplicationException(string.Format("StorageAccountKey not found"));
                        }
                    }

                    // connect to storage account
                    StorageCredentials  creds         = new StorageCredentials(_storageAccount, StorageAccountKey);
                    CloudStorageAccount storAccount   = new CloudStorageAccount(creds, true);
                    CloudBlobClient     blobClient    = storAccount.CreateCloudBlobClient();
                    CloudBlobContainer  blobContainer = blobClient.GetContainerReference(container);
                    CloudBlob           blob          = blobContainer.GetBlobReference(inFileNameRelative);

                    MemoryStream strm = new MemoryStream();

                    blob.DownloadToStream(strm);
                    strm.Seek(0, SeekOrigin.Begin);

                    // set context properties
                    messageContext.Write("EventGridSubscriptionResponse", "https://AzureClaimCheck.AzureClaimCheckProperties", "False");
                    messageContext.Write("OriginalStoragePath", "https://AzureClaimCheck.AzureClaimCheckProperties", string.IsNullOrEmpty(fullURI) ? relativeURI : fullURI);
                    messageContext.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", inFileName);

                    messageContext.Write("ClientId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", ClientId);
                    messageContext.Write("MessageTypeId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", MessageTypeId);

                    bodyPart.Data = strm;
                    pContext.ResourceTracker.AddResource(strm);
                }
            }
            else
            {
                // do Send

                // prepare outbound file name
                string outFileName = AzureClaimCheckPipelineComponentHelper.ExpandFileName(messageContext, pInMsg.MessageID.ToString(), StorageOutboundFileName);

                bool bHaveStorageKey = false;
                if (!string.IsNullOrEmpty(StorageAccountKey))
                {
                    bHaveStorageKey = true;
                }

                // check key vault properties
                if (!bHaveStorageKey)
                {
                    if (!string.IsNullOrEmpty(KeyVaultURL))
                    {
                        if (!string.IsNullOrEmpty(KeyVaultClientId))
                        {
                            if (!string.IsNullOrEmpty(KeyVaultClientSecret))
                            {
                                string keyVaultSecret = string.IsNullOrEmpty(ClientId) ? "" : ClientId;
                                keyVaultSecret += string.IsNullOrEmpty(MessageTypeId) ? "" : MessageTypeId;
                                keyVaultSecret += string.IsNullOrEmpty(_KeyVaultSecretSufix) ? "" : _KeyVaultSecretSufix;

                                string StorageAccountKeyTemp = AzureClaimCheckPipelineComponentHelper.GetKeyVaultSecret(KeyVaultURL, KeyVaultClientId, KeyVaultClientSecret, keyVaultSecret).GetAwaiter().GetResult();
                                StorageAccountKey = StorageAccountKeyTemp;
                            }
                        }
                    }
                }

                // check for storage key
                if (!bHaveStorageKey)
                {
                    if (string.IsNullOrEmpty(StorageAccountName))
                    {
                        throw new ApplicationException(string.Format("StorageAccountName not found"));
                    }
                    if (string.IsNullOrEmpty(StorageAccountKey))
                    {
                        throw new ApplicationException(string.Format("StorageAccountKey not found"));
                    }
                }

                string outFileNameRelative = string.Format("{0}/{1}/{2}", ClientId, MessageTypeId, outFileName);

                // connect to storage account
                StorageCredentials  creds         = new StorageCredentials(StorageAccountName, StorageAccountKey);
                CloudStorageAccount storAccount   = new CloudStorageAccount(creds, true);
                CloudBlobClient     blobClient    = storAccount.CreateCloudBlobClient();
                CloudBlobContainer  blobContainer = blobClient.GetContainerReference(StorageOutboundContainer);
                blobContainer.CreateIfNotExists();
                CloudBlockBlob blob = blobContainer.GetBlockBlobReference(outFileNameRelative);

                blob.UploadFromStream(bodyPart.GetOriginalDataStream());

                string fullFileName = blob.Uri.AbsolutePath;

                // create service bus message body
                MemoryStream strm = new MemoryStream(Encoding.UTF8.GetBytes(fullFileName));
                strm.Seek(0, SeekOrigin.Begin);
                bodyPart.Data = strm;
                pContext.ResourceTracker.AddResource(strm);

                // set context properties for SB message
                if (!string.IsNullOrEmpty(ClientId))
                {
                    messageContext.Write("ClientId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", ClientId);
                }
                if (!string.IsNullOrEmpty(MessageTypeId))
                {
                    messageContext.Write("MessageTypeId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", MessageTypeId);
                }
            }

            return(pInMsg);
        }
        /// <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 Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            #region Copy input stream

            try
            {
                IBaseMessagePart bodyPart = inmsg.BodyPart;

                if (bodyPart != null)
                {
                    Stream originalStream = bodyPart.GetOriginalDataStream();

                    // Biztalk will not do property promotion in time if we do not touch the stream. Seems to be a quirk of how the send pipeline works.
                    // If original message is returned no property promotion will happen before the EDI assembler component gets the message.
                    if (originalStream != null)
                    {
                        StreamReader  sReader = new StreamReader(originalStream);
                        VirtualStream vStream = new VirtualStream();
                        StreamWriter  sWriter = new StreamWriter(vStream);

                        //Write message body to a virutal memory stream
                        sWriter.Write(sReader.ReadToEnd());
                        sWriter.Flush();
                        sReader.Close();

                        vStream.Seek(0, SeekOrigin.Begin);

                        pc.ResourceTracker.AddResource(vStream);
                        inmsg.BodyPart.Data = vStream;
                    }
                }

                #endregion

                #region Property promotion

                // Set the identificators. Make sure to set " " if missing to get property promoted (will make Biztalk fail the file on missing party)
                if (string.IsNullOrEmpty((string)inmsg.Context.Read(_senderId, _propertyNameSpace)))
                {
                    inmsg.Context.Promote("DestinationPartySenderIdentifier", _edifactPropertyNamespace, " ");
                }
                else
                {
                    inmsg.Context.Promote("DestinationPartySenderIdentifier", _edifactPropertyNamespace,
                                          inmsg.Context.Read(_senderId, _propertyNameSpace));
                }

                if (string.IsNullOrEmpty((string)inmsg.Context.Read(_receiverId, _propertyNameSpace)))
                {
                    inmsg.Context.Promote("DestinationPartyReceiverIdentifier", _edifactPropertyNamespace, " ");
                }
                else
                {
                    inmsg.Context.Promote("DestinationPartyReceiverIdentifier", _edifactPropertyNamespace,
                                          inmsg.Context.Read(_receiverId, _propertyNameSpace));
                }

                // If no qualifier is set in pipeline use " " since that will resolve as <no qualifier> in Biztalk.
                if (string.IsNullOrEmpty(_senderIdQualifier))
                {
                    inmsg.Context.Promote("DestinationPartySenderQualifier", _edifactPropertyNamespace, " ");
                }
                else
                {
                    // If no value is found on property set space as value (<No qualifier>)
                    if (string.IsNullOrEmpty((string)inmsg.Context.Read(_senderIdQualifier, _propertyNameSpace)))
                    {
                        inmsg.Context.Promote("DestinationPartySenderQualifier", _edifactPropertyNamespace, " ");
                    }
                    else
                    {
                        inmsg.Context.Promote("DestinationPartySenderQualifier", _edifactPropertyNamespace,
                                              inmsg.Context.Read(_senderIdQualifier, _propertyNameSpace));
                    }
                }

                // If no qualifier is set in pipeline use " " since that will resolve as <no qualifier> in Biztalk.
                if (string.IsNullOrEmpty(_receiverIdQualifier))
                {
                    inmsg.Context.Promote("DestinationPartyReceiverQualifier", _edifactPropertyNamespace, " ");
                }
                else
                {
                    // If no value is found on property set space as value (<No qualifier>)
                    if (string.IsNullOrEmpty((string)inmsg.Context.Read(_receiverIdQualifier, _propertyNameSpace)))
                    {
                        inmsg.Context.Promote("DestinationPartyReceiverQualifier", _edifactPropertyNamespace, " ");
                    }
                    else
                    {
                        inmsg.Context.Promote("DestinationPartyReceiverQualifier", _edifactPropertyNamespace,
                                              inmsg.Context.Read(_receiverIdQualifier, _propertyNameSpace));
                    }
                }
                return(inmsg);

                #endregion
            }
            catch (Exception ex)
            {
                if (inmsg != null)
                {
                    inmsg.SetErrorInfo(ex);
                }

                throw;
            }
        }
Exemplo n.º 30
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 Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            Stream           originalStrm = null;
            FileStream       fileArchive  = null;
            BinaryWriter     binWriter    = null;
            IBaseMessagePart bodyPart     = null;
            const int        bufferSize   = 1024;

            try
            {
                if (Enabled)
                {
                    //IBaseMessagePart bodyPart = inmsg.BodyPart;
                    bodyPart = inmsg.BodyPart;

                    if (bodyPart != null)
                    {
                        string FullPath = "";
                        //string TransportType = "";

                        FullPath = MakeFullPath(FilePath, FileName);

                        //TransportType = inmsg.Context.Read("OutboundTransportType", "http://schemas.microsoft.com/BizTalk/2003/system-properties") as string;

                        //if (TransportType == null)
                        //{
                        //    TransportType = inmsg.Context.Read("InboundTransportType", "http://schemas.microsoft.com/BizTalk/2003/system-properties") as string;
                        //}

                        //FullPath = ProcessDateTimeMacros(FullPath, inmsg);
                        //FullPath = ProcessMessageMacros(FullPath, inmsg);
                        //FullPath = ProcessSystemPropertiesMacros(FullPath, TransportType, inmsg);

                        //switch (TransportType)
                        //{
                        //    case "FILE":
                        //        FullPath = ProcessFilePropertiesMacros(FullPath, inmsg);
                        //        break;

                        //    case "FTP":
                        //        FullPath = ProcessFTPPropertiesMacros(FullPath, inmsg);
                        //        break;
                        //}

                        if (!Directory.Exists(Path.GetDirectoryName(FullPath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(FullPath));
                        }

                        if (!Overwrite)
                        {
                            if (File.Exists(FullPath + FileMask))
                            {
                                FullPath = FullPath + inmsg.MessageID.ToString();
                            }
                        }

                        FullPath = FullPath + FileMask;

                        originalStrm = bodyPart.GetOriginalDataStream();

                        if (!originalStrm.CanSeek)
                        {
                            ReadOnlySeekableStream seekableStream = new ReadOnlySeekableStream(originalStrm);
                            inmsg.BodyPart.Data = seekableStream;
                            originalStrm        = inmsg.BodyPart.Data;
                        }

                        pc.ResourceTracker.AddResource(originalStrm);

                        fileArchive = new FileStream(FullPath, FileMode.Create, FileAccess.Write);
                        binWriter   = new BinaryWriter(fileArchive);
                        byte[] buffer   = new byte[bufferSize];
                        int    sizeRead = 0;

                        while ((sizeRead = originalStrm.Read(buffer, 0, bufferSize)) != 0)
                        {
                            binWriter.Write(buffer, 0, sizeRead);
                        }
                    }
                }
            }

            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry(ex.Source, ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Warning);
            }

            finally
            {
                if (binWriter != null)
                {
                    binWriter.Flush();
                    binWriter.Close();
                }

                if (originalStrm != null)
                {
                    originalStrm.Seek(0, SeekOrigin.Begin);
                }
            }
            return(inmsg);
        }