Ejemplo n.º 1
0
        /// <summary>
        /// Creates an array of IBaseMessage objects from array of strings
        /// </summary>
        /// <param name="mf">Reference to BizTalk message factory object</param>
        /// <param name="url">Address of receive location where this message will be submitted to</param>
        /// <param name="data">Payloads for each message</param>
        /// <returns>Array of BizTalk message objects</returns>
        public static IBaseMessage[] CreateMessages(IBaseMessageFactory mf, string url, string[] data)
        {
            IBaseMessagePart    part = null;
            IBaseMessageContext ctx  = null;

            IBaseMessage[]       msgs = null;
            SystemMessageContext smc  = null;

            msgs = new IBaseMessage[data.Length];

            for (int c = 0; c < data.Length; c++)
            {
                // Write the data to a new stream...
                StreamWriter sw = new StreamWriter(new MemoryStream());
                sw.Write(data[c]);
                sw.Flush();
                sw.BaseStream.Seek(0, SeekOrigin.Begin);

                // Create a new message
                msgs[c]   = mf.CreateMessage();
                part      = mf.CreateMessagePart();
                part.Data = sw.BaseStream;
                ctx       = msgs[c].Context;
                msgs[c].AddPart("body", part, true);

                // Set the system context properties
                smc = new SystemMessageContext(ctx);
                if (null != url)
                {
                    smc.InboundTransportLocation = url;
                }
            }

            return(msgs);
        }
