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 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); }
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); }
/// <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); }
public void TransactionalTask(IScheduledTaskStreamProvider2 provider) { //call GetStream CommittableTransaction transaction = null; Stream result = ((IScheduledTaskStreamProvider2)provider).GetStreams(this.adapterConfiguration.Task.TaskParameters, out transaction); if (result != null) { Batch batch = null; if (transaction != null) { batch = new ReceiveTxnBatch(transportProxy, controlledTermination, transaction, batchFinished, this.adapterConfiguration.SuspendMessage); } else { batch = new ReceiveBatch(transportProxy, controlledTermination, batchFinished, 0); } Stream readonlystream = new ReadOnlySeekableStream(result); IBaseMessageFactory messageFactory = this.transportProxy.GetMessageFactory(); IBaseMessage message = this.CreateMessage(messageFactory, readonlystream, this.adapterConfiguration.Name); batch.SubmitMessage(message, new StreamAndUserData(readonlystream, null)); batch.Done(); this.batchFinished.WaitOne(); ((IScheduledTaskStreamProvider2)provider).Done(batch.OverallSuccess); } }
/// <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); }
/// <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); }
public override void Open(string uri, Microsoft.BizTalk.Component.Interop.IPropertyBag config, IPropertyBag bizTalkConfig, Microsoft.BizTalk.Component.Interop.IPropertyBag handlerPropertyBag, IBTTransportProxy transportProxy, string transportType, string propertyNamespace, ControlledTermination control) { try { this.properties = new SBQueueReceiveProperties(uri); XmlDocument locationConfigDom = ConfigProperties.ExtractConfigDom(config); this.properties.LocationConfiguration(locationConfigDom, false); // this is our handle back to the EPM this.transportProxy = transportProxy; // used to control whether the EPM can unload us this.control = control; this.uri = uri; this.transportType = transportType; this.propertyNamespace = propertyNamespace; this.messageFactory = this.transportProxy.GetMessageFactory(); Start(); } catch (Exception) { throw; } finally { } }
/// <summary> /// Synchronously executes the task using the specified <see cref="RuntimeTaskExecutionContext"/> execution context object. /// </summary> /// <param name="context">The execution context.</param> public override void Run(RuntimeTaskExecutionContext context) { var callToken = TraceManager.CustomComponent.TraceIn(); IBaseMessageFactory msgFactory = context.PipelineContext.GetMessageFactory(); IBaseMessage responseMsg = msgFactory.CreateMessage(); IBaseMessageContext responseMsgCtx = msgFactory.CreateMessageContext(); IBaseMessageContext requestMsgCtx = context.Message.Context; responseMsg.Context = responseMsgCtx; if (BizTalkUtility.ContainsResponsePart(context.Message)) { IBaseMessagePart responsePart = BizTalkUtility.GetResponsePart(context.Message); responseMsg.AddPart(context.Message.BodyPartName, responsePart, true); } else { responseMsg.AddPart(context.Message.BodyPartName, context.Message.BodyPart, true); } responseMsgCtx.Promote(EpmRRCorrelationToken.Name.Name, EpmRRCorrelationToken.Name.Namespace, requestMsgCtx.Read(EpmRRCorrelationToken.Name.Name, EpmRRCorrelationToken.Name.Namespace)); responseMsgCtx.Promote(RouteDirectToTP.Name.Name, RouteDirectToTP.Name.Namespace, true); responseMsgCtx.Promote(CorrelationToken.Name.Name, CorrelationToken.Name.Namespace, requestMsgCtx.Read(CorrelationToken.Name.Name, CorrelationToken.Name.Namespace)); responseMsgCtx.Promote(ReqRespTransmitPipelineID.Name.Name, ReqRespTransmitPipelineID.Name.Namespace, requestMsgCtx.Read(ReqRespTransmitPipelineID.Name.Name, ReqRespTransmitPipelineID.Name.Namespace)); responseMsgCtx.Write(ReceivePipelineResponseConfig.Name.Name, ReceivePipelineResponseConfig.Name.Namespace, requestMsgCtx.Read(ReceivePipelineResponseConfig.Name.Name, ReceivePipelineResponseConfig.Name.Namespace)); context.Message = responseMsg; TraceManager.CustomComponent.TraceOut(callToken); }
/// <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); }
private void EndpointTask() { //Stream readonlystream = null; object provider = null; object taskArguments = null; try { try { Assembly streamProviderAssembly = Assembly.Load(this.properties.StreamProviderAssemblyName); provider = streamProviderAssembly.CreateInstance(this.properties.StreamProviderTypeName); } catch (Exception provderException) { transportProxy.SetErrorInfo(new ApplicationException("Error creating IScheduledTaskStreamProvider interface", provderException)); } if (provider != null) { //create GetStream argument object object [] args = new object [] {}; object result = provider.GetType().InvokeMember("GetParameterType", BindingFlags.InvokeMethod, null, provider, args); if (result != null) { StringReader strReader = new StringReader(this.properties.StreamProviderArguments); XmlSerializer serializer = new XmlSerializer((System.Type)result); taskArguments = serializer.Deserialize(strReader); } //call GetStream args = new object[] { taskArguments }; result = provider.GetType().InvokeMember("GetStream", BindingFlags.InvokeMethod, null, provider, args); if (result != null) { Stream readonlystream = new ReadOnlySeekableStream((Stream)result); IBaseMessageFactory messageFactory = this.transportProxy.GetMessageFactory(); IBTTransportBatch batch = transportProxy.GetBatch(this, null); IBaseMessage message = this.CreateMessage(messageFactory, readonlystream, this.properties.Name); batch.SubmitMessage(message); batch.Done(null); this.batchFinished.WaitOne(); } } } catch (Exception exception) { string errorMessage = exception.Message; //transportProxy.SetErrorInfo(exception); while (exception.InnerException != null) { exception = exception.InnerException; errorMessage += "\r\n" + exception.Message; } transportProxy.ReceiverShuttingdown(this.uri, new ScheduledException(errorMessage)); } }
/// <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); } }
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); }
/// <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); }
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); }
/// <summary> /// Creatable receiver constructor /// </summary> /// <param name="tp">Transport proxy object reference</param> public BizTalkMessaging(IBTTransportProxy tp) { if (null == tp) { throw new ArgumentNullException("IBTTransportProxy may not be null"); } this._tp = tp; _mf = _tp.GetMessageFactory(); _initialized = true; }
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); }
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); }
/// <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); } }
public void NonTransactionalTask(IScheduledTaskStreamProvider provider) { //call GetStream Stream result = ((IScheduledTaskStreamProvider)provider).GetStream(this.adapterConfiguration.Task.TaskParameters); if (result != null) { Stream readonlystream = new ReadOnlySeekableStream(result); ReceiveBatch batch = new ReceiveBatch(transportProxy, controlledTermination, batchFinished, 0); IBaseMessageFactory messageFactory = this.transportProxy.GetMessageFactory(); IBaseMessage message = this.CreateMessage(messageFactory, readonlystream, this.adapterConfiguration.Name); batch.SubmitMessage(message, new StreamAndUserData(readonlystream, null)); batch.Done(); this.batchFinished.WaitOne(); } }
/// <summary> /// Deep XML message valitation method. This method copies the inbound message, processes /// the inbound message onto the copied message and returns the copied message if all went well /// </summary> /// <param name="pc">the <see cref="IPipelineContext"/></param> /// <param name="inmsg">the inbound message</param> /// <returns>the copied message instance, if all went well</returns> private IBaseMessage FullyValidateMessage(IPipelineContext pc, IBaseMessage inmsg) { IBaseMessage copiedMessage = null; if (pc != null && inmsg != null) { #region duplicate inbound message IBaseMessageFactory messageFactory = pc.GetMessageFactory(); copiedMessage = messageFactory.CreateMessage(); IBaseMessageContext copiedContext = inmsg.Context; IBaseMessagePart copiedMessagePart = inmsg.BodyPart; copiedMessage.Context = copiedContext; #endregion this.ProcessPart(pc, inmsg, copiedMessage, copiedMessagePart); } return(copiedMessage); }
private void Init(string url) { if (true == this.adapterRegistered) { return; } Trace.WriteLine(string.Format("HttpReceiveAdapter.Init( url:{0} ) called", url), "HttpReceive: Info"); lock (this) { if (false == this.adapterRegistered) { // Register the adapter with messaging engine this.transportProxy.RegisterIsolatedReceiver(url, (IBTTransportConfig)this); this.msgFactory = this.transportProxy.GetMessageFactory(); this.adapterRegistered = true; } } }
/// <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 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> /// Initialize the adapter by specifying the address of the receive location that uses the adapter /// </summary> /// <param name="tp">Transport proxy object reference</param> /// <param name="url">Address of the receive location</param> /// <param name="callBack">Reference to the configuration callback interface</param> private void InternalInitialize(IBTTransportProxy tp, string url, IBTTransportConfig callBack) { lock (this) { while (false == _initialized) { IBTTransportConfig cb = null; if (null == url) { throw new ArgumentNullException("Url may not be null"); } if (null == callBack) { cb = this; } else { cb = callBack; } if (null == tp && null == _tp) { _tp = new IBTTransportProxy(); } else if (null != tp) { _tp = tp; } _tp.RegisterIsolatedReceiver(url, cb); _mf = _tp.GetMessageFactory(); _initialized = true; } } }
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); }
/// <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); }
/// <summary> /// Initialize the adapter by specifying the address of the receive location that uses the adapter /// </summary> /// <param name="tp">Transport proxy object reference</param> /// <param name="url">Address of the receive location</param> /// <param name="callBack">Reference to the configuration callback interface</param> private void InternalInitialize(IBTTransportProxy tp, string url, IBTTransportConfig callBack) { lock(this) { while ( false == _initialized ) { IBTTransportConfig cb = null; if ( null == url ) throw new ArgumentNullException("Url may not be null"); if ( null == callBack ) { cb = this; } else { cb = callBack; } if ( null == tp && null == _tp ) { _tp = new IBTTransportProxy(); } else if ( null != tp ) { _tp = tp; } _tp.RegisterIsolatedReceiver(url, cb); _mf = _tp.GetMessageFactory(); _initialized = true; } } }
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> /// 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 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; }
/// <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; }
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); }
/// <summary> /// Creatable receiver constructor /// </summary> /// <param name="tp">Transport proxy object reference</param> public BizTalkMessaging(IBTTransportProxy tp) { if ( null == tp ) throw new ArgumentNullException("IBTTransportProxy may not be null"); this._tp = tp; _mf = _tp.GetMessageFactory(); _initialized = true; }