/// <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)
        {
            /*************************************************************************************************************************
             * 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);
        }
Пример #2
0
        private string ProcessFTPPropertiesMacros(string Target, Microsoft.BizTalk.Message.Interop.IBaseMessage Message)
        {
            try
            {
                string UpdatedTarget    = "";
                string ReceivedFileName = "";
                string FileName         = "";
                string FileExtension    = "";

                ReceivedFileName = Message.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/ftp-properties") as string;

                int Index = 0;
                //int Index2 = 0;
                int FileNameLength = 0;

                Index         = ReceivedFileName.LastIndexOf(".");
                FileExtension = ReceivedFileName.Substring(Index);

                FileNameLength = ReceivedFileName.Length - FileExtension.Length;
                FileName       = ReceivedFileName.Substring(0, FileNameLength);

                UpdatedTarget = Target.Replace("%FTPReceivedFileName%", FileName);
                UpdatedTarget = UpdatedTarget.Replace("%FTPReceivedFileExtension%", FileExtension);

                return(UpdatedTarget);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #3
0
 /// <summary>
 /// called by the messaging engine when a new message arrives
 /// checks if the incoming message is in a recognizable format
 /// if the message is in a recognizable format, only this component
 /// within this stage will be execute (FirstMatch equals true)
 /// </summary>
 /// <param name="pc">the pipeline context</param>
 /// <param name="inmsg">the actual message</param>
 public bool Probe(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
 {
     //
     // TODO: check whether you're interested in the given message
     //
     return(true);
 }
Пример #4
0
 /// <summary>
 /// called by the messaging engine until returned null, after disassemble has been called
 /// </summary>
 /// <param name="pc">the pipeline context</param>
 /// <returns>an IBaseMessage instance representing the message created</returns>
 public Microsoft.BizTalk.Message.Interop.IBaseMessage GetNext(Microsoft.BizTalk.Component.Interop.IPipelineContext pc)
 {
     // get the next message from the Queue and return it
     Microsoft.BizTalk.Message.Interop.IBaseMessage msg = null;
     if ((_msgs.Count > 0))
     {
         msg = ((Microsoft.BizTalk.Message.Interop.IBaseMessage)(_msgs.Dequeue()));
     }
     return(msg);
 }
Пример #5
0
        /// <summary>
        /// Set the message back to the original message, ensure it's body part is seekable, set the position back to 0, and apply RIP context properties
        /// </summary>
        private void HandleRIPException(Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, Exception e)
        {
            TraceManager.PipelineComponent.TraceInfo("{0} - Handling error in a recoverable interchange processing fashion", callToken);

            _BREPipelineMetaInstructionCollection.InMsg = inmsg;
            _BREPipelineMetaInstructionCollection.InMsg.BodyPart.Data = originalStream;
            _BREPipelineMetaInstructionCollection.InMsg.BodyPart.Data.Position = 0;           
            _BREPipelineMetaInstructionCollection.InMsg.SetErrorInfo(e);
            _BREPipelineMetaInstructionCollection.InMsg.Context.Write(BizTalkGlobalPropertySchemaEnum.MessageDestination.ToString(), ContextPropertyNamespaces._BTSPropertyNamespace,
                "SuspendQueue");
        }
Пример #6
0
        private string ProcessMessageMacros(string Target, Microsoft.BizTalk.Message.Interop.IBaseMessage Message)
        {
            try
            {
                string UpdatedTarget = "";

                UpdatedTarget = Target.Replace("%BodyPartName%", Message.BodyPartName.ToString());
                UpdatedTarget = UpdatedTarget.Replace("%MessageID%", Message.MessageID.ToString());
                UpdatedTarget = UpdatedTarget.Replace("%PartCount%", Message.PartCount.ToString());

                return(UpdatedTarget);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        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>
        /// 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)
        {
            XmlDocument message = new XmlDocument();

            message.Load(inmsg.BodyPart.Data);

            string targetNS = this._TargetNamespace.Trim();

            message.DocumentElement.SetAttribute("xmlns", targetNS);

            MemoryStream outStream = new MemoryStream();

            message.Save(outStream);

            outStream.Position  = 0;
            inmsg.BodyPart.Data = outStream;

            return(inmsg);
        }
Пример #9
0
        private string ProcessDateTimeMacros(string Target, Microsoft.BizTalk.Message.Interop.IBaseMessage Message)
        {
            try
            {
                string UpdatedTarget = "";
                string Time          = "";

                UpdatedTarget = Target.Replace("%Date%", DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString());
                UpdatedTarget = UpdatedTarget.Replace("%Day%", DateTime.Now.Day.ToString());
                UpdatedTarget = UpdatedTarget.Replace("%Month%", DateTime.Now.Month.ToString());

                Time = DateTime.Now.TimeOfDay.ToString().Replace(":", ".");

                UpdatedTarget = UpdatedTarget.Replace("%Time%", Time);
                UpdatedTarget = UpdatedTarget.Replace("%Year%", DateTime.Now.Year.ToString());

                return(UpdatedTarget);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <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)
        {
            /*************************************************************************************************************************
             * This component will read the Custom SOAPHeader from the Message Context Properties.                                   *
             *     The custom header name will be defined on the component configuration and we can read it from the targert         *
             *           http://schemas.microsoft.com/BizTalk/2003/SOAPHeader                                                        *
             *     and will add the header in the OutboundCustomHeaders (used by the WCF-BasicHTTP Adapter)                          *
             *           Specify the custom SOAP headers for outgoing messages. When this property is used, the property must have   *
             *           the <headers> element as the root element. All of the custom SOAP headers must be placed inside the         *
             *           <headers> element.                                                                                          *
             *           If the custom SOAP header value is an empty string, you must assign <headers></headers> or <headers> to this*
             *           property.                                                                                                   *
             *                                                                                                                       *
             * Ex: BusinessServiceHeader with "http://schemas.microsoft.com/BizTalk/2003/SOAPHeader" namespace                       *
             ************************************************************************************************************************/

            if (!string.IsNullOrEmpty(this.SOAPHeaderName))
            {
                string soapHeader = Convert.ToString(inmsg.Context.Read(this.SOAPHeaderName,
                                                                        "http://schemas.microsoft.com/BizTalk/2003/SOAPHeader"));

                if (!string.IsNullOrEmpty(soapHeader))
                {
                    XDocument xdoc = XDocument.Parse(soapHeader);
                    xdoc.Declaration = null;
                    Console.WriteLine(xdoc.ToString().Replace(System.Environment.NewLine, ""));

                    string outboundHeader = "<headers>" + xdoc.ToString().Replace(System.Environment.NewLine, "") + "</headers>";

                    inmsg.Context.Promote("IsDynamicSend", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true);
                    inmsg.Context.Write("OutboundCustomHeaders", "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties", outboundHeader);
                }
            }

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

            // If the message body part is null then instantiate it again so we can assign the typed xml document stream to it
            if (_BREPipelineMetaInstructionCollection.InMsg.BodyPart == null)
            {
                TraceManager.PipelineComponent.TraceInfo("{0} - Instantiating the message body part since it was null and the pipeline component needs to assign the TypedXMLDocument to it.", callToken);
                IBaseMessagePart messageBodyPart = pc.GetMessageFactory().CreateMessagePart();
                _BREPipelineMetaInstructionCollection.InMsg.AddPart("Body", messageBodyPart, true);
            }
        }