Ejemplo n.º 2
0
        internal static IBaseMessage CloneMessage(IBaseMessage inmsg, IPipelineContext pc)
        {
            IBaseMessageFactory messageFactory = pc.GetMessageFactory();

            var outmsg = messageFactory.CreateMessage();

            outmsg.Context = PipelineUtil.CloneMessageContext(inmsg.Context);

            // Generate new empty message body part, we will retain nothing from the old
            IBaseMessagePart body = messageFactory.CreateMessagePart();

            if ((inmsg != null) && (inmsg.BodyPart != null))
            {
                body.PartProperties = PipelineUtil.CopyPropertyBag(inmsg.BodyPart.PartProperties, messageFactory);
            }

            // This is what the XmlWriter will end up generating, and what appears in the
            // directive at the top of the file
            body.Charset     = "UTF-8";
            body.ContentType = "text/xml";
            body.Data        = null;

            CloneParts(pc, inmsg, outmsg, body);

            return(outmsg);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates IBaseMessage object from string
        /// </summary>
        /// <param name="mf">Reference to BizTalk message factory object</param>
        /// <param name="url">Address of receive location where this message will be submitted</param>
        /// <param name="data">Payload of the message</param>
        /// <returns>BizTalk message object</returns>
        public static IBaseMessage CreateMessage(IBaseMessageFactory mf, string url, string data)
        {
            IBaseMessagePart     part = null;
            IBaseMessageContext  ctx  = null;
            IBaseMessage         msg  = null;
            SystemMessageContext smc  = null;

            // Write the data to a new stream...
            StreamWriter sw = new StreamWriter(new MemoryStream());

            sw.Write(data);
            sw.Flush();
            sw.BaseStream.Seek(0, SeekOrigin.Begin);

            // Create a new message
            msg       = mf.CreateMessage();
            part      = mf.CreateMessagePart();
            part.Data = sw.BaseStream;
            ctx       = msg.Context;
            msg.AddPart("body", part, true);

            // Set the system context properties
            smc = new SystemMessageContext(ctx);
            if (null != url)
            {
                smc.InboundTransportLocation = url;
            }

            return(msg);
        }
        private IBaseMessage CreateMessage(BrokeredMessage message)
        {
            Stream stm = message.GetBody <Stream>();


            IBaseMessageFactory factory = this.transportProxy.GetMessageFactory();
            IBaseMessagePart    part    = factory.CreateMessagePart();

            part.Data = stm;



            IBaseMessage msg = factory.CreateMessage();

            msg.AddPart("body", part, true);

            //  We must add these context properties
            SystemMessageContext context = new SystemMessageContext(msg.Context);

            context.InboundTransportLocation = this.uri;
            context.InboundTransportType     = this.transportType;

            msg.Context.Promote("SequenceNumber", this.propertyNamespace, message.SequenceNumber.ToString());

            return(msg);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Create the output message when validation errors are captured
        /// </summary>
        /// <param name="pContext">Pipeline context</param>
        /// <param name="pInMsg">Input message in  the pipeline</param>
        /// <param name="errorStream">Stream for the Validation Errors</param>
        /// <param name="requestId">Request Id</param>
        /// <returns></returns>
        public static IBaseMessage CreateOutPutMessage(IPipelineContext pContext, IBaseMessage pInMsg, VirtualStream errorStream, string requestId)
        {
            VirtualStream seekableStream = new VirtualStream(pInMsg.BodyPart.GetOriginalDataStream());

            seekableStream.Position = 0;
            errorStream.Position    = 0;
            VirtualStream outMsgStream = CreateValidationErrorMessage(seekableStream, errorStream, requestId);

            outMsgStream.Position = 0;

            IBaseMessageFactory messageFactory  = pContext.GetMessageFactory();
            IBaseMessage        pOutMsg         = messageFactory.CreateMessage();
            IBaseMessagePart    pOutMsgBodyPart = messageFactory.CreateMessagePart();
            IBasePropertyBag    pOutPb          = PipelineUtil.CopyPropertyBag(pInMsg.BodyPart.PartProperties, messageFactory);

            pOutMsg.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);

            pOutMsgBodyPart.Charset     = Constants.BodyPartCharSet;
            pOutMsgBodyPart.ContentType = Constants.BodyPartContentType;
            pOutMsgBodyPart.Data        = outMsgStream;
            string outMessageType = string.Format("{0}#{1}", Constants.AIBPValidationErrorNameSpace, Constants.AIBPValidationErrorRootNode);

            pOutMsg.Context.Promote(Constants.MessageTypePropName, Constants.SystemPropertiesNamespace, outMessageType);

            pOutMsg.AddPart("Body", pOutMsgBodyPart, true);

            // Add resources to the resource tracker to be disposed of at correct time
            pContext.ResourceTracker.AddResource(seekableStream);
            pContext.ResourceTracker.AddResource(outMsgStream);
            pContext.ResourceTracker.AddResource(errorStream);
            return(pOutMsg);
        }
Ejemplo n.º 6
0
        private IBaseMessage CreateMessage(Shared.Components.Entry message)
        {
            MemoryStream mem = new MemoryStream(UTF8Encoding.UTF8.GetBytes(message.Content));

            IBaseMessageFactory factory = this.transportProxy.GetMessageFactory();
            IBaseMessagePart    part    = factory.CreateMessagePart();

            part.Data = mem;

            IBaseMessage msg = factory.CreateMessage();

            msg.AddPart("body", part, true);

            //  We must add these context properties
            SystemMessageContext context = new SystemMessageContext(msg.Context);

            context.InboundTransportLocation = this.uri;
            context.InboundTransportType     = this.transportType;
            //Set ActionOnFailure to zero in the context property of each messaqe that you do not want BizTalk Server to suspend on a processing exception.
            //Failure to set this property allows BizTalk Server to fall back to its default behavior
            //of suspending the message on a processing exception.
            //context.ActionOnFailure = 0;

            //we could promote entity id and updated, msg.Context.Promote(ns, message.Id
            return(msg);
        }
		/// <summary>
		/// Creates IBaseMessage object from string
		/// </summary>
		/// <param name="mf">Reference to BizTalk message factory object</param>
		/// <param name="url">Address of receive location where this message will be submitted</param>
		/// <param name="data">Payload of the message</param>
		/// <returns>BizTalk message object</returns>
		public static IBaseMessage CreateMessage(IBaseMessageFactory mf, string url, string data)
		{
			IBaseMessagePart		part	= null; 
			IBaseMessageContext		ctx		= null;
			IBaseMessage			msg		= null;
			SystemMessageContext	smc		= null;

			// Write the data to a new stream...
			StreamWriter sw = new StreamWriter(new MemoryStream());
			sw.Write(data);
			sw.Flush();
			sw.BaseStream.Seek(0, SeekOrigin.Begin);

			// Create a new message
			msg = mf.CreateMessage();
			part = mf.CreateMessagePart();
			part.Data = sw.BaseStream;
			ctx = msg.Context;
			msg.AddPart("body", part, true);

			// Set the system context properties
			smc = new SystemMessageContext(ctx);
			if ( null != url )
				smc.InboundTransportLocation = url;

			return msg;
		}
Ejemplo n.º 8
0
        /// <summary>
        /// Creates IBaseMessage objects from array of streams
        /// </summary>
        /// <param name="mf">Reference to BizTalk message factory object</param>
        /// <param name="url">Address of receive location where this message will be submitted to</param>
        /// <param name="data">Payloads for each message</param>
        /// <returns>Array of BizTalk message objects</returns>
        public static IBaseMessage[] CreateMessages(IBaseMessageFactory mf, string url, Stream[] data)
        {
            IBaseMessagePart    part = null;
            IBaseMessageContext ctx  = null;

            IBaseMessage[]       msgs = null;
            SystemMessageContext smc  = null;

            msgs = new IBaseMessage[data.Length];

            for (int c = 0; c < data.Length; c++)
            {
                // Create a new message
                msgs[c]   = mf.CreateMessage();
                part      = mf.CreateMessagePart();
                part.Data = data[c];
                ctx       = msgs[c].Context;
                msgs[c].AddPart("body", part, true);

                // Set the system context properties
                smc = new SystemMessageContext(ctx);
                if (null != url)
                {
                    smc.InboundTransportLocation = url;
                }
            }

            return(msgs);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// (1) Gets the file from the sftp host
        /// (2) Creates a IBaseMessage
        /// (3) Sets varius properties such as uri, messagepart, transporttype etc
        /// (4) Adds the message to the batch
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="uri"></param>
        /// <param name="size"></param>
        /// <param name="afterGetAction"></param>
        /// <param name="afterGetFilename"></param>
        /// <returns></returns>
        internal IBaseMessage CreateMessage(string fileName, string uri, long size,
                                            SftpReceiveProperties.AfterGetActions afterGetAction, string afterGetFilename)
        {
            try
            {
                TraceMessage("[SftpReceiverEndpoint] Reading file to stream " + fileName);

                // Retrieves the message from sftp server.
                var stream = _sftp.Get(fileName);
                stream.Position = 0;


                // Creates new message
                IBaseMessageFactory messageFactory = _transportProxy.GetMessageFactory();
                IBaseMessagePart    part           = messageFactory.CreateMessagePart();
                part.Data = stream;
                var message = messageFactory.CreateMessage();
                message.AddPart(MessageBody, part, true);

                // Setting metadata
                SystemMessageContext context =
                    new SystemMessageContext(message.Context)
                {
                    InboundTransportLocation = uri,
                    InboundTransportType     = _transportType
                };

                // Write/Promote any adapter specific properties on the message context
                message.Context.Write(Remotefilename, _propertyNamespace, fileName);

                SetReceivedFileName(message, fileName);

                message.Context.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/" +
                                      _transportType.ToLower() + "-properties", fileName);

                message.Context.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", fileName);

                // Add the file to the batch
                Files.Add(new BatchMessage(message, fileName, BatchOperationType.Submit, afterGetAction, afterGetFilename));

                // Greg Sharp: Let the caller set this as the file size may be stale
                // Add the size of the file to the stream
                //if (message.BodyPart.Data.CanWrite)
                //    message.BodyPart.Data.SetLength(size);

                return(message);
            }
            catch (Exception ex)
            {
                TraceMessage("[SftpReceiverEndpoint] Error Adding file [" + fileName + "]to batch. Error: " + ex.Message);

                if (_useLoadBalancing)
                {
                    DataBaseHelper.CheckInFile(uri, Path.GetFileName(fileName), _traceFlag);
                }

                return(null);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        ///     Creates a new message part
        /// </summary>
        /// <param name="body">Body of the part</param>
        /// <returns>The new part</returns>
        public static IBaseMessagePart CreatePartFromStream(Stream body)
        {
            if (body == null)
                throw new ArgumentNullException("body");

            IBaseMessagePart part = _factory.CreateMessagePart();
            part.Data = body;
            return part;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Adds a new message part to the specified request message which is intended to be used as a response part.
        /// </summary>
        /// <param name="msgFactory">The <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessageFactory"/> factory object providing message part creation capabilities.</param>
        /// <param name="requestMsg">The request message represented by the <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object.</param>
        /// <returns>A new message part represented by the <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessagePart"/> object.</returns>
        public static IBaseMessagePart CreateResponsePart(IBaseMessageFactory msgFactory, IBaseMessage requestMsg)
        {
            Guard.ArgumentNotNull(msgFactory, "msgFactory");
            Guard.ArgumentNotNull(requestMsg, "requestMsg");

            IBaseMessagePart responsePart = msgFactory.CreateMessagePart();

            requestMsg.AddPart(Resources.ResponseBodyPartName, responsePart, false);

            return(responsePart);
        }
Ejemplo n.º 12
0
        public static IBaseMessage CreateMessage(IBaseMessageFactory factory, string fileName)
        {
            IBaseMessage message = factory.CreateMessage();

            message.Context = factory.CreateMessageContext();
            IBaseMessagePart part = factory.CreateMessagePart();

            part.Data = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            message.AddPart("body", part, true);
            return(message);
        }
Ejemplo n.º 13
0
        public static IBaseMessage CreateMessage(IBaseMessageFactory factory, string fileName, StringCollection parts)
        {
            IBaseMessage message = CreateMessage(factory, fileName);

            for (int i = 0; i < parts.Count; i++)
            {
                IBaseMessagePart part = factory.CreateMessagePart();
                part.Data = new FileStream(parts[i], FileMode.Open, FileAccess.Read);
                message.AddPart(string.Format(CultureInfo.CurrentCulture, "part{0}", new object[] { i }), part, false);
            }
            return(message);
        }
Ejemplo n.º 14
0
        public static IBaseMessagePart getMsgFromStream(Stream body)
        {
            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            IBaseMessagePart part = msgfactory.CreateMessagePart();

            part.Data = body;
            return(part);
        }
Ejemplo n.º 15
0
        private static IBaseMessagePart CloneMessagePart(IPipelineContext pipelineContext, IBaseMessagePart messagePart)
        {
            IBaseMessageFactory messageFactory = pipelineContext.GetMessageFactory();
            IBaseMessagePart    messagePart1   = messageFactory.CreateMessagePart();

            messagePart1.Charset        = messagePart.Charset;
            messagePart1.ContentType    = messagePart.ContentType;
            messagePart1.PartProperties = PipelineUtil.CopyPropertyBag(messagePart.PartProperties, messageFactory);
            VirtualStream virtualStream = new VirtualStream();

            MessageHelper.CopyStream(messagePart.Data, (Stream)virtualStream);
            messagePart1.Data = (Stream)virtualStream;
            return(messagePart1);
        }
Ejemplo n.º 16
0
        internal IBaseMessagePart CopyMessagePart(IBaseMessageFactory factory)
        {
            IBaseMessagePart part = factory.CreateMessagePart();

            part.Data = this.GetOriginalDataStream();
            IBasePropertyBag partProperties = this.PartProperties;

            if (partProperties != null)
            {
                IBasePropertyBag bag2 = PipelineUtil.CopyPropertyBag(partProperties, factory);
                part.PartProperties = bag2;
            }
            return(part);
        }
        private IBaseMessage CreateMessage(IBaseMessageFactory messageFactory, Stream stream, string taskName)
        {
            IBaseMessagePart messagePart = messageFactory.CreateMessagePart();

            messagePart.Data = stream;
            IBaseMessage message = messageFactory.CreateMessage();

            message.AddPart("body", messagePart, true);
            SystemMessageContext context = new SystemMessageContext(message.Context);

            context.InboundTransportLocation = this.uri;
            context.InboundTransportType     = this.transportType;
            message.Context.Write(TaskNameProperty.Name.Name, TaskNameProperty.Name.Namespace, this.properties.Name);
            message.Context.Write(NextScheduleTimeProperty.Name.Name, NextScheduleTimeProperty.Name.Namespace, this.properties.Schedule.GetNextActivationTime());
            return(message);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates a new message with some notification description,
        /// and adds it to the BatchMessage
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        internal IBaseMessage CreateEmptyBatchMessage(string uri)
        {
            try
            {
                //string errorMessageFormat = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Error message=\"Empty Batch\" datetime=\"{0}\" source=\"{1}\"/>";
                string errorMessageFormat = "<bLogical:EmptyBatch message=\"Empty Batch\" datetime=\"{0}\" source=\"{1}\" xmlns:bLogical=\"http://Blogical.Shared.Adapters.Sftp.Schemas.EmptyBatch\" />";
                string errorMessage       = String.Format(errorMessageFormat, DateTime.Now.ToString(), uri);

                UTF8Encoding utf8Encoding  = new UTF8Encoding();
                byte[]       messageBuffer = utf8Encoding.GetBytes(errorMessage);

                MemoryStream ms = new MemoryStream(messageBuffer.Length);
                ms.Write(messageBuffer, 0, messageBuffer.Length);
                ms.Position = 0;

                ReadOnlySeekableStream ross = new ReadOnlySeekableStream(ms);

                IBaseMessageFactory messageFactory = _transportProxy.GetMessageFactory();
                IBaseMessagePart    part           = messageFactory.CreateMessagePart();
                part.Data = ross;
                var message = messageFactory.CreateMessage();
                message.AddPart(MessageBody, part, true);

                SystemMessageContext context =
                    new SystemMessageContext(message.Context)
                {
                    InboundTransportLocation = uri,
                    InboundTransportType     = _transportType
                };

                //Write/Promote any adapter specific properties on the message context
                message.Context.Write(Remotefilename, _propertyNamespace, Emptybatchfilename);

                // Add the file to the batch
                Files.Add(new BatchMessage(message, Emptybatchfilename, BatchOperationType.Submit));

                // Add the size of the file to the stream
                message.BodyPart.Data.SetLength(ms.Length);
                ms.Close();
                return(message);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        private IBaseMessage CreateMessage(Shared.Components.Entry message)
        {
            MemoryStream mem = new MemoryStream(UTF8Encoding.UTF8.GetBytes(message.Content));

            IBaseMessageFactory factory = this.transportProxy.GetMessageFactory();
            IBaseMessagePart    part    = factory.CreateMessagePart();

            part.Data = mem;

            IBaseMessage msg = factory.CreateMessage();

            msg.AddPart("body", part, true);

            //  We must add these context properties
            SystemMessageContext context = new SystemMessageContext(msg.Context);

            context.InboundTransportLocation = this.uri;
            context.InboundTransportType     = this.transportType;

            //we could promote entity id and updated, msg.Context.Promote(ns, message.Id
            return(msg);
        }
		/// <summary>
		/// Creates IBaseMessage object from stream
		/// </summary>
		/// <param name="mf">Reference to the BizTalk message factory</param>
		/// <param name="url">Address of receive location where this message will be submitted to</param>
		/// <param name="charset">Charset of the date</param>
		/// <param name="data">Message payload</param>
		/// <returns>BizTalk message object</returns>
		public static IBaseMessage CreateMessage(IBaseMessageFactory mf, string url, string charset, Stream data)
		{
			IBaseMessagePart		part	= null; 
			IBaseMessageContext		ctx		= null;
			IBaseMessage			msg		= null;
			SystemMessageContext	smc		= null;

			// Create a new message
			msg = mf.CreateMessage();
			part = mf.CreateMessagePart();
			part.Data = data;
			part.Charset = charset;
			ctx = msg.Context;
			msg.AddPart("body", part, true);

			// Set the system context properties
			smc = new SystemMessageContext(ctx);
			if ( null != url )
				smc.InboundTransportLocation = url;

			return msg;
		}
        private IBaseMessage BuildResponseMessage(WebResponse webResponse)
        {
            IBaseMessage btsResponse = null;

            // Get the response stream, create a new message attaching
            // the response stream...
            using (Stream s = webResponse.GetResponseStream())
            {
                // NOTE:
                // Copy the network stream into a virtual stream stream. If we were
                // to use a forward only stream (as in the response stream) we would
                // not be able to suspend the response data on failure. The virtual
                // stream will overflow to disc when it reaches a given threshold
                VirtualStream vs        = new VirtualStream();
                int           bytesRead = 0;
                byte[]        buff      = new byte[8 * 1024];
                while ((bytesRead = s.Read(buff, 0, buff.Length)) > 0)
                {
                    vs.Write(buff, 0, bytesRead);
                }

                webResponse.Close();

                // Seek the stream back to the start...
                vs.Position = 0;

                // Build BTS message from the stream
                IBaseMessageFactory mf = transportProxy.GetMessageFactory();
                btsResponse = mf.CreateMessage();
                IBaseMessagePart body = mf.CreateMessagePart();
                body.Data = vs;
                btsResponse.AddPart("Body", body, true);
            }

            return(btsResponse);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates IBaseMessage object from stream
        /// </summary>
        /// <param name="mf">Reference to the BizTalk message factory</param>
        /// <param name="url">Address of receive location where this message will be submitted to</param>
        /// <param name="charset">Charset of the date</param>
        /// <param name="data">Message payload</param>
        /// <returns>BizTalk message object</returns>
        public static IBaseMessage CreateMessage(IBaseMessageFactory mf, string url, string charset, Stream data)
        {
            IBaseMessagePart     part = null;
            IBaseMessageContext  ctx  = null;
            IBaseMessage         msg  = null;
            SystemMessageContext smc  = null;

            // Create a new message
            msg          = mf.CreateMessage();
            part         = mf.CreateMessagePart();
            part.Data    = data;
            part.Charset = charset;
            ctx          = msg.Context;
            msg.AddPart("body", part, true);

            // Set the system context properties
            smc = new SystemMessageContext(ctx);
            if (null != url)
            {
                smc.InboundTransportLocation = url;
            }

            return(msg);
        }
        private IBaseMessage BuildResponseMessage(IBaseMessage message, IBaseMessageContext context, LoopBackTransmitProperties props)
        {
            Guid callToken  = TraceManager.CustomComponent.TraceIn();
            long startScope = TraceManager.CustomComponent.TraceStartScope("BuildResponseMessage", callToken);

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

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

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

            return(btsResponse);
        }
		/// <summary>
		/// Creates IBaseMessage objects from array of streams
		/// </summary>
		/// <param name="mf">Reference to BizTalk message factory object</param>
		/// <param name="url">Address of receive location where this message will be submitted to</param>
		/// <param name="data">Payloads for each message</param>
		/// <returns>Array of BizTalk message objects</returns>
		public static IBaseMessage[] CreateMessages(IBaseMessageFactory mf, string url, Stream[] data)
		{
			IBaseMessagePart		part	= null; 
			IBaseMessageContext		ctx		= null;
			IBaseMessage[]			msgs	= null;
			SystemMessageContext	smc		= null;

			msgs = new IBaseMessage[data.Length];

			for ( int c = 0; c < data.Length; c++ )
			{
				// Create a new message
				msgs[c] = mf.CreateMessage();
				part = mf.CreateMessagePart();
				part.Data = data[c];
				ctx = msgs[c].Context;
				msgs[c].AddPart("body", part, true);

				// Set the system context properties
				smc = new SystemMessageContext(ctx);
				if ( null != url )
					smc.InboundTransportLocation = url;
			}

			return msgs;
		}
Ejemplo n.º 25
0
        /// <summary>
        /// processes the inbound message part
        /// </summary>
        /// <param name="pc"></param>
        /// <param name="inmsg"></param>
        /// <param name="outmsg"></param>
        /// <param name="part"></param>
        private void ProcessPart(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart part)
        {
            IDocumentSpec docSpec = null;

            Stream dataStream = part.GetOriginalDataStream();
            MarkableForwardOnlyEventingReadStream eventingDataStream = new MarkableForwardOnlyEventingReadStream(dataStream);

            XmlSchemaCollection schemaCollection = new XmlSchemaCollection(new NameTable());

            schemaCollection.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallBack);

            // retrieve the assigned document schemas to validate against
            SchemaList docSchemas = this.DocumentSchemas;

            // retrieve the namespace this document adheres to
            string contextProperty = (string)outmsg.Context.Read(XmlCompleteValidator._documentSpecNameProperty.Name.Name, XmlCompleteValidator._documentSpecNameProperty.Name.Namespace);

            // if the inbound message has a namespace,
            if (contextProperty != null && contextProperty.Length > 0)
            {
                // clear the original schemas to validate against
                docSchemas.Clear();

                string[] contextSchemas = contextProperty.Split(new char[] { '|' });

                // set it's schemas
                foreach (string schemaName in contextSchemas)
                {
                    docSchemas.Add(new Schema(schemaName));
                }
            }

            #region retrieve validation schemas, shamelessly copied from the original XmlValidator pipeline component
            bool validateSchemas = this.DocumentSchemas != null && this.DocumentSchemas.Count > 0;
            if (validateSchemas && this.DocumentSchemas.Count == 1 && this.DocumentSchemas[0].SchemaName.Length == 0)
            {
                validateSchemas = false;
            }

            if (validateSchemas)
            {
                foreach (Schema s in docSchemas)
                {
                    try
                    {
                        docSpec = pc.GetDocumentSpecByName(s.SchemaName);
                    }
                    catch (COMException e)
                    {
                        throw new XmlCompleteValidatorException(
                                  ExceptionType.CANNOT_GET_DOCSPEC_BY_NAME,
                                  e.ErrorCode.ToString("X") + ": " + e.Message,
                                  new string[] { s.SchemaName });
                    }

                    if (docSpec == null)
                    {
                        throw new XmlCompleteValidatorException(
                                  ExceptionType.CANNOT_GET_DOCSPEC_BY_NAME,
                                  string.Empty,
                                  new string[] { s.SchemaName });
                    }

                    XmlSchemaCollection coll = docSpec.GetSchemaCollection();

                    schemaCollection.Add(coll);
                }
            }
            else
            {
                try
                {
                    docSpec = pc.GetDocumentSpecByType(Utils.GetDocType(eventingDataStream));
                }
                catch (COMException e)
                {
                    throw new XmlCompleteValidatorException(
                              ExceptionType.CANNOT_GET_DOCSPEC_BY_TYPE,
                              e.ErrorCode.ToString("X") + ": " + e.Message,
                              new string[] { Utils.GetDocType(eventingDataStream) });
                }

                if (docSpec == null)
                {
                    throw new XmlCompleteValidatorException(
                              ExceptionType.CANNOT_GET_DOCSPEC_BY_TYPE,
                              string.Empty,
                              new string[] { Utils.GetDocType(eventingDataStream) });
                }

                schemaCollection = docSpec.GetSchemaCollection();
            }
            #endregion

            // the most critical line within this component, assign an
            // XmlEventingValidationStream to ensure the inbound messagestream is validated
            // and events can be assigned which allow us to capture any erros that might occur
            XmlEventingValidationStream validatingStream = new XmlEventingValidationStream(eventingDataStream);

            // add the schemas we'd like to validate the inbound message against
            validatingStream.Schemas.Add(schemaCollection);

            // assign a validation event which will accumulate any errors within the inbound message
            validatingStream.ValidatingReader.ValidationEventHandler += new ValidationEventHandler(XmlMessageValidationCallBack);

            // and assign the AfterLastReadEvent, which fires upon reading the last piece of information
            // from the inbound message stream and pushes all accumulated error information out into
            // the eventviewer and onto the HAT context by throwing an exception which contains the errors
            validatingStream.AfterLastReadEvent += new AfterLastReadEventHandler(validatingStream_AfterLastReadEvent);

            // duplicate the inbound message part by creating a new one and copying it's properties
            IBaseMessageFactory messageFactory = pc.GetMessageFactory();
            IBaseMessagePart    messagePart    = messageFactory.CreateMessagePart();

            // if the inbound message exists and has a body part, copy the part properties
            // into the outbound messagepart
            if (inmsg != null && inmsg.BodyPart != null)
            {
                messagePart.PartProperties = PipelineUtil.CopyPropertyBag(inmsg.BodyPart.PartProperties, messageFactory);
            }

            // set the outbound charset
            messagePart.Charset = "UTF-8";

            // set the outbound content type
            messagePart.ContentType = "text/xml";

            // and assign the outbound datastream
            messagePart.Data = validatingStream;

            // finally, copy existing message parts
            CopyMessageParts(pc, inmsg, outmsg, messagePart, false);
        }
		/// <summary>
		/// Creates an array of IBaseMessage objects from array of strings
		/// </summary>
		/// <param name="mf">Reference to BizTalk message factory object</param>
		/// <param name="url">Address of receive location where this message will be submitted to</param>
		/// <param name="data">Payloads for each message</param>
		/// <returns>Array of BizTalk message objects</returns>
		public static IBaseMessage[] CreateMessages(IBaseMessageFactory mf, string url, string[] data)
		{
			IBaseMessagePart		part	= null; 
			IBaseMessageContext		ctx		= null;
			IBaseMessage[]			msgs	= null;
			SystemMessageContext	smc		= null;

			msgs = new IBaseMessage[data.Length];

			for ( int c = 0; c < data.Length; c++ )
			{
				// Write the data to a new stream...
				StreamWriter sw = new StreamWriter(new MemoryStream());
				sw.Write(data[c]);
				sw.Flush();
				sw.BaseStream.Seek(0, SeekOrigin.Begin);

				// Create a new message
				msgs[c] = mf.CreateMessage();
				part = mf.CreateMessagePart();
				part.Data = sw.BaseStream;
				ctx = msgs[c].Context;
				msgs[c].AddPart("body", part, true);

				// Set the system context properties
				smc = new SystemMessageContext(ctx);
				if ( null != url )
					smc.InboundTransportLocation = url;
			}

			return msgs;
		}
Ejemplo n.º 27
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            if (!Enabled)
            {
                return(pInMsg);
            }
            string errorMessage;

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

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

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

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

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

            string[] filenames = FileNames.Split('|');
            while (i < pInMsg.PartCount & i < filenames.Length)
            {
                if (!string.IsNullOrEmpty(filenames[i]))
                {
                    string           partName = "";
                    IBaseMessagePart part     = pInMsg.GetPartByIndex(i, out partName),
                                     newPart  = messageFactory.CreateMessagePart();
                    Stream originalStream     = part.GetOriginalDataStream();
                    newPart.Data        = originalStream;
                    newPart.Charset     = part.Charset;
                    newPart.ContentType = "text/xml";
                    newPart.PartProperties.Write("FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", filenames[i]);
                    newMsg.AddPart(filenames[i], newPart, false);
                }
                i++;
            }
            return(newMsg);
        }