Example #1
0
        public void Execute(ref Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, Microsoft.BizTalk.Component.Interop.IPipelineContext pc)
        {
            var stream = new MessageModificationTranslatorStream(inmsg.BodyPart.GetOriginalDataStream(), _messageModificationDetails, callToken);

            inmsg.BodyPart.Data = stream;
            pc.ResourceTracker.AddResource(stream);
        }
 public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(
     IPipelineContext pContext,
     Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
 {
     try
     {
         if (pInMsg != null)
         {
             Stream originalStream =
                 pInMsg.BodyPart.GetOriginalDataStream();
             pInMsg.BodyPart.Data = Decode(originalStream);
             pContext.ResourceTracker.AddResource(pInMsg.BodyPart.Data);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(
             @"Exception caught in ZipDecodeComponent::Execute: " +
             ex.Message);
         throw new ApplicationException(
                   @"ZipDecodeComponent was unable to decompress 
                     input stream. This may occur if there is more than one 
                     file in the zip archive. See inner exception 
                     for more information.", ex);
     }
     return(pInMsg);
 }
Example #3
0
 public void Execute(ref Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, Microsoft.BizTalk.Component.Interop.IPipelineContext pc)
 {
     if (xmlFactsApplicationStage == XMLFactsApplicationStageEnum.Explicit)
     {
         TypedXMLDocumentWrapper.ApplyTypedXMLDocument(document, inmsg, pc, callToken);
     }
 }
        /// <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(IPipelineContext pc,
                                                                      Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            /*************************************************************************************************************************
             * This component will read the MessageType from the Message Context Properties.                                         *
             *     BTS.MessageType: Specifies the type of the message. The message type is defined as a concatenation of document    *
             *                      schema namespace and document root node: http://<MyNamespace>#<MyRootNode>.                      *
             * and will promote the Operation property based on the content on the Root node "<MyRootNode>" specified on the         *
             * message type "http://<MyNamespace>#<MyRootNode>" of the message.                                                      *
             *                                                                                                                       *
             * Ex: Message Type = "http://schemas.integration.com#GetClientInfo"                                                     *
             *     Operation will be defined as "GetClientInfo"                                                                      *
             ************************************************************************************************************************/

            // Note:
            // System properties are mostly used internally by BizTalk Messaging Engine and its components.
            // In general, changing the values set by the engine for those properties is not recommended, because it may affect
            // the execution logic of the engine. However, there are a large number of properties that you can change.

            string msgType = Convert.ToString(inmsg.Context.Read("MessageType",
                                                                 "http://schemas.microsoft.com/BizTalk/2003/system-properties"));

            string operation = msgType.Substring(msgType.LastIndexOf('#') + 1);

            inmsg.Context.Promote("Operation", "http://schemas.microsoft.com/BizTalk/2003/system-properties",
                                  operation);

            return(inmsg);
        }
 public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(
     IPipelineContext pContext,
     Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
 {
     pInMsg.BodyPart.Data = new XmlNamespaceRemoverStream(
         pInMsg.BodyPart.GetOriginalDataStream());
     return pInMsg;
 }
Example #6
0
        public static Microsoft.BizTalk.Message.Interop.IBaseMessage Test_FF_Assembler_Pipeline <T1>(Microsoft.BizTalk.Message.Interop.IBaseMessage iBaseMsg)
        {
            Microsoft.BizTalk.Component.Interop.IBaseComponent comp = PTL.Simple.Assembler
                                                                      .FlatFile()
                                                                      .WithDocumentSpec <T1>().End();

            PTL.SendPipelineWrapper pipeline = PTL.Simple.Pipelines.Send()
                                               .WithAssembler(comp)
                                               .WithSpec <T1>();
            // Execute the send pipeline
            Microsoft.BizTalk.Message.Interop.IBaseMessage outputMessage = pipeline.Execute(iBaseMsg);

            return(outputMessage);
        }
Example #7
0
        /// <summary>
        /// Static method to apply a TypedXMLDocument to a BizTalk message body
        /// </summary>
        /// <param name="document"></param>
        /// <param name="inmsg"></param>
        /// <param name="pc"></param>
        /// <param name="callToken"></param>
        public static void ApplyTypedXMLDocument(TypedXmlDocument document, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, Microsoft.BizTalk.Component.Interop.IPipelineContext pc, string callToken)
        {
            TraceManager.PipelineComponent.TraceInfo("{0} - Applying typed XML document (overwriting current message body)", callToken);

            XmlDocument   doc = (XmlDocument)document.Document;
            VirtualStream ms  = new VirtualStream();

            doc.Save(ms);
            ms.Position         = 0;
            inmsg.BodyPart.Data = ms;

            // Add the new message body part's stream to the Pipeline Context's resource tracker so that it will be disposed off correctly
            pc.ResourceTracker.AddResource(ms);
        }
Example #8
0
        public static PTL.MessageCollection Test_FF_Disassembler_Pipeline <T1>(Microsoft.BizTalk.Message.Interop.IBaseMessage iBaseMsg)
        {
            Microsoft.BizTalk.Component.Interop.IBaseComponent comp = PTL.Simple.Disassembler
                                                                      .FlatFile().WithValidation(false)
                                                                      .WithDocumentSpec <T1>().End();

            PTL.ReceivePipelineWrapper pipeline = PTL.Simple.Pipelines.Receive()
                                                  .WithDisassembler(comp)
                                                  .WithSpec <T1>();

            // Execute the send pipeline
            PTL.MessageCollection outputMessage = pipeline.Execute(iBaseMsg);

            return(outputMessage);
        }
Example #9
0
        public void Execute(ref Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, Microsoft.BizTalk.Component.Interop.IPipelineContext pc)
        {
            StringBuilder outboundHeadersBuilder = new StringBuilder();

            foreach (KeyValuePair <string, string> kp in outboundHTTPHeadersCollection)
            {
                outboundHeadersBuilder.AppendFormat("{0}: {1}", kp.Key, kp.Value);
                outboundHeadersBuilder.Append(Environment.NewLine);
            }

            string outboundHeaders = outboundHeadersBuilder.ToString();

            TraceManager.PipelineComponent.TraceInfo(callToken + " - Adding outbound HTTP headers to the message with the below value " + Environment.NewLine + outboundHeaders);
            inmsg.Context.Write(BizTalkWCFPropertySchemaEnum.HttpHeaders.ToString(), ContextPropertyNamespaces._WCFPropertyNamespace, outboundHeaders);
            inmsg.Context.Write(BizTalkGlobalPropertySchemaEnum.IsDynamicSend.ToString(), ContextPropertyNamespaces._BTSPropertyNamespace, true);
        }
Example #10
0
        private static void writeMessage(Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, XmlDocument xmlDoc)
        {
            var outputStream = new VirtualStream();

            using (var writer = XmlWriter.Create(outputStream, new XmlWriterSettings()
            {
                CloseOutput = false,
                Encoding = Encoding.UTF8
            }))
            {
                xmlDoc.WriteTo(writer);
                writer.Flush();
            }

            outputStream.Seek(0, SeekOrigin.Begin);

            inmsg.BodyPart.Charset = Encoding.UTF8.WebName;
            inmsg.BodyPart.Data    = outputStream;
        }
        /// <summary>
        /// Determine whether the message being probed exists in our assembly
        /// </summary>
        /// <param name="messageType"></param>
        /// <returns></returns>
        //private bool CanHandleMessage(string messageType, string docSpecName)
        //{
        //    bool canHandle = false;

        //    //query the biztalk management database to see if the messageType is defined in our Assembly (actually our docSpecName)

        //    SqlDbHelper.

        //}

        /// <summary>
        /// Read the incoming message to determine the messageType
        /// </summary>
        /// <param name="inMsg">The Biztalk Message to read</param>
        /// <returns>The messageType (namespace+rootnodename)</returns>
        private string GetMessageType(Microsoft.BizTalk.Message.Interop.IBaseMessage inMsg, out string rootNodeName)
        {
            string messageType = string.Empty;

            //string messageType = (string)inMsg.Context.Read("MessageType", MessageContext.SystemPropertiesNamespace);
            //if (messageType != null)
            //{
            //    return messageType;
            //}
            //read the message body to determine rootnode and namespace
            //Wrap the originalStream in a seekable stream so that position can be rewound to 0 before returning

            var    originalStream = inMsg.BodyPart.GetOriginalDataStream();
            Stream seekableStream;

            if (!originalStream.CanSeek)
            {
                seekableStream      = new ReadOnlySeekableStream(originalStream);
                inMsg.BodyPart.Data = seekableStream;
            }
            else
            {
                seekableStream = originalStream;
            }

            //Stream that will be set to the xml extracted from the incoming message
            using (var copiedStream = new MemoryStream())
            {
                seekableStream.CopyTo(copiedStream);
                copiedStream.Position   = 0;
                seekableStream.Position = 0;

                XDocument xDoc = XDocument.Load(copiedStream);
                messageType  = string.Format("{0}#{1}", xDoc.Root.Name.NamespaceName, xDoc.Root.Name.LocalName);
                rootNodeName = xDoc.Root.Name.LocalName;
            }

            //_logger.DebugFormat("XmlSchemaResolver:: GetMessageType: Processing Message, determined message type {0}", messageType);

            return(messageType);
        }
Example #12
0
 Execute(IPipelineContext pContext,
         Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
 {
     try
     {
         if (pInMsg != null)
         {
             Stream originalStream = pInMsg.BodyPart.
                                     GetOriginalDataStream();
             pInMsg.BodyPart.Data = Decode(originalStream);
             pContext.ResourceTracker.AddResource(pInMsg.BodyPart.Data);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(
             @"Exception caught in GnuPGDecodeComponent::Execute: "
             + ex.Message);
     }
     return(pInMsg);
 }
Example #13
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)
        {
            #region Handle CORS Requests

            // Detect of the incoming message is an HTTP CORS request
            // http://www.w3.org/TR/cors/

            // If it is, we will promote both the RouteDirectToTP property and the
            // EpmRRCorrelationToken so that the request is immediately routed
            // back to the send pipeline of this receive port

            object httpMethod = null;
            httpMethod = inmsg.Context.Read(HTTP_METHOD_PROPNAME, WCF_PROPERTIES_NS);

            if (httpMethod != null && (httpMethod as string) == OPTIONS_METHOD)
            {
                object curCorrToken = inmsg.Context.Read(EPM_RR_CORRELATION_TOKEN_PROPNAME, SYSTEM_PROPERTIES_NS);
                inmsg.Context.Promote(EPM_RR_CORRELATION_TOKEN_PROPNAME, SYSTEM_PROPERTIES_NS, curCorrToken);
                inmsg.Context.Promote(ROUTE_DIRECT_TO_TP_PROPNAME, SYSTEM_PROPERTIES_NS, true);

                var corsDoc = new XmlDocument();
                corsDoc.AppendChild(corsDoc.CreateElement(DEFAULT_PREFIX, CORS_MSG_ROOT, JSON_SCHEMAS_NS));
                writeMessage(inmsg, corsDoc);

                return(inmsg);
            }

            #endregion


            #region Handle JSONP Request

            // Here we are detecting if there has been any value promoted to the jsonp callback property
            // which will contain the name of the function that should be passed the JSON data returned
            // by the service.

            object jsonpCallback     = inmsg.Context.Read(JSONP_CALLBACK_PROPNAME, JSON_SCHEMAS_NS);
            string jsonpCallbackName = (jsonpCallback ?? (object)string.Empty) as string;

            if (!string.IsNullOrWhiteSpace(jsonpCallbackName))
            {
                var jsonpDoc = new XmlDocument();
                jsonpDoc.AppendChild(jsonpDoc.CreateElement(DEFAULT_PREFIX, JSONP_MSG_ROOT, JSON_SCHEMAS_NS));
                writeMessage(inmsg, jsonpDoc);

                return(inmsg);
            }

            #endregion

            // Determine the current operation. We will use this as the root node
            // of the document if there isn't one specified as a property on the
            // component
            object operation = null;
            operation = inmsg.Context.Read(OPERATION_NAME_PROPNAME, SYSTEM_PROPERTIES_NS);
            string operationName = (operation ?? (object)string.Empty) as string;

            // Make message seekable
            if (!inmsg.BodyPart.Data.CanSeek)
            {
                var    originalStream = inmsg.BodyPart.Data;
                Stream seekableStream = new ReadOnlySeekableStream(originalStream);
                inmsg.BodyPart.Data = seekableStream;
                pc.ResourceTracker.AddResource(originalStream);
            }

            // We are going to do something terrible and bring the entire message in memory.
            // Then we are going to create a string out of it, because that's how the library
            // wants it.

            // Please don't use this code for production purposes with large messages.
            // You have been warned.

            MemoryStream jsonStream = new MemoryStream();
            inmsg.BodyPart.Data.CopyTo(jsonStream);
            inmsg.BodyPart.Data.Seek(0, SeekOrigin.Begin);

            // I am not going to assume any specific encoding. The BodyPart tells us
            // which encoding to use, so we will use that to get the string -- except
            // when it doesn't, then I will be a horrible person and assume an encoding.

            var jsonString = jsonStream.Length == 0
                                    ? string.Empty
                                    : Encoding.GetEncoding(inmsg.BodyPart.Charset ?? Encoding.UTF8.WebName).GetString(jsonStream.ToArray());

            var rawDoc = JsonConvert.DeserializeXmlNode(jsonString, string.IsNullOrWhiteSpace(this.RootNode) ? operationName : this.RootNode, true);

            // Here we are ensuring that the custom namespace shows up on the root node
            // so that we have a nice clean message type on the request messages
            var xmlDoc = new XmlDocument();
            xmlDoc.AppendChild(xmlDoc.CreateElement(DEFAULT_PREFIX, rawDoc.DocumentElement.LocalName, this.Namespace));
            xmlDoc.DocumentElement.InnerXml = rawDoc.DocumentElement.InnerXml;

            // All of the heavy lifting has been done, now we just have to shuffle this
            // new data over to the output message
            writeMessage(inmsg, xmlDoc);

            return(inmsg);
        }
        /// <summary>
        /// Examine the incoming message and determine which document spec name (specifically which strong name) to assign.
        /// </summary>
        /// <param name="pContext"></param>
        /// <param name="pInMsg"></param>
        /// <returns></returns>
        public bool Probe(IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
        {
            bool handled = false;

            //the messagetype is not unique, which is why the biztalk resolver fails. However, the docSpecName IS unique as it contains
            //the FQN, eg the docspecName for the SAM unLockBAResponse is ES.FS.WG.SAM.Schemas.SAMSchemas.SAMServiceSchemas.SamServiceService_servlet_x2esam_x2eedscs_x2eeds_x2ecom+unLockBAResponse
            //Whereas the docSpecName for the STAX unLockBAResponse is ES.FS.WG.STAX.Schemas.SAMSchemas.SamServiceService_servlet_x2esam_x2eedscs_x2eeds_x2ecom+unLockBAResponse.

            string rootNodeName = string.Empty;
            string messageType  = GetMessageType(pInMsg, out rootNodeName);

            //Is this a messageType we know how to handle
            //ie does the messageType exist in the schema assembly we are resolving to.

            //NOTE: If the schema contains only a single root node, the docSpecName does NOT include the rootNodeName
            string docSpecName = string.Empty;

            if (_multiElementSchema)
            {
                docSpecName = string.Format("{0}.{1}+{2}", DocSpecQN, DocSpecClassName, rootNodeName);
            }
            else
            {
                docSpecName = string.Format("{0}.{1}", DocSpecQN, DocSpecClassName);
            }

            string        docSpecStrongName = string.Format("{0}, {1}", docSpecName, AssemblyStrongName);
            IDocumentSpec docSpec           = null;

            try
            {
                //determine if this is a valid doc spec name by loading the doc spec (effectively queries the BT mgt database for us)
                //look up from Biztalk to ensure strongname is valid, if lookup fails an exception is thrown

                docSpec = pContext.GetDocumentSpecByName(docSpecStrongName);

                //first check the cache, if not in cache retrieve from Biztalk and place in cache
                //if it is in the cache, it is inherently a valid docSpecStrongName as it must have already been looked up from Biztalk
                //so no need to do anything further, just assign the strong name to the message

                //if (!StrongNameCache.ContainsKey(rootNodeName))
                //{
                //    //look up from Biztalk to ensure strongname is valid, if lookup fails an exception is thrown
                //    docSpec = pContext.GetDocumentSpecByName(docSpecStrongName);

                //    //if capacity reached, remove the first entry added to the cache.
                //    if (StrongNameCache.Count == CacheCapacity)
                //    {
                //        string keyToRemove = StrongNameCache.ElementAt(0).Key;
                //        StrongNameCache.Remove(keyToRemove);
                //    }

                //    StrongNameCache[rootNodeName] = docSpec.DocSpecStrongName;
                //}

                //make sure the incoming message matches the docSpec we found
                handled = (docSpec.DocType == messageType);
            }
            catch (Exception)
            {
                //consume the exception and return false (not handled by this component)
                //_logger.DebugFormat("XmlSchemaResolver:: Probe: Message not being handled {0}, DocSpecName {1}", messageType, docSpecStrongName);
            }

            if (handled)
            {
                pInMsg.Context.Write("DocumentSpecName", "http://schemas.microsoft.com/BizTalk/2003/xmlnorm-properties", docSpecStrongName);
            }
            else
            {
                handled = _xmlDissambler.Probe(pContext, pInMsg);
            }

            return(handled);
        }
 public void Disassemble(IPipelineContext pContext, Microsoft.BizTalk.Message.Interop.IBaseMessage pInMsg)
 {
     _xmlDissambler.Disassemble(pContext, pInMsg);
 }
Example #16
0
 public void Execute(ref Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, Microsoft.BizTalk.Component.Interop.IPipelineContext pc)
 {
     inmsg = PipelineExecutionHelper.Execute(component, inmsg, pc);
 }
Example #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 dataStream = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk);

            pc.ResourceTracker.AddResource(dataStream);

            using (XmlWriter writer = XmlWriter.Create(dataStream))
            {
                // Start creating the message body
                writer.WriteStartDocument();
                writer.WriteStartElement("ns0", ROOT_NODE_NAME, TARGET_NAMESPACE);

                for (int i = 0; i < inmsg.Context.CountProperties; i++)
                {
                    // Read in current property information
                    string propName      = null;
                    string propNamespace = null;
                    object propValue     = inmsg.Context.ReadAt(i, out propName, out propNamespace);

                    // Skip properties that we don't care about due to configuration (default is to allow all properties)
                    if (ExcludeSystemProperties && propNamespace == SYSTEM_NAMESPACE)
                    {
                        continue;
                    }

                    if (!String.IsNullOrWhiteSpace(CustomPropertyNamespace) &&
                        propNamespace != CustomPropertyNamespace)
                    {
                        continue;
                    }

                    // Create Property element
                    writer.WriteStartElement(PROPERTY_NODE_NAME);

                    // Create attributes on Property element
                    writer.WriteStartAttribute(NAMESPACE_ATTRIBUTE);
                    writer.WriteString(propNamespace);
                    writer.WriteEndAttribute();

                    writer.WriteStartAttribute(NAME_ATTRIBUTE);
                    writer.WriteString(propName);
                    writer.WriteEndAttribute();

                    // Write value inside property element
                    writer.WriteString(Convert.ToString(propValue));

                    writer.WriteEndElement();
                }

                // Finish out the message
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
            }

            dataStream.Seek(0, SeekOrigin.Begin);

            var outmsg = Utility.CloneMessage(inmsg, pc);

            outmsg.BodyPart.Data = dataStream;

            return(outmsg);
        }
Example #18
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)
        {
            var readyWarehouseId = RushOrderHelper.WarehouseFinder.GetNextReadyWarehouse();

            inmsg.Context.Promote(WAREHOUSE_ID_PROPERTY_NAME,
                                  WAREHOUSE_ID_PROPERTY_NAMESPACE,
                                  readyWarehouseId);

            return(inmsg);
        }
Example #19
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)
        {
            #region Handle CORS Requests

            // Detect of the incoming message is an HTTP CORS request
            // http://www.w3.org/TR/cors/

            object httpMethod = null;
            httpMethod = inmsg.Context.Read(HTTP_METHOD_PROPNAME, WCF_PROPERTIES_NS);

            if (httpMethod != null && (httpMethod as string) == OPTIONS_METHOD)
            {
                // Remove the message body before returning
                var emptyOutputStream = new VirtualStream();
                inmsg.BodyPart.Data = emptyOutputStream;

                return(inmsg);
            }

            #endregion


            // Make message seekable
            if (!inmsg.BodyPart.Data.CanSeek)
            {
                var    originalStream = inmsg.BodyPart.Data;
                Stream seekableStream = new ReadOnlySeekableStream(originalStream);
                inmsg.BodyPart.Data = seekableStream;
                pc.ResourceTracker.AddResource(originalStream);
            }

            // Here again we are loading the entire document into memory
            // this is still a bad plan, and shouldn't be done in production
            // if you expect larger message sizes

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(inmsg.BodyPart.Data);

            if (xmlDoc.FirstChild.LocalName == "xml")
            {
                xmlDoc.RemoveChild(xmlDoc.FirstChild);
            }

            // Remove any root-level attributes added in the process of creating the XML
            // (Think xmlns attributes that have no meaning in JSON)

            xmlDoc.DocumentElement.Attributes.RemoveAll();

            string jsonString = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.Indented, true);

            #region Handle JSONP Request

            // Here we are detecting if there has been any value promoted to the jsonp callback property
            // which will contain the name of the function that should be passed the JSON data returned
            // by the service.

            object jsonpCallback     = inmsg.Context.Read(JSONP_CALLBACK_PROPNAME, JSON_SCHEMAS_NS);
            string jsonpCallbackName = (jsonpCallback ?? (object)string.Empty) as string;

            if (!string.IsNullOrWhiteSpace(jsonpCallbackName))
            {
                jsonString = string.Format("{0}({1});", jsonpCallbackName, jsonString);
            }

            #endregion

            var outputStream = new VirtualStream(new MemoryStream(Encoding.UTF8.GetBytes(jsonString)));
            inmsg.BodyPart.Data = outputStream;

            return(inmsg);
        }
        /// <summary>
        /// Saves out a message to a file, using tracked filename and timestamp where possible.
        /// </summary>
        /// <param name="messageIdentifier">Message guid</param>
        public void ExtractMessage(string messageIdentifier)
        {
            bool retry = false;

            messageIdentifier = messageIdentifier.Trim();

            Guid messageId = new Guid(messageIdentifier);

            Console.Write("Processing {0}. ", messageIdentifier);

            do
            {
                try
                {
                    retry = false;

                    Microsoft.BizTalk.Message.Interop.IBaseMessage msg = _btsOps.GetTrackedMessage(messageId, _trackingDatabase);

                    // Build an output filename
                    string saveFileName      = msg.MessageID.ToString();
                    string saveFileExtension = ".txt";
                    string receivedFileName  = (string)msg.Context.Read(_settings.FilenameProperty, _settings.FilenameSchema);

                    // If we've obtained a filename from the context
                    if (receivedFileName != null)
                    {
                        saveFileName      = Path.GetFileNameWithoutExtension(receivedFileName);
                        saveFileExtension = Path.GetExtension(receivedFileName);
                    }

                    // Loop each message part
                    for (int i = 0; i < msg.PartCount; i++)
                    {
                        string partName;
                        Microsoft.BizTalk.Message.Interop.IBaseMessagePart part = msg.GetPartByIndex(i, out partName);

                        if (part != null && part.Data != null)
                        {
                            // Attempt to construct a file name based on part data
                            string fileName          = String.Empty;
                            string partFileName      = part.PartProperties.Read("FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties") as String;
                            string partFileExtension = saveFileExtension;

                            // Use the partName if there is no mime name
                            if (partFileName == null)
                            {
                                partFileName = partName;
                            }
                            else
                            // Use the extension from the filename for this part
                            {
                                partFileExtension = Path.GetExtension(partFileName);
                                partFileName      = Path.GetFileNameWithoutExtension(partFileName);
                            }

                            // Handle duplicate files names with an incrementing counter
                            int fileNameDuplicate = -1;
                            do
                            {
                                fileName = CleanFilename(String.Format("{0}_{1}{3}{2}", saveFileName, partFileName, partFileExtension, fileNameDuplicate++ >= 0 ? fileNameDuplicate.ToString() : String.Empty));
                            } while (File.Exists(fileName));

                            Console.WriteLine("Saving message to {0}", fileName);

                            using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
                            {
                                byte[] buffer = new byte[1024];
                                int    length = 0;
                                while ((length = part.Data.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    fs.Write(buffer, 0, length);
                                }

                                fs.Flush();
                            }

                            DateTime createdTime = DateTime.Now;

                            // Try to get the file created time
                            object prop = msg.Context.Read("FileCreationTime", "http://schemas.microsoft.com/BizTalk/2003/file-properties");

                            if (prop == null)
                            {
                                // If there was no file created time (e.g. it was a SOAP message), get the adapter finished time
                                prop = msg.Context.Read("AdapterReceiveCompleteTime", "http://schemas.microsoft.com/BizTalk/2003/messagetracking-properties");
                            }

                            if (prop != null)
                            {
                                createdTime = (DateTime)prop;
                            }

                            File.SetLastWriteTime(fileName, createdTime);
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteError(ex);

                    do
                    {
                        string prompt = PromptFor <string>("Would you like to retry this message? [Y/N]");
                        switch (prompt.ToUpper().Trim())
                        {
                        case "N":
                            return;

                        case "Y":
                            retry = true;
                            break;

                        default:
                            WriteColourfulLine(CON_COLOUR_WARN, "Invalid answer, Y or N please.");
                            break;
                        }
                    } while (!retry);                           // impossible for a false retry as we'll return on a N
                }
            } while (retry);
        }
Example #21
0
        public void Execute(ref Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, Microsoft.BizTalk.Component.Interop.IPipelineContext pc)
        {
            dynamic        transformMetaData;
            SchemaMetadata sourceSchemaMetadata;
            string         schemaName;
            SchemaMetadata targetSchemaMetadata;

            try
            {
                transformMetaData    = TransformMetaData.For(mapType);
                sourceSchemaMetadata = transformMetaData.SourceSchemas[0];
                schemaName           = sourceSchemaMetadata.SchemaName;
                targetSchemaMetadata = transformMetaData.TargetSchemas[0];
            }
            catch (Exception e)
            {
                throw new Exception(String.Format("Exception encountered while trying to instantiate map {0}, exception details - {1}", mapName, e.Message));
            }

            if (validateSourceSchema == TransformationSourceSchemaValidation.ValidateSourceSchema || validateSourceSchema == TransformationSourceSchemaValidation.ValidateSourceSchemaIfKnown)
            {
                object property = inmsg.Context.Read(BizTalkGlobalPropertySchemaEnum.MessageType.ToString(), ContextPropertyNamespaces._BTSPropertyNamespace);

                if (property == null)
                {
                    if (validateSourceSchema == TransformationSourceSchemaValidation.ValidateSourceSchema)
                    {
                        throw new Exception("Unable to read source messageType while performing transformation against map " + mapName);
                    }
                }
                else
                {
                    string messageType = property.ToString();

                    if (!string.IsNullOrEmpty(messageType))
                    {
                        if (string.Compare(messageType, schemaName, false, CultureInfo.CurrentCulture) != 0)
                        {
                            throw new Exception(String.Format("Transformation mismatch exception for map {0}, was expecting source schema to be {1} but was actually {2}.", mapName, schemaName, messageType));
                        }
                    }
                }
            }

            try
            {
                dynamic transform = transformMetaData.Transform2;
                Stream  output    = new VirtualStream();

                TraceManager.PipelineComponent.TraceInfo("{0} - Applying transformation {1} to the message", callToken, mapName);
                TraceManager.PipelineComponent.TraceInfo("{0} - Message is being transformed from message type {1} to message type {2}", callToken, schemaName, targetSchemaMetadata.SchemaName);

                //TODO figure out what is suppose to go in this null object instead of null.
                transform.Transform(inmsg.BodyPart.GetOriginalDataStream(), null, output);
                output.Position = 0;
                pc.ResourceTracker.AddResource(output);

                inmsg.BodyPart.Data = output;
                inmsg.Context.Write(BizTalkGlobalPropertySchemaEnum.SchemaStrongName.ToString(), ContextPropertyNamespaces._BTSPropertyNamespace, null);
                inmsg.Context.Promote(BizTalkGlobalPropertySchemaEnum.MessageType.ToString(), ContextPropertyNamespaces._BTSPropertyNamespace, targetSchemaMetadata.SchemaName);
            }
            catch (Exception e)
            {
                throw new Exception("Exception encountered while trying to execute map - " + e.Message);
            }
        }
Example #22
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)
        {
            string                 ActivityID    = Guid.NewGuid().ToString();
            string                 ShareLocation = "D:\\Share\\TrackingArchive\\"; // Should be an UNC Path with desired access granted to the User Account
            string                 FileExtension = ".txt";
            string                 FullFilePath  = ShareLocation + ActivityID + FileExtension;
            StringBuilder          SBContext     = new StringBuilder();
            ReadOnlySeekableStream stream        = new ReadOnlySeekableStream(inmsg.BodyPart.GetOriginalDataStream());
            Stream                 sourceStream  = inmsg.BodyPart.GetOriginalDataStream();

            if (!sourceStream.CanSeek)
            {
                ReadOnlySeekableStream seekableStream = new ReadOnlySeekableStream(sourceStream);

                inmsg.BodyPart.Data = seekableStream;

                sourceStream = inmsg.BodyPart.Data;
            }

            if (inmsg.BodyPart != null)
            {
                VirtualStream virtualStream = new VirtualStream(sourceStream);

                PipelineHelper.ArchiveToFileLocation(virtualStream, FullFilePath);
                PipelineHelper.ArchivetoStorage(pc, inmsg, FullFilePath, true);

                sourceStream.Position        = 0;
                inmsg.BodyPart.Data          = sourceStream;
                inmsg.BodyPart.Data.Position = 0;
            }

            return(inmsg);

            #endregion
        }