Пример #12
0
        //Get the list of stream types that require reading before the pipeline executes from the pipeline parameters and read a character from the stream
        //to ensure that the stream reading logic gets exercised (especially important if the stream in question writes to the message context such as in 
        //the case of the Microsoft.BizTalk.Component.XmlDasmStreamWrapper)
        private void ReadStreamIfNecessary(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, IBaseMessagePart copiedBodyPart, string streamType)
        {
            if (!string.IsNullOrEmpty(streamsToReadBeforeExecution))
            {
                streamsToReadBeforeExecution.Replace(" ", "");
                List<string> streamsToReadBeforeExecutionList = new List<string>(streamsToReadBeforeExecution.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));

                if (streamsToReadBeforeExecutionList.Contains(streamType))
                {
                    TraceManager.PipelineComponent.TraceInfo("{0} - Reading stream to ensure it's read logic get's executed prior to pipeline component execution", callToken);
                    StreamReader reader = new StreamReader(copiedBodyPart.Data);
                    reader.Read();
                    pc.ResourceTracker.AddResource(reader);
                    copiedBodyPart.Data.Position = 0;
                }
                else
                {
                    TraceManager.PipelineComponent.TraceInfo("{0} - No need to read stream as stream type does not match entries in StreamsToReadBeforeExecution parameter", callToken);
                }
            }
            else
            {
                TraceManager.PipelineComponent.TraceInfo("{0} - No need to read stream as there are no entries in StreamsToReadBeforeExecution parameter", callToken);
            }
        }
Пример #13
0
        /// <summary>
        /// Setup the BREPipelineMetaInstructionCollection by copying over the body and context from the input message
        /// </summary>
        private void SetupBREPipelineMetaInstructionCollection(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            _BREPipelineMetaInstructionCollection = new BREPipelineMetaInstructionCollection(_XMLFactsApplicationStage, instructionExecutionOrder, partNames, callToken);
            _BREPipelineMetaInstructionCollection.Pc = pc;

            // Create a copy of the original body part and copy over it's properties as well
            IBaseMessagePart copiedBodyPart = pc.GetMessageFactory().CreateMessagePart();

            string streamType = inmsg.BodyPart.Data.GetType().ToString();
            TraceManager.PipelineComponent.TraceInfo("{0} - Inbound message body had a stream type of {1}", callToken, streamType);

            // If the input stream is not seekable then wrap it with a ReadOnlySeekableStream so that it can have it's position set
            if (!inmsg.BodyPart.GetOriginalDataStream().CanSeek)
            {
                TraceManager.PipelineComponent.TraceInfo("{0} - Inbound message body stream was not seekable so wrapping it with a ReadOnlySeekableStream", callToken);

                ReadOnlySeekableStream seekableDataStream = new ReadOnlySeekableStream(inmsg.BodyPart.GetOriginalDataStream());
                originalStream = seekableDataStream;
                pc.ResourceTracker.AddResource(seekableDataStream);
            }
            else
            {
                TraceManager.PipelineComponent.TraceInfo("{0} - Inbound message body stream was seekable so no need to wrap it", callToken);

                originalStream = inmsg.BodyPart.GetOriginalDataStream();
            }

            //Explicitly set the stream position to 0 in case the position was shifted while referencing it
            originalStream.Position = 0;

            pc.ResourceTracker.AddResource(originalStream);
            copiedBodyPart.Data = originalStream;
            ReadStreamIfNecessary(pc, inmsg, copiedBodyPart, streamType);

            //Copy over part properties
            copiedBodyPart.PartProperties = inmsg.BodyPart.PartProperties;

            // Create a new message in the _BREPipelineMetaInstructionCollection and copy over the body and any additional parts
            _BREPipelineMetaInstructionCollection.InMsg = pc.GetMessageFactory().CreateMessage();
            CopyMessageParts(inmsg, _BREPipelineMetaInstructionCollection.InMsg, copiedBodyPart);

            // Copy over context by reference, this is to ensure that context isn't lost if using an XML Disassembler prior to BRE component
            // and not reading the stream prior to cloning context
            _BREPipelineMetaInstructionCollection.InMsg.Context = inmsg.Context;
        }
Пример #14
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)
        {
            long ticks = TraceIn();

            if (_Enabled)
            {
                // Setup the BREPipelineMetaInstructionCollection by copying over the body and context from the input message
                SetupBREPipelineMetaInstructionCollection(pc, inmsg);

                // Instantiate a TypedXMLDocumentWrapper class pointing to the body part's stream, a SQLDataConnectionCollection, and a MessageUtility object, passing in the 
                // body part's stream, and if available the message type context property value as well
                InstantiateInstructionLoaderPolicyFacts(pc);

                // Set ApplicationContext to String.Empty if it has a null value since that would cause the rules engine to crash
                if (applicationContext == null)
                {
                    applicationContext = string.Empty;
                }

                try
                {
                    // Execute the InstructionLoaderPolicy
                    if (!string.IsNullOrEmpty(instructionLoaderPolicy))
                    {
                        object[] instructionLoaderFacts = { applicationContext, _BREPipelineMetaInstructionCollection, documentWrapper, sqlConnectionCollection, utility };
                        ExecutePolicy(instructionLoaderPolicy, instructionLoaderFacts, instructionLoaderPolicyVersion);
                    }

                    // If the InstructionLoaderPolicy returned a handled error then throw that now
                    if (_BREPipelineMetaInstructionCollection.BREException != null)
                    {
                        throw _BREPipelineMetaInstructionCollection.BREException;
                    }

                    // Override the default ExecutionPolicy name and version, ApplicationContext, and XMLFactsApplicationStage if an override instruction was set by the InstructionLoaderPolicy
                    ApplyOverrides();

                    // Add out of the box MetaInstructions and custom MetaInstructions set on the pipeline component parameters
                    // to the collection so they can be used in any ExecutionPolicy
                    AddOutOfTheBoxMetaInstructions();
                    AddMetaInstructionsFromPipelineComponentParameters();

                    // Execute the ExecutionPolicy using the instantiated MetaInstructions as facts and passing in the TypedXMLDocument from within the wrapper if properly setup
                    // as well as any DataConnections that were setup in the InstructionLoaderPolicy
                    if (!string.IsNullOrEmpty(executionPolicy))
                    {
                        object[] pipelineMetaInstructionFacts = SetupExecutionPolicyFacts();

                        // Execute the Execution policy in question, utilizing the DebugTrackingInspector if a TrackingFolder has been specified
                        ExecutePolicy(executionPolicy, pipelineMetaInstructionFacts, executionPolicyVersion);

                        // If any of the MetaInstructions have returned exceptions then throw them now.
                        _BREPipelineMetaInstructionCollection.ThrowExceptions();

                        try
                        {
                            // If a TypedXMLDocument had been setup and xmlFactsApplicationStage is set to BeforeInstructionExecution then fetch 
                            // the potentially updated body from the asserted fact and replace the message body stream with this
                            if (_XMLFactsApplicationStage == XMLFactsApplicationStageEnum.BeforeInstructionExecution && documentWrapper.DocumentCount == 1)
                            {
                                TypedXMLDocumentWrapper.ApplyTypedXMLDocument((TypedXmlDocument)pipelineMetaInstructionFacts[2], _BREPipelineMetaInstructionCollection.InMsg, pc, callToken);
                            }

                            // Execute all the instructions that have been loaded into the MetaInstructions by the ExecutionPolicy
                            _BREPipelineMetaInstructionCollection.Execute();

                            // If a TypedXMLDocument had been setup and xmlFactsApplicationStage is set to AfterInstructionExecution then fetch 
                            // the potentially updated body from the asserted fact and replace the message body stream with this.  First check to see if the 
                            // message and/or body part are null and if so create them with context copied from the original message
                            if (_XMLFactsApplicationStage == XMLFactsApplicationStageEnum.AfterInstructionExecution && documentWrapper.DocumentCount == 1)
                            {
                                RecreateBizTalkMessageAndBodyPartIfNecessary(pc, inmsg);
                                TypedXMLDocumentWrapper.ApplyTypedXMLDocument((TypedXmlDocument)pipelineMetaInstructionFacts[2], _BREPipelineMetaInstructionCollection.InMsg, pc, callToken);
                            }
                        }
                        catch (Exception)
                        {
                            // Call compensation methods on all MetaInstructions before throwing the error
                            _BREPipelineMetaInstructionCollection.Compensate();
                            throw;
                        }
                    }
                }
                catch (Exception e)
                {
                    TraceManager.PipelineComponent.TraceError(e, true, Guid.Parse(callToken));
                    
                    // Handle any exception in a recoverable fashion if RIP has been setup, otherwise throw the exception
                    if (recoverableInterchangeProcessingEnabled)
                    {
                        HandleRIPException(inmsg, e);
                    }
                    else
                    {
                        _BREPipelineMetaInstructionCollection.InMsg.BodyPart.Data.Position = 0;

                        TraceManager.PipelineComponent.TraceEndScope(callToken, ticks);
                        TraceManager.PipelineComponent.TraceOut(callToken);
                        throw;
                    }
                }
                finally
                {
                    //Close all SQLConnections in the collection
                    if (sqlConnectionCollection.SQLConnectionCount > 0)
                    {
                        sqlConnectionCollection.CloseSQLConnections();
                    }
                }

                // If RIP has been setup then apply the appropriate context properties to ensure that routing failures are handled in a recoverable fashion
                if (recoverableInterchangeProcessingEnabled)
                {
                    _BREPipelineMetaInstructionCollection.InMsg.Context.Write(BizTalkGlobalPropertySchemaEnum.SuspendMessageOnRoutingFailure.ToString(), ContextPropertyNamespaces._BTSPropertyNamespace,
                            true);
                }

                TraceManager.PipelineComponent.TraceEndScope(callToken, ticks);
                TraceManager.PipelineComponent.TraceOut(callToken);

                // Return the updated message
                return _BREPipelineMetaInstructionCollection.InMsg;
            }

            TraceManager.PipelineComponent.TraceEndScope(callToken, ticks);
            TraceManager.PipelineComponent.TraceInfo("{0} - BRE Pipeline Framework pipeline component was disabled so acting like a pass through pipeline component.",callToken);
            TraceManager.PipelineComponent.TraceOut(callToken);

            // Return the original message, treating this pipeline component as if it were a pass through pipeline component if the Enabled property is set to false
            return inmsg;
        }
        /// <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)
        {
            System.IO.Stream       st     = inmsg.BodyPart.GetOriginalDataStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(st);
            string body = reader.ReadToEnd();

            body = body.Replace(_FindString, _ReplaceWith);

            System.IO.MemoryStream m      = new System.IO.MemoryStream();
            System.IO.StreamWriter writer = new System.IO.StreamWriter(m);
            writer.AutoFlush = true;
            writer.Write(body);
            m.Position          = 0;
            inmsg.BodyPart.Data = m;

            reader.Close();
            return(inmsg);
        }
        /// <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 ExecuteFive(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     = null; // 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);
        }
Пример #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)
        {
            //
            // TODO: implement component logic
            //
            // this way, it's a passthrough pipeline component
            IBaseMessageContext context = inmsg.Context;
            Stream            inStream  = inmsg.BodyPart.Data;
            XslTransmitHelper transmit  = new XslTransmitHelper(this.XslPath, this.XPathSourceFileName, this.EnableValidateNamespace, this.AllowPassThruTransmit);

            if (!string.IsNullOrEmpty(this.XPathSourceFileName))
            {
                string sourceFileName = transmit.GetSourceFileName(XmlReader.Create(inStream), this.XPathSourceFileName);
                if (!string.IsNullOrEmpty(sourceFileName))
                {
                    context.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourceFileName);
                    context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourceFileName);
                }
                inStream.Seek(0, SeekOrigin.Begin);
            }
            var outStream = transmit.Transmit(inStream);

            inmsg.BodyPart.Data = outStream;
            pc.ResourceTracker.AddResource(outStream);



            return(inmsg);
        }
        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);
        }
Пример #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)
        {
            var stream = GetSeekeableMessageStream(inmsg);

            EdifactCharacterSet targetCharSet;

            var syntax = inmsg.Context.Read("UNB1_1", "http://schemas.microsoft.com/BizTalk/2006/edi-properties") as string;

            if (syntax == null || Enum.TryParse <EdifactCharacterSet>(syntax, out targetCharSet) == false)
            {
                targetCharSet = _targetCharSet;
            }

            var result = new MemoryStream();

            var settings = new XmlWriterSettings {
                Encoding = Encoding.UTF8, OmitXmlDeclaration = true
            };

            var separators = _extraCharsToReplace.ToCharArray();

            using (var reader = XmlReader.Create(stream))
                using (var writer = XmlWriter.Create(result, settings))
                {
                    while (reader.Read())
                    {
                        switch (reader.NodeType)
                        {
                        case XmlNodeType.Element:
                            writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
                            writer.WriteAttributes(reader, true);

                            if (reader.IsEmptyElement)
                            {
                                writer.WriteEndElement();
                            }
                            break;

                        case XmlNodeType.Text:
                            var value = reader.Value;

                            var sb = new StringBuilder();
                            foreach (var c in value)
                            {
                                var step1 = c.Translate(targetCharSet, _fallbackChar);
                                var step2 = separators.Contains(step1) ? _fallbackChar : step1;
                                var step3 = this.Normalize && char.IsControl(step2) ? ' ' : step2;
                                sb.Append(step3);
                            }
                            writer.WriteString(this.Normalize ? sb.ToString().Trim() : sb.ToString());
                            break;

                        case XmlNodeType.EndElement:
                            writer.WriteFullEndElement();
                            break;

                        case XmlNodeType.XmlDeclaration:
                        case XmlNodeType.ProcessingInstruction:
                            //writer.WriteProcessingInstruction(reader.Name, reader.Value);
                            break;

                        case XmlNodeType.SignificantWhitespace:
                            writer.WriteWhitespace(reader.Value);
                            break;
                        }
                    }
                    writer.Flush();
                }

            result.Seek(0, SeekOrigin.Begin);

            inmsg.BodyPart.Data = result;

            pc.ResourceTracker.AddResource(result);


            return(inmsg);
        }
Пример #20
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)
        {
            try
            {
                if (inmsg.BodyPart != null) //Verify the message is different from null
                {
                    MemoryStream memStrm = new MemoryStream();

                    Stream       originalStrm = inmsg.BodyPart.GetOriginalDataStream();
                    StreamReader sReader      = new StreamReader(originalStrm, System.Text.Encoding.Default);

                    string       original = sReader.ReadToEnd();
                    StreamWriter swriter  = new StreamWriter(memStrm, System.Text.Encoding.Default); //Modify message
                    if (string.IsNullOrEmpty(original))
                    {
                        swriter.Write(AppendedValue);
                        swriter.Flush();
                        memStrm.Seek(0, System.IO.SeekOrigin.Begin);

                        inmsg.BodyPart.Data = memStrm;
                        pc.ResourceTracker.AddResource(memStrm);
                    }
                    else
                    {
                        swriter.Write(original);
                        swriter.Flush();
                        memStrm.Seek(0, System.IO.SeekOrigin.Begin);

                        inmsg.BodyPart.Data = memStrm;
                        pc.ResourceTracker.AddResource(memStrm);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("IKT-Agder.Felles.PipelineComponents",
                                                       "Occurred an error on validating the message: " + ex.Message + "\n" + ex.StackTrace,
                                                       System.Diagnostics.EventLogEntryType.Error);
                throw (ex);
            }
            return(inmsg);
        }
        /// <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);
        }
Пример #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)
        {
            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);
        }
Пример #23
0
        public static void ArchivetoStorage(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, string FullFilePath, bool ReadFullContext)
        {
            StringBuilder          SBContext = new StringBuilder();
            ReadOnlySeekableStream stream    = new ReadOnlySeekableStream(inmsg.BodyPart.GetOriginalDataStream());
            Stream sourceStream = inmsg.BodyPart.GetOriginalDataStream();
            List <JsonContextProperty> jsonContextpropertylist = new List <JsonContextProperty>();

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

                inmsg.BodyPart.Data = seekableStream;

                sourceStream = inmsg.BodyPart.Data;
            }

            if (inmsg.BodyPart != null)
            {
                string        json          = "NA";
                VirtualStream virtualStream = new VirtualStream(sourceStream);
                //ArchiveToFileLocation(virtualStream, FullFilePath);
                //virtualStream.Seek(0, SeekOrigin.Begin);
                inmsg.BodyPart.Data = virtualStream;


                if (ReadFullContext == true)
                {
                    IBaseMessageContext ctx = inmsg.Context;
                    string name;
                    string nspace;

                    for (int loop = 0; loop < ctx.CountProperties; loop++)
                    {
                        ctx.ReadAt(loop, out name, out nspace);
                        string value = ctx.Read(name, nspace).ToString();
                        jsonContextpropertylist.Add(new JsonContextProperty()
                        {
                            Name      = name,
                            NameSpace = nspace,
                            Value     = value
                        });
                    }
                    json = JsonConvert.SerializeObject(jsonContextpropertylist);
                }
                string InterchangeID = inmsg.Context.Read("InterchangeID", "http://schemas.microsoft.com/BizTalk/2003/system-properties").ToString();
                string ServiceName   = "NA";
                if (inmsg.Context.Read("ReceivePortID", "http://schemas.microsoft.com/BizTalk/2003/system-properties") != null)
                {
                    ServiceName = inmsg.Context.Read("ReceiveLocationName", "http://schemas.microsoft.com/BizTalk/2003/system-properties").ToString();
                }
                else if (inmsg.Context.Read("SPID", "http://schemas.microsoft.com/BizTalk/2003/system-properties") != null)
                {
                    ServiceName = inmsg.Context.Read("SPName", "http://schemas.microsoft.com/BizTalk/2003/system-properties").ToString();
                }

                string msgId = inmsg.MessageID.ToString();

                SqlConnection Conn = new SqlConnection("Server=BT360DEV34\\MSSQLSERVER1;Database=B360_BAM;Integrated Security=True;");


                SqlCommand command = new SqlCommand(
                    "INSERT INTO [dbo].[CustomTrackTbl] " +
                    "([ActivityID] " +
                    ",[CorrelationID] " +
                    ",[StartTime] " +
                    ",[EndTime] " +
                    ",[ServiceName] " +
                    ",[MsgContext] " +
                    ",[StreamMsgPayload] " +
                    ",[RawMsgPayload] " +
                    ",[Status] " +
                    ",[MessageArchiveLocation])" +
                    "VALUES(@ActivityID,@CorrelationID,@StartTime,@EndTime,@ServiceName,@MsgContext,@StreamMsgPayload,@RawMsgPayload,@Status,@MessageArchiveLocation)", Conn);

                command.Parameters.Add("@ActivityID", SqlDbType.VarChar).Value    = msgId;
                command.Parameters.Add("@CorrelationID", SqlDbType.VarChar).Value = InterchangeID;
                command.Parameters.Add("@StartTime", SqlDbType.VarChar).Value     = DateTime.Now.ToString();
                command.Parameters.Add("@EndTime", SqlDbType.VarChar).Value       = DateTime.Now.ToString();
                command.Parameters.Add("@ServiceName", SqlDbType.VarChar).Value   = ServiceName;
                command.Parameters.Add("@MsgContext", SqlDbType.VarChar).Value    = json;
                sourceStream.Position = 0;
                command.Parameters.Add("@StreamMsgPayload", SqlDbType.Binary).Value        = sourceStream;
                command.Parameters.Add("@RawMsgPayload", SqlDbType.VarChar).Value          = "NA";
                command.Parameters.Add("@Status", SqlDbType.VarChar, 255).Value            = "Success";
                command.Parameters.Add("@MessageArchiveLocation", SqlDbType.VarChar).Value = FullFilePath;

                Conn.Open();
                command.ExecuteNonQuery();
                Conn.Close();
            }
        }
        /// <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)
        {
            if (_ArchiveFiles)
            {
                string archiveFileName = inmsg.Context.Read(_FileNameProperty, _FileNamePropertyNamespace) as string;
                if (archiveFileName != null && !string.IsNullOrEmpty(archiveFileName))
                {
                    if (archiveFileName.Contains("\\"))
                    {
                        archiveFileName = archiveFileName.Substring(archiveFileName.LastIndexOf("\\") + 1);
                    }

                    ArchivingStream archivingStream = new ArchivingStream(inmsg.BodyPart.Data, _ArchivePath + "\\" + archiveFileName);
                    pc.ResourceTracker.AddResource(archivingStream);
                    inmsg.BodyPart.Data = archivingStream;
                }
            }
            return(inmsg);
        }
        /// <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;
            }
        }
        /// <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 ExecuteFour(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);

            IBaseMessage outmsg = null;// = Utility.CloneMessage(inmsg, pc);

            //outmsg.BodyPart.Data = dataStream;

            return(outmsg);
        }
        /// <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 pipelineContext,
                                                                      Microsoft.BizTalk.Message.Interop.IBaseMessage inputMsg)
        {
            System.Diagnostics.Debug.WriteLine("At top of Execute method for DBASE pipeline");
            IBaseMessagePart bodyPart = inputMsg.BodyPart;

            if (bodyPart != null)
            {
                try
                {
                    // First write the ODBC file to disk so can query it.
                    BinaryReader binaryReader = new BinaryReader(bodyPart.Data);
                    string       folderName   = this.TempDropFolderLocation;
                    if (folderName.Substring(folderName.Length - 1, 1) != "\\")
                    {
                        folderName += "\\";
                    }
                    string extension = (this.TypeToProcess == odbcType.Excel) ? ".xls" : ".dbf";
                    string filename  = System.IO.Path.GetRandomFileName();
                    filename  = filename.Remove(8);
                    filename += extension;
                    string       folderNameAndFileName = folderName + filename;
                    FileStream   fileStream            = new FileStream(folderNameAndFileName, FileMode.CreateNew);
                    BinaryWriter binaryWriter          = new BinaryWriter(fileStream);
                    binaryWriter.Write(binaryReader.ReadBytes(Convert.ToInt32(binaryReader.BaseStream.Length)));
                    binaryWriter.Close();
                    binaryReader.Close();

                    // Create the Connection String for the ODBC File
                    string dataSource;
                    if (this.TypeToProcess == odbcType.Excel)
                    {
                        dataSource = "Data Source=" + folderNameAndFileName + ";";
                    }
                    else // dbf
                    {
                        dataSource = "Data Source=" + folderName + ";";
                    }
                    string odbcConnectionString = this.connectionString;
                    if (odbcConnectionString.Substring(odbcConnectionString.Length - 1, 1) != ";")
                    {
                        odbcConnectionString += ";";
                    }
                    odbcConnectionString += dataSource;
                    OleDbConnection oConn = new OleDbConnection();
                    oConn.ConnectionString = odbcConnectionString;

                    // Create the Select Statement for the ODBC File
                    OleDbDataAdapter oCmd;
                    // Get the filter if there is one
                    string whereClause = "";
                    if (Filter.Trim() != "")
                    {
                        whereClause = " Where " + Filter.Trim();
                    }
                    if (this.TypeToProcess == odbcType.Excel)
                    {
                        oCmd = new OleDbDataAdapter(this.SqlStatement.Trim() + whereClause, oConn);
                    }
                    else // dbf
                    {
                        oCmd = new OleDbDataAdapter(this.SqlStatement.Trim() + " From " + filename + whereClause, oConn);
                    }
                    oConn.Open();
                    // Perform the Select statement from above into a dataset, into a DataSet.
                    DataSet odbcDataSet = new DataSet();
                    oCmd.Fill(odbcDataSet, this.DataNodeName);
                    oConn.Close();
                    // Delete the message
                    if (this.DeleteTempMessages)
                    {
                        System.IO.File.Delete(folderNameAndFileName);
                    }

                    // Write the XML From this DataSet into a String Builder
                    System.Text.StringBuilder stringBuilder = new StringBuilder();
                    System.IO.StringWriter    stringWriter  = new System.IO.StringWriter(stringBuilder);
                    odbcDataSet.Tables[0].WriteXml(stringWriter);

                    System.Xml.XmlDocument fromDataSetXMLDom = new System.Xml.XmlDocument();
                    fromDataSetXMLDom.LoadXml(stringBuilder.ToString());

                    // Create the Final XML Document. Root Node Name and Target Namespace
                    // come from properties set on the pipeline
                    System.Xml.XmlDocument finalMsgXmlDom = new System.Xml.XmlDocument();
                    System.Xml.XmlElement  xmlElement;
                    xmlElement = finalMsgXmlDom.CreateElement("ns0", this.RootNodeName, this.NameSpace);
                    finalMsgXmlDom.AppendChild(xmlElement);

                    // Add the XML to the finalMsgXmlDom from the DataSet XML,
                    // After this the XML Message will be complete
                    finalMsgXmlDom.FirstChild.InnerXml = fromDataSetXMLDom.FirstChild.InnerXml;

                    Stream strm = new MemoryStream();
                    // Save final XML Document to Stream
                    finalMsgXmlDom.Save(strm);
                    strm.Position = 0;
                    bodyPart.Data = strm;
                    pipelineContext.ResourceTracker.AddResource(strm);
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            }
            return(inputMsg);
        }
Пример #28
0
        private string ProcessSystemPropertiesMacros(string Target, string TransportType, Microsoft.BizTalk.Message.Interop.IBaseMessage Message)
        {
            try
            {
                string UpdatedTarget = "";
                string Variable      = "";

                UpdatedTarget = Target.Replace("%TransportType%", TransportType);

                Variable      = Message.Context.Read("InterchangeID", "http://schemas.microsoft.com/BizTalk/2003/system-properties") as string;
                UpdatedTarget = UpdatedTarget.Replace("%InterchangeID%", Variable);

                Variable      = Message.Context.Read("InterchangeSequenceNumber", "http://schemas.microsoft.com/BizTalk/2003/system-properties") as string;
                UpdatedTarget = UpdatedTarget.Replace("%InterchangeSequenceNumber%", Variable);

                Variable      = Message.Context.Read("ReceivePortName", "http://schemas.microsoft.com/BizTalk/2003/system-properties") as string;
                UpdatedTarget = UpdatedTarget.Replace("%ReceivePortName%", Variable);

                return(UpdatedTarget);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #29
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);
        }
Пример #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>

        // Here we go... this is where the real work is done!
        public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            // The 'SpreadsheetDocument.Open' method throws a System.IndexOutOfRange exception when you use the stream from inmsg directly. This is because this is a Microsoft.BizTalk.Message.Interop.StreamViewOfIStream occurence. So first I copy it to a regular MemoryStream.

            Stream instream = CopyStream(inmsg.BodyPart.GetOriginalDataStream());

            //try
            //{
            string      xml    = string.Empty;
            XmlDocument xmldoc = new XmlDocument();
            XmlElement  root   = xmldoc.CreateElement(RootElementName, NamespaceName);

            xmldoc.AppendChild(root);
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(instream, false))
            {
                // I'm not going into all the details of the OpenXml format. You can find it all in the SDK.

                WorkbookPart          wbp             = doc.WorkbookPart;
                SharedStringTablePart shareStringPart = doc.WorkbookPart.GetPartsOfType <SharedStringTablePart>().First();
                SharedStringItem[]    items           = shareStringPart.SharedStringTable.Elements <SharedStringItem>().ToArray();

                Sheet     sheet         = wbp.Workbook.Descendants <Sheet>().First();
                Worksheet worksheet     = ((WorksheetPart)doc.WorkbookPart.GetPartById(sheet.Id)).Worksheet;
                Hashtable columnHeaders = new Hashtable();
                if (_UseColumnNamesFromFirstRow)
                {
                    // Here is the part where I look for the column headers. I loop through the rows of the sheet to find the top row (RowIndex.Value == 1) and then put all cell values into a Hashtable. (There's probably an easier way to get the first row, but I couldn't figure it out, and this works too ;-)

                    foreach (Row row in worksheet.Descendants <Row>())
                    {
                        if (row.RowIndex.Value == 1)
                        {
                            foreach (Cell cell in row)
                            {
                                string columnheader = GetCellValue(cell, items).Replace(' ', '_');
                                if (!string.IsNullOrEmpty(columnheader))
                                {
                                    string col = GetCellColumn(cell);

                                    // As explained above, I'm adding the column as a prefix.

                                    columnHeaders.Add(col, col + "_" + columnheader);
                                }
                            }
                            break;
                        }
                    }
                }
                foreach (Row row in worksheet.Descendants <Row>())
                {
                    if (!(_UseColumnNamesFromFirstRow && row.RowIndex.Value == 1))
                    {
                        // And here the XmlDocument is being build.

                        XmlElement rownode = xmldoc.CreateElement(RowElementName, NamespaceName);
                        root.AppendChild(rownode);
                        foreach (Cell cell in row)
                        {
                            string col = GetCellColumn(cell);
                            string nodename;
                            if (columnHeaders.ContainsKey(col))
                            {
                                nodename = (string)columnHeaders[col];
                            }
                            else
                            {
                                nodename = "Col" + col;
                            }
                            string cellvalue = GetCellValue(cell, items).Trim();
                            if (!string.IsNullOrEmpty(cellvalue))
                            {
                                XmlElement node = xmldoc.CreateElement(nodename, NamespaceName);
                                node.InnerText = cellvalue;
                                rownode.AppendChild(node);
                            }
                        }
                    }
                }
            }

            // Finally write the XmlDocument contents to a stream and replace the pipeline stream with this new stream.

            MemoryStream memStr = new MemoryStream();
            StreamWriter strOut = new StreamWriter(memStr);

            strOut.Write(xmldoc.OuterXml);


            strOut.Flush();
            memStr.Position = 0;
            pc.ResourceTracker.AddResource(memStr);
            inmsg.BodyPart.Data = memStr;
            //}
            //catch (Exception exc)
            //{
            // You can do your own error handling here...
            //}

            return(inmsg);
        }