public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { var contentReader = new ContentReader(); var data = pInMsg.BodyPart.GetOriginalDataStream(); if (!data.CanSeek || !data.CanRead) { const int bufferSize = 0x280; const int thresholdSize = 0x100000; data = new ReadOnlySeekableStream(data, new VirtualStream(bufferSize, thresholdSize), bufferSize); pContext.ResourceTracker.AddResource(data); } if (contentReader.IsXmlContent(data)) { var encoding = contentReader.Encoding(data); data = new ContentWriter().RemoveNamespace(data, encoding); pContext.ResourceTracker.AddResource(data); pInMsg.BodyPart.Data = data; } else { data.Seek(0, SeekOrigin.Begin); pInMsg.BodyPart.Data = data; } return pInMsg; }
/// <summary> /// Write and optionally promote a context property to one of the implemented schemas. /// </summary> /// <param name="pInMsg">The message, whose context will be written to.</param> /// <param name="propertyName">The context property name.</param> /// <param name="propertyValue">The context property value.</param> /// <param name="promoteContextProperty">A boolean flag that determines whether the written context property is promoted.</param> public static void Set(IBaseMessage pInMsg, string propertyName, string propertyValue, bool promoteContextProperty = false) { bool written = false; System.Exception exception = null; foreach (string namespaceValue in Namespaces) { try { pInMsg.Context.Write(propertyName, namespaceValue, propertyValue); if (promoteContextProperty) { pInMsg.Context.Promote(propertyName, namespaceValue, propertyValue); } written = true; break; } catch (Exception ex) { exception = ex; } } if (!written) { if (exception == null) { } throw exception; } }
/// <summary> /// Helper class to persist BizTalk message bodies /// </summary> /// <param name='message'>The BizTalk message to persist</param> /// <param name='destination'>The destination directory to persist the file to</param> public static void PersistMessage(IBaseMessage message, string destination) { using (var fs = new FileStream(destination, FileMode.Create)) { var enc = Encoding.GetEncoding("UTF-8"); if (!string.IsNullOrEmpty(message.BodyPart.Charset)) { enc = Encoding.GetEncoding(message.BodyPart.Charset); } using (var writer = new StreamWriter(fs, enc)) { var msgStream = message.BodyPart.GetOriginalDataStream(); using (var reader = new StreamReader(msgStream, enc)) { const int size = 1024; var buf = new char[size]; var charsRead = reader.Read(buf, 0, size); while (charsRead > 0) { writer.Write(buf, 0, charsRead); charsRead = reader.Read(buf, 0, size); } } } } }
public static Stream CreateSourceStream(IBaseMessage pInMsg) { SeekableReadOnlyStream stream = new SeekableReadOnlyStream(pInMsg.BodyPart.GetOriginalDataStream()); Stream sourceStream = pInMsg.BodyPart.GetOriginalDataStream(); return sourceStream; }
public void InitializeTest() { _testMessage = MessageHelper.Create("<test></test>"); _testMessage.Context.Promote(new ContextProperty("http://testuri.org#SourceProperty"), "Value"); _testMessage.Context.Promote(new ContextProperty("http://testuri.org#BooleanProperty"), true); _testMessage.Context.Promote(new ContextProperty("http://testuri.org#XmlDocumentProperty"), new XmlDocument()); }
public void Resubmit(IBaseMessage msg, bool preserveRetryCount, object userData) { SystemMessageContext context = new SystemMessageContext(msg.Context); if (preserveRetryCount) { UpdateProperty[] updates = new UpdateProperty[1]; updates[0] = new UpdateProperty(); updates[0].Name = retryCountProp.Name.Name; updates[0].NameSpace = retryCountProp.Name.Namespace; updates[0].Value = context.RetryCount++; context.UpdateProperties(updates); // If preserveRetryCount is true, ignore RetryInterval // Request the redelivery immediately!! base.Resubmit(msg, DateTime.Now, userData); } else { // This is retry in case of error/failure (i.e. normal retry) if (context.RetryCount > 0) { DateTime retryAt = DateTime.Now.AddMinutes(context.RetryInterval); base.Resubmit(msg, retryAt, userData); } else { base.MoveToNextTransport(msg, userData); } } }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } var cu = new CompressionUtil(); for (var i = 0; i < pInMsg.PartCount; i++) { string partName; var part = pInMsg.GetPartByIndex(i, out partName); var fileName = GetFileName(part); cu.AddMessage(part.GetOriginalDataStream(), fileName); } var outMsg = pContext.GetMessageFactory().CreateMessage(); outMsg.Context = pInMsg.Context; var bodyPart = pContext.GetMessageFactory().CreateMessagePart(); bodyPart.Data = cu.GetZip(); bodyPart.Charset = "utf-8"; bodyPart.ContentType = "application/zip"; outMsg.AddPart("Body",bodyPart,true); return outMsg; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } String value = null; IBaseMessagePart bodyPart = pInMsg.BodyPart; Stream inboundStream = bodyPart.GetOriginalDataStream(); VirtualStream virtualStream = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk); ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream); XmlTextReader xmlTextReader = new XmlTextReader(readOnlySeekableStream); XPathCollection xPathCollection = new XPathCollection(); XPathReader xPathReader = new XPathReader(xmlTextReader, xPathCollection); xPathCollection.Add(XPath); while (xPathReader.ReadUntilMatch()) { if (xPathReader.Match(0)) { if (xPathReader.NodeType == XmlNodeType.Attribute) { value = xPathReader.GetAttribute(xPathReader.Name); } else { value = xPathReader.ReadString(); } if (PromoteProperty) { pInMsg.Context.Promote(new ContextProperty(PropertyPath), value); } else { pInMsg.Context.Write(new ContextProperty(PropertyPath), value); } break; } } if (string.IsNullOrEmpty(value) && ThrowIfNoMatch) { throw new InvalidOperationException("The specified XPath did not exist or contained an empty value."); } readOnlySeekableStream.Position = 0; pContext.ResourceTracker.AddResource(readOnlySeekableStream); bodyPart.Data = readOnlySeekableStream; return pInMsg; }
public override IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg) { //write the itinerary to context, using the typed service request - //assumes the message body is not to be altered: RecordResult serviceRequest = new RecordResult(); PipelineComponentHelper.WriteItineraryToMessage(inmsg, serviceRequest); return inmsg; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { var ticket = new ISSOTicket(); pInMsg.Context.Write(new ContextProperty(SSOTicketProperties.SSOTicket), ticket.IssueTicket(0)); return pInMsg; }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { IBaseMessagePart bodyPart = pInMsg.BodyPart; if (bodyPart != null) { _qOutMessages = _decompressionManager.DecompressAndSpliMessage(pInMsg, pContext); } }
public IBaseMessage Assemble(IPipelineContext pContext) { var message = _inputMessage; _inputMessage = null; if ( message != null ) { _stagesSeen.Add(pContext.StageID); } return message; }
private ReadOnlySeekableStream GetSeekableStream(IBaseMessage msg) { Stream inboundStream = msg.BodyPart.GetOriginalDataStream(); VirtualStream virtualStream = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk); ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(inboundStream, virtualStream); readOnlySeekableStream.Position = 0; readOnlySeekableStream.Seek(0, SeekOrigin.Begin); return readOnlySeekableStream; }
private static void CloneParts(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart bodyPart) { for (int i = 0; i < inmsg.PartCount; i++) { string partName = null; IBaseMessagePart currentPart = inmsg.GetPartByIndex(i, out partName); if (currentPart == null) continue; outmsg.AddPart(partName, partName == inmsg.BodyPartName ? bodyPart : currentPart, partName == inmsg.BodyPartName); } }
public override sealed void SubmitResponseMessage(IBaseMessage solicitDocSent, IBaseMessage responseDocToSubmit) { IBaseMessagePart bodyPart = responseDocToSubmit.BodyPart; if (bodyPart == null) throw new InvalidOperationException("The message does not contain body part"); Stream stream = bodyPart.GetOriginalDataStream(); if (stream == null || stream.CanSeek == false) throw new InvalidOperationException("Message body stream is null or it is not seekable"); base.SubmitResponseMessage(solicitDocSent, responseDocToSubmit, solicitDocSent); }
public void MergeIntoMessage(IBaseMessage message) { foreach (MessageInfoContextInfoProperty prop in this.MessageContextProperties) { if (prop.Promoted) { message.Context.Promote(prop.Name, prop.Namespace, prop.Value); } else { message.Context.Write(prop.Name, prop.Namespace, prop.Value); } } }
/// <summary> /// Reads the response message from the server /// </summary> /// <param name="msg">Response message from the server</param> /// <returns>Flag to delete message from the server or not</returns> public bool TransmitMessage(IBaseMessage msg) { // Note: We need to read the stream which will execute the // pipeline, we then replace the stream with the one we // have created IBaseMessagePart bodyPart = msg.BodyPart; Stream s = null; if (bodyPart != null) s = bodyPart.GetOriginalDataStream(); // Create a memory stream to copy the data into Stream memStrm = new MemoryStream(); byte[] buff = new byte[4096]; int dataRead = 0, readOffSet = 0, writeOffSet = 0; if (s != null) { s.Seek(0, SeekOrigin.Begin); // Copy the data from the src stream do { dataRead = s.Read(buff, readOffSet, 4096); memStrm.Write(buff, writeOffSet, dataRead); } while (dataRead > 0); } // Create a new message IBaseMessage response = BizTalkMessaging._mf.CreateMessage(); // Copy over the context response.Context = msg.Context; // Copy over the body part, note, only support single part messages IBaseMessagePart messageBodyPart = BizTalkMessaging._mf.CreateMessagePart(); messageBodyPart.Data = memStrm; memStrm.Seek(0, SeekOrigin.Begin); response.AddPart(msg.BodyPartName, messageBodyPart, true); _msg = response; ThreadPool.QueueUserWorkItem(DeleteTransmitMessage, msg); // Return false. // We'll issue a Batch.DeleteMessage() later. return false; }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } //Get a reference to the BizTalk schema. var documentSpec = pContext.GetDocumentSpecByName(DocumentSpecName); //Get a list of properties defined in the schema. var annotations = documentSpec.GetPropertyAnnotationEnumerator(); var doc = new XmlDocument(); using (var sw = new StringWriter(new StringBuilder())) { //Create a new instance of the schema. doc.Load(((IFFDocumentSpec)documentSpec).CreateXmlInstance(sw)); } //Write all properties to the message body. while (annotations.MoveNext()) { var annotation = (IPropertyAnnotation)annotations.Current; var node = doc.SelectSingleNode(annotation.XPath); object propertyValue; if (pInMsg.Context.TryRead(new ContextProperty(annotation.Name, annotation.Namespace), out propertyValue)) { node.InnerText = propertyValue.ToString(); } } var data = new VirtualStream(); pContext.ResourceTracker.AddResource(data); doc.Save(data); data.Seek(0, SeekOrigin.Begin); var outMsg = pInMsg; outMsg.BodyPart.Data = data; //Promote message type and SchemaStrongName outMsg.Context.Promote(new ContextProperty(SystemProperties.MessageType), documentSpec.DocType); outMsg.Context.Promote(new ContextProperty(SystemProperties.SchemaStrongName), documentSpec.DocSpecStrongName); _outputQueue.Enqueue(outMsg); }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { //load up the Excel reader: Stream originalStream = pInMsg.BodyPart.GetOriginalDataStream(); string fileName = (string) pInMsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties"); _reader = GetDataReader(fileName, originalStream); //store the incoming context properties to write out again: _contextProperties = new List<ContextProperty>(); for (int i = 0; i < pInMsg.Context.CountProperties; i++) { ContextProperty property = new ContextProperty(); property.Value = pInMsg.Context.ReadAt(i, out property.Name, out property.Namespace); property.IsPromoted = pInMsg.Context.IsPromoted(property.Name, property.Namespace); _contextProperties.Add(property); } }
/// <summary> /// Read a context property value from a message's context. /// </summary> /// <param name="pInMsg">The message whose context will be read.</param> /// <param name="propertyName">The context property name.</param> /// <param name="defaultValue">A default value to return if the context property is not found.</param> /// <returns>The value of the context property.</returns> public static string Get(IBaseMessage pInMsg, string propertyName, string defaultValue = "") { string result = defaultValue; try { foreach (string namespaceValue in Namespaces) { if (pInMsg.Context.Read(propertyName, namespaceValue) != null) { result = System.Convert.ToString(pInMsg.Context.Read(propertyName, namespaceValue)); break; } } } catch { } return result; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { //read the incoming JSON stream: var inStream = pInMsg.BodyPart.GetOriginalDataStream(); var json = string.Empty; using (var reader = new StreamReader(inStream)) { json = reader.ReadToEnd(); } //convert to XML: var document = JsonConvert.DeserializeXNode(json, "root"); var output = new XElement(XName.Get(RootElementName, TargetNamespace)); output.Add(document.Root.Descendants()); //fix up the namespaces: XNamespace ns = TargetNamespace; foreach (var element in output.Descendants()) { element.Name = ns.GetName(element.Name.LocalName); var attributes = element.Attributes().ToList(); element.Attributes().Remove(); foreach (XAttribute attribute in attributes) { if (!attribute.IsNamespaceDeclaration) { element.Add(new XAttribute(attribute.Name.LocalName, attribute.Value)); } } } //write to output body stream: var outStream = new MemoryStream(); var writer = new XmlTextWriter(outStream, Encoding.Default); output.WriteTo(writer); writer.Flush(); outStream.Flush(); outStream.Position = 0; pInMsg.BodyPart.Data = outStream; //promote the message type: pInMsg.Context.Promote(_MessageTypeProperty.Name.Name, _MessageTypeProperty.Name.Namespace, string.Format("{0}#{1}", TargetNamespace, RootElementName)); return pInMsg; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } var contentReader = new ContentReader(); var data = pInMsg.BodyPart.GetOriginalDataStream(); if (!data.CanSeek || !data.CanRead) { const int bufferSize = 0x280; const int thresholdSize = 0x100000; data = new ReadOnlySeekableStream(data, new VirtualStream(bufferSize, thresholdSize), bufferSize); pContext.ResourceTracker.AddResource(data); } if (contentReader.IsXmlContent(data) && contentReader.NamespacExists(data, NamespaceToModify)) { var encoding = contentReader.Encoding(data); data = new ContentWriter().ModifyNamespace(data, NamespaceToModify, NewNamespace, encoding); pContext.ResourceTracker.AddResource(data); pInMsg.BodyPart.Data = data; if (ShouldUpdateMessageTypeContext) { var rootName = contentReader.GetRootNode(data); var contextReader = new ContextReader(); contextReader.UpdateMessageTypeContext(pInMsg.Context, NewNamespace, rootName); } } else { data.Seek(0, SeekOrigin.Begin); pInMsg.BodyPart.Data = data; } return pInMsg; }
public static IBaseMessagePart CreateIBaseMsgPart(IBaseMessage pInMsg, ref long position, ref Stream sourceStream) { if (!sourceStream.CanSeek) { SeekableReadOnlyStream seekableStream = new SeekableReadOnlyStream(sourceStream); pInMsg.BodyPart.Data = seekableStream; sourceStream = pInMsg.BodyPart.Data; } position = sourceStream.Position; sourceStream.Position = position; IBaseMessagePart bodyPart = pInMsg.BodyPart; return bodyPart; }
public microServiceBusTransmitProperties(IBaseMessage message, string propertyNamespace) { XmlDocument locationConfigDom = null; // get the adapter configuration off the message IBaseMessageContext context = message.Context; string config = (string)context.Read("AdapterConfig", propertyNamespace); if (null != config) { locationConfigDom = new XmlDocument(); locationConfigDom.LoadXml(config); this.ReadLocationConfiguration(locationConfigDom); } else // the config can be null all that means is that we are doing a dynamic send { this.ReadLocationConfiguration(message.Context); } }
public Queue DecompressAndSpliMessage(IBaseMessage inMsg, IPipelineContext pctx) { var readOnlySeekableStream = GetSeekableStream(inMsg); var messages = _decompressor.DecompressMessage(readOnlySeekableStream); var outMsgs = new Queue(); IBaseMessage outMessage; foreach (var msg in messages) { outMessage = pctx.GetMessageFactory().CreateMessage(); outMessage.AddPart("Body", pctx.GetMessageFactory().CreateMessagePart(), true); outMessage.BodyPart.Data = msg.Value; outMessage.Context = PipelineUtil.CloneMessageContext(inMsg.Context); ContextExtensions.Promote(outMessage.Context, new ContextProperty(FileProperties.ReceivedFileName), msg.Key); outMsgs.Enqueue(outMessage); } return outMsgs; }
private static string ResolveMessageMacros(IBaseMessage btsMessage, string fileNamePattern) { // generate the new filename using the specified filename pattern // start by assigning the pattern to the output filename string outputFileName = fileNamePattern; // replace the %MessageID% macro if (MessageIDMacroRegex.IsMatch(outputFileName) == true) { outputFileName = MessageIDMacroRegex.Replace(outputFileName, btsMessage.MessageID.ToString()); } // replace the %BodyPartName% macro if (BodyPartNameMacroRegex.IsMatch(outputFileName) == true) { outputFileName = BodyPartNameMacroRegex.Replace(outputFileName, btsMessage.BodyPartName.ToString()); } // return generated filename return(outputFileName); }
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { if (pipelineContext == null) { throw new ArgumentNullException(nameof(pipelineContext)); } if (message == null) { throw new ArgumentNullException(nameof(message)); } message.BodyPart.WrapOriginalDataStream( originalStream => { if (_logger.IsDebugEnabled) { _logger.Debug($"Wrapping message stream in a {nameof(ZipInputStream)}."); } return(new ZipInputStream(originalStream)); }, pipelineContext.ResourceTracker); return(message); }
public void Execute(ref IBaseMessage inmsg, IPipelineContext pc) { try { object value = null; value = StaticHelpers.ReadFromSSO(_SSOApplication, _SSOKey); if (promotion == ContextInstructionTypeEnum.Write) { inmsg.Context.Write(propertyName, propertyNamespace, TypeCaster.GetTypedObject(value, type)); } else if (promotion == ContextInstructionTypeEnum.Promote) { inmsg.Context.Promote(propertyName, propertyNamespace, TypeCaster.GetTypedObject(value, type)); } } catch (Exception e) { throw new Exception("Unable to set context property " + propertyNamespace + "#" + propertyName + " from SSO application " + _SSOApplication + " and SSO Key " + _SSOKey + ". Encountered error - " + e.ToString()); } }
/// <summary> /// Copies all the message parts from the source message into the destination message. /// </summary> /// <param name="sourceMessage">Source message.</param> /// <param name="destinationMessage">Destination message.</param> public static void CopyMessageParts(IBaseMessage sourceMessage, IBaseMessage destinationMessage) { if (sourceMessage == null) { throw new ArgumentNullException("sourceMessage"); } if (destinationMessage == null) { throw new ArgumentNullException("destinationMessage"); } string bodyPartName = sourceMessage.BodyPartName; for (int index = 0; index < sourceMessage.PartCount; ++index) { string partName = null; IBaseMessagePart partByIndex = sourceMessage.GetPartByIndex(index, out partName); bool isBodyPart = string.Compare(partName, bodyPartName, true, CultureInfo.CurrentCulture) == 0; destinationMessage.AddPart(partName, partByIndex, isBodyPart); } }
public static int ResolveTrackingContextCacheDuration(this IBaseMessage message, TimeSpan configuredDuration) { // TODO ? assert that WCF transport is used var wcfTimeout = message.GetProperty(WcfProperties.SendTimeout); if (!wcfTimeout.IsNullOrEmpty()) { return((int)TimeSpan.Parse(wcfTimeout, CultureInfo.InvariantCulture).TotalSeconds); } // TODO ? assert that HTTP transport is used var httpTimeout = message.GetProperty(HttpProperties.RequestTimeout); // TODO ? assert Timeout.Value > 0 if (httpTimeout.HasValue) { return(httpTimeout.Value); } return((int)configuredDuration.TotalSeconds); }
private IBaseMessage CreateMessage(IEventType eventType, ActionContext contextItem) { Stream fs; fs = new MemoryStream(eventType.DataContext); IBaseMessagePart part = this.messageFactory.CreateMessagePart(); part.Data = fs; IBaseMessage message = this.messageFactory.CreateMessage(); message.AddPart(MESSAGE_BODY, part, true); SystemMessageContext context = new SystemMessageContext(message.Context); context.InboundTransportType = this.transportType; context.InboundTransportLocation = this.properties.Uri; //Write/Promote any adapter specific properties on the message context message.Context.Write(PROP_REMOTEMESSAGEID, PROP_NAMESPACE, contextItem.BubblingObjectBag.MessageId); return(message); }
public void AddDocument(IPipelineContext pc, IBaseMessage pInMsg) { assembler.AddDocument(pc, pInMsg); string type = String.Empty; try { type = pInMsg.Context.Read("MessageType", NS) as string; } catch { type = String.Empty; } if (!string.IsNullOrWhiteSpace(type)) { pInMsg.Context.Write("Operation", NS, type); pInMsg.Context.Promote("Operation", NS, type); } }
/// <summary> /// Transmit a message handed down by the EPM /// </summary> /// <param name="msg">Message to send</param> /// <returns>True if the message was sent successfuly</returns> public bool TransmitMessage(IBaseMessage msg) { _terminate.Enter(); try { bool logMessages = Convert.ToBoolean( GetAdapterConfigValue(msg.Context, "logMessages") ); if (logMessages) { SystemMessageContext ctxt = new SystemMessageContext(msg.Context); LogHelper.LogMessage(msg.MessageID, ctxt.InterchangeID); } // // discard the message // return(true); } finally { _terminate.Leave(); } }
public void AddDocument(IPipelineContext pContext, IBaseMessage pInMsg) { StreamReader messageReader = new StreamReader(pInMsg.BodyPart.GetOriginalDataStream()); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.Append("<?xml version=\"1.0\"?>"); messageBuilder.Append(messageReader.ReadToEnd().ExceptBlanks()); MemoryStream newMessageStream = new MemoryStream(); StreamWriter writer = new StreamWriter(newMessageStream); writer.Write(messageBuilder.ToString()); writer.Flush(); newMessageStream.Seek(0, SeekOrigin.Begin); IBaseMessage outputMessage = pInMsg; outputMessage.BodyPart.Data = newMessageStream; _outputMessages.Enqueue(outputMessage); }
protected async void RecieveMessageAsync(byte[] messageBytes, IPEndPoint ipEndPoint) { await Task.Run(() => { try { IBaseMessage message = Serializer.Deserialize(messageBytes); if (PeerManager.AddOrUpdatePeer(message.From, ipEndPoint)) { OnNewConnectedPeer?.Invoke(this, message.From); } OnMessageReceived?.Invoke(this, message); } catch (Exception e) { OnMessageReceivedFailure?.Invoke(this, new ReceiveFailureException("Failed deserialising new message", e)); } }); }
public void CanExecutePipelineWithFlatFile() { ReceivePipelineWrapper pipeline = PipelineFactory.CreateReceivePipeline(typeof(CSV_FF_RecvPipeline)); // Create the input message to pass through the pipeline Stream stream = DocLoader.LoadStream("CSV_FF_RecvInput.txt"); IBaseMessage inputMessage = MessageHelper.CreateFromStream(stream); inputMessage.BodyPart.Charset = "UTF-8"; // Add the necessary schemas to the pipeline, so that // disassembling works pipeline.AddDocSpec(typeof(Schema3_FF)); // Execute the pipeline, and check the output MessageCollection outputMessages = pipeline.Execute(inputMessage); Assert.IsNotNull(outputMessages); Assert.IsTrue(outputMessages.Count > 0); }
protected override void SubmitRequestFailure(IBaseMessage message, int hrStatus, object userData) { failedMessages.Add(new FailedMessage(message, hrStatus)); Stream originalStream = message.BodyPart.GetOriginalDataStream(); if (this.innerBatch != null) { try { originalStream.Seek(0, SeekOrigin.Begin); message.BodyPart.Data = originalStream; this.innerBatch.MoveToSuspendQ(message, userData); this.innerBatchCount++; } catch (Exception e) { Trace.WriteLine("ReceiveBatch.SubmitFailure Exception: {0}", e.Message); this.innerBatch = null; } } }
/// <summary> /// Archives the input message into the specified archiving location. /// </summary> /// <param name="pipelineContext">Pipeline context</param> /// <param name="inputMessage">Input message</param> /// <returns>Original input message</returns> protected override IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage inputMessage) { // check if the message already has the RetryCount and RetryInterval properties // to skip the processing int retryCount = inputMessage.Context.Read <int>(BtsProperties.RetryCount.Name, BtsProperties.RetryCount.Namespace, 0); int retryInterval = inputMessage.Context.Read <int>(BtsProperties.RetryInterval.Name, BtsProperties.RetryInterval.Namespace, 0); if (retryCount <= 0 && retryInterval <= 0) { // get the actual number of transmissions the send handler has attempted int actualRetryCount = inputMessage.Context.Read <int>(BtsProperties.ActualRetryCount.Name, BtsProperties.ActualRetryCount.Namespace, 0); TraceProvider.Logger.TraceInfo("Message context ActualRetryCount = {0}", actualRetryCount); // get configured retry settings retryCount = this.RetryCount; retryInterval = this.RetryInterval; TraceProvider.Logger.TraceInfo("SendPortRetryService configuration settings: RetryCount = {0}, RetryInterval = {1}", retryCount, retryInterval); if (retryCount > 0 && retryInterval > 0) { // calculate how many retries are left retryCount = Math.Max(retryCount - actualRetryCount, 0); // update message context inputMessage.Context.Write(BtsProperties.RetryCount.Name, BtsProperties.RetryCount.Namespace, retryCount); inputMessage.Context.Write(BtsProperties.RetryInterval.Name, BtsProperties.RetryInterval.Namespace, retryInterval); TraceProvider.Logger.TraceInfo("Updated Message Retry context properties to: RetryCount = {0}, RetryInterval = {1}", retryCount, retryInterval); } else { TraceProvider.Logger.TraceInfo("Skipping SendPortRetry, RetryCount and/or RetryInterval not specified: RetryCount = {0}, RetryInterval = {1}", retryCount, retryInterval); } } else { TraceProvider.Logger.TraceInfo("Skipping SendPortRetry, message already has context properties: RetryCount = {0}, RetryInterval = {1}", retryCount, retryInterval); } // return original message return(inputMessage); }
public virtual IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { var map = message.ResolvePluginType(BizTalkFactoryProperties.MapTypeName, MapType) .OfPluginType <TransformBase>(); if (map != null) { if (_logger.IsDebugEnabled) { _logger.DebugFormat("Applying '{0}' XSL Transform to message.", map.AssemblyQualifiedName); } message.BodyPart.WrapOriginalDataStream( originalStream => originalStream .Transform() .ExtendWith(message.Context) .Apply(map, Encoding), pipelineContext.ResourceTracker); if (map.GetOutputSettings().OutputMethod == XmlOutputMethod.Xml) { if (_logger.IsDebugEnabled) { _logger.DebugFormat("Probing output of '{0}' XSL Transform and promoting new message type.", map.AssemblyQualifiedName); } message.ProbeAndPromoteMessageType(pipelineContext); } else if (_logger.IsDebugEnabled) { _logger.DebugFormat("Skip probing of '{0}' XSL Transform output for a message type as its OutputMethod is not XML.", map.AssemblyQualifiedName); } } else { if (_logger.IsDebugEnabled) { _logger.Debug("No XSL Transform was found in message context or configured to apply to message."); } } return(message); }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string name = String.Empty; string ns = String.Empty; /* * for (int i = 0; i < pInMsg.Context.CountProperties; i++) * { * object obj = pInMsg.Context.ReadAt(i, out name, out ns); * * } */ Stream orig_stream = pInMsg.BodyPart.GetOriginalDataStream(); if (orig_stream == null) { return(pInMsg); } var assembly = pInMsg.Context.Read("SchemaStrongName", ns_system); if (assembly == null) { throw new ArgumentException("Schema StrongName is not promoted!"); } SchemaMetaData schemaMetaData = SchemaRetriever.GetSchemaMetaData((string)assembly); if (schemaMetaData != null) { pInMsg.BodyPart.Data = new XPathStream(orig_stream, schemaMetaData, pInMsg.Context); } return(pInMsg); }
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { var extractors = BuildPropertyExtractorCollection(pipelineContext, message); var xpathExtractors = extractors.OfType <XPathExtractor>().ToArray(); var otherExtractors = extractors.Except(xpathExtractors).ToArray(); if (otherExtractors.Any()) { otherExtractors.Each(pe => pe.Execute(message.Context)); } if (xpathExtractors.Any()) { // setup a stream that will invoke our callback whenever an XPathExtractor's XPath expression is matched message.BodyPart.WrapOriginalDataStream( originalStream => XPathMutatorStreamFactory.Create( originalStream, xpathExtractors, () => message.Context), pipelineContext.ResourceTracker); } return(message); }
public void TestGoogleBucket() { IBaseMessage msg = MessageHelper.CreateFromString(Resource.GoogleBucketEntry_1); rcvpipeline.AddDocSpec(typeof(Schemas.BucketClaimCheck)); MessageCollection messages = rcvpipeline.Execute(msg); IBaseMessage message = messages[0]; ClaimCheckPipelineComponent claimCheckPipelineComponent = new ClaimCheckPipelineComponent(); claimCheckPipelineComponent.Enabled = true; claimCheckPipelineComponent.ClientId = "111382948100122064143"; claimCheckPipelineComponent.ServiceAccountName = "*****@*****.**"; FileInfo credentials = new FileInfo(googlecredentials); var jsonfilepath = credentials.FullName; claimCheckPipelineComponent.ServiceAccountKey = jsonfilepath; sndpipeline.AddComponent(claimCheckPipelineComponent, PipelineStage.Encode); IBaseMessage sendmessage = sndpipeline.Execute(messages); Diff myDiff = DiffBuilder.Compare(Input.FromString(Resource.GoogleBucketResult)) .WithTest(Input.FromStream(sendmessage.BodyPart.Data)) .CheckForIdentical().Build(); Assert.IsFalse(myDiff.HasDifferences()); }
public void XmlToJsonConverterPcDoesNotRemovesAtTheRateCharactersWhenRemoveAtTheRateCharIsSetToFalse() { //Arrange IBaseMessage inputMessage = PTL.MessageHelper.CreateFromStream(MessageHelper.LoadMessage("PurchaseOrder.xml")); var xmlToJsonConverter = new XmlToJsonConverter { RemoveAtTheRateChar = false }; PTL.SendPipelineWrapper testPipelineWrapper = PTL.PipelineFactory.CreateEmptySendPipeline(); testPipelineWrapper.AddComponent(xmlToJsonConverter, PTL.PipelineStage.Encode); //Act IBaseMessage outputMessages = testPipelineWrapper.Execute(inputMessage); //Assert Assert.IsTrue(outputMessages.BodyPart.Data.Position == 0, "The stream position should be zero"); var rdr = new StreamReader(outputMessages.BodyPart.Data); string outMsg = rdr.ReadToEnd(); Debug.WriteLine("Output Message: " + outMsg); Assert.IsTrue(outMsg.IndexOf('@', 0) > 0); }
public PowershellTransmitterProperties(IBaseMessage message, string propertyNamespace) { XmlDocument locationConfigDom = null; // get the adapter configuration off the message IBaseMessageContext context = message.Context; string config = (string)context.Read("AdapterConfig", propertyNamespace); // the config can be null all that means is that we are doing a dynamic send if (null != config) { locationConfigDom = new XmlDocument(); locationConfigDom.LoadXml(config); Uri = Extract(locationConfigDom, "/Config/uri", string.Empty); script = Extract(locationConfigDom, "/Config/script", string.Empty); host = IfExistsExtract(locationConfigDom, "Config/host", string.Empty); user = IfExistsExtract(locationConfigDom, "Config/user", string.Empty); password = IfExistsExtract(locationConfigDom, "Config/password", string.Empty); } }
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { message.EnsureFileOutboundTransport(); var location = Path.GetDirectoryName(message.GetProperty(BtsProperties.OutboundTransportLocation)); if (ImpersonationEnabled) { if (_logger.IsDebugEnabled) { _logger.Debug("Impersonating file adapter's configured user to create directory."); } Delegate.InvokeAs( message.GetProperty(FileProperties.Username), message.GetProperty(FileProperties.Password), () => CreateDirectory(location)); } else { CreateDirectory(location); } return(message); }
IBaseMessage IComponent.Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string json; Trace.WriteLine("JsonToXmlConverter Pipeline - Entered Execute()"); Trace.WriteLine(String.Format("JsonToXmlConverter Pipeline - RootNode: {0}", Rootnode)); var originalStream = pInMsg.BodyPart.GetOriginalDataStream(); using (TextReader reader = new StreamReader(originalStream)) { json = reader.ReadToEnd(); } Trace.WriteLine(String.Format("JsonToXmlConverter Pipeline - Read JSON Data: {0}", json)); Trace.WriteLine(String.Format("JsonToXmlConverter Pipeline - Deserializing JSON to Xml...")); try { // Append deserialized Xml data to master root node. XmlDocument xmlDoc = !string.IsNullOrWhiteSpace(Rootnode) ? JsonConvert.DeserializeXmlNode(json, Rootnode) : JsonConvert.DeserializeXmlNode(json); Trace.WriteLine(String.Format("JsonToXmlConverter Pipeline - Xml: {0}", xmlDoc.InnerXml)); var output = Encoding.ASCII.GetBytes(xmlDoc.InnerXml); var memoryStream = new MemoryStream(); memoryStream.Write(output, 0, output.Length); memoryStream.Position = 0; pInMsg.BodyPart.Data = memoryStream; } catch (Exception ex) { Trace.WriteLine(String.Format("JsonToXmlConverter Pipeline - Exception: {0}", ex.Message)); } pInMsg.BodyPart.Data.Position = 0; return(pInMsg); }
public static void ShowMessage(IBaseMessage message, TestContext testContext, bool asXml = true) { testContext.WriteLine("-------------------"); for (int i = 0; i < message.Context.CountProperties; i++) { string strName; string strNamespace; var value = message.Context.ReadAt(i, out strName, out strNamespace); testContext.WriteLine("{1} - {0} = {2}", strName, strNamespace, value); } testContext.WriteLine("-------------------"); if (asXml) { // Show the intermediate result var reader = XmlReader.Create(message.BodyPart.Data); { using (StringWriter writer = new StringWriter()) { XmlTextWriter xmlWriter = new XmlTextWriter(writer) { //set formatting options Formatting = Formatting.Indented, Indentation = 1, IndentChar = '\t' }; //write the document formatted xmlWriter.WriteNode(reader, true); testContext.WriteLine(writer.ToString()); } testContext.WriteLine("-------------------"); } } else { var reader = new StreamReader(message.BodyPart.Data); testContext.WriteLine(reader.ReadToEnd()); testContext.WriteLine("-------------------"); } }
private void OnSendButton(object param) { if (param is string) { string str = (string)param; if (string.IsNullOrEmpty(str)) { Debug.LogErrorFormat("OnSendButton str IsNullOrEmpty"); return; } MsgPerson p = new MsgPerson(); p.Name = "huangqiaoping_hahaha"; p.Email = "*****@*****.**"; p.Id = 222; IBaseMessage msg = ReceiverHelper.PopMessage(); msg.WriteIn(p, DefineProtobuf.MSG_PERSON); CoreModules.netMDL.SendMessage(msg); Debug.LogErrorFormat("OnSendButton str = {0}", str); } }
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { if (TrackingModes != ActivityTrackingModes.None) { message = _defaultActivityTracker.Execute(pipelineContext, message); var markableForwardOnlyEventingReadStream = message.BodyPart.WrapOriginalDataStream( originalStream => originalStream.AsMarkable(), pipelineContext.ResourceTracker); var probe = markableForwardOnlyEventingReadStream.ProbeBatchContent(); var batchDescriptor = probe.BatchDescriptor; if (batchDescriptor != null && !batchDescriptor.EnvelopeSpecName.IsNullOrEmpty()) { if (_logger.IsDebugEnabled) { _logger.DebugFormat( "Tracking batch release process for envelope '{0}' and partition '{1}'.", batchDescriptor.EnvelopeSpecName, batchDescriptor.Partition ?? "[null]"); } var batchTrackingContext = probe.BatchTrackingContext; BatchReleaseProcessActivityTracker.Create(pipelineContext, message).TrackActivity(batchTrackingContext); message.SetProperty(TrackingProperties.Value1, batchDescriptor.EnvelopeSpecName); message.SetProperty(TrackingProperties.Value2, batchDescriptor.EnvironmentTag); message.SetProperty(TrackingProperties.Value3, batchDescriptor.Partition); } else { if (_logger.IsInfoEnabled) { _logger.Debug("Tracking of batch release process is skipped for non batch message."); } } markableForwardOnlyEventingReadStream.StopMarking(); } return(message); }
// This is for submit-response protected override void SubmitSuccess(IBaseMessage message, Int32 hrStatus, object userData) { if (this.batchFailed) { // Previous submit operation might have moved the stream position // Seek the stream position back to zero before submitting again! IBaseMessage solicit = userData as IBaseMessage; if (solicit == null) { throw new InvalidOperationException("Response message does not have corresponding request message"); } IBaseMessagePart responseBodyPart = message.BodyPart; if (responseBodyPart != null) { Stream stream = responseBodyPart.GetOriginalDataStream(); stream.Position = 0; } this.batch.SubmitResponseMessage(solicit, message); } }
public IBaseMessage Execute(IPipelineContext pipelineContext, IBaseMessage message) { var customBrokeredMessagePropertyNamespace = message.GetProperty(SBMessagingProperties.CustomBrokeredMessagePropertyNamespace) ?? throw new InvalidOperationException($"{nameof(CustomBrokeredMessagePropertyNamespace)} has no value defined in SB-Messaging adapter configuration."); if (message.Direction().IsInbound()) { var correlationId = message.GetProperty(SBMessagingProperties.CorrelationId); // use the native BTS API instead of the message.PromoteCorrelationId(correlationId) to have no dependency on // BizTalk.Schemas which would reversed the desired dependency order, i.e. from an artifact component // (BizTalk.Schemas) to a runtime one (BizTalk.Pipeline.MicroComponents itself) if (!correlationId.IsNullOrEmpty()) { message.Context.Promote(nameof(SBMessagingProperties.CorrelationId), PropertySchemaNamespaces.BizTalkFactory, correlationId); } var messageType = (string)message.Context.Read(nameof(BizTalkFactoryProperties.MessageType), customBrokeredMessagePropertyNamespace); if (!messageType.IsNullOrEmpty()) { message.Promote(BtsProperties.MessageType, messageType); } } else { // use the native BTS API instead of the message.GetProperty(BizTalkFactoryProperties.CorrelationId) to have no // dependency on BizTalk.Schemas which would reversed the desired dependency order, i.e. from an artifact component // (BizTalk.Schemas) to a runtime one (BizTalk.Pipeline.MicroComponents itself) var correlationId = (string)message.Context.Read(nameof(SBMessagingProperties.CorrelationId), BizTalkFactoryProperties.MessageType.Namespace); if (!correlationId.IsNullOrEmpty()) { message.SetProperty(SBMessagingProperties.CorrelationId, correlationId); } var messageType = message.GetOrProbeMessageType(pipelineContext); if (!messageType.IsNullOrEmpty()) { message.Context.Write(nameof(BizTalkFactoryProperties.MessageType), customBrokeredMessagePropertyNamespace, messageType); } } return(message); }
public static void CopyMessageParts(IPipelineContext pc, IBaseMessage inmsg, IBaseMessage outmsg, IBaseMessagePart bodyPart, bool allowUnrecognizeMessage) { string bodyPartName = inmsg.BodyPartName; for (int i = 0; i < inmsg.PartCount; i++) { string partName = null; IBaseMessagePart partByIndex = inmsg.GetPartByIndex(i, out partName); if ((partByIndex == null) && !allowUnrecognizeMessage) { throw new ArgumentNullException("otherOutPart[" + i + "]"); } if (bodyPartName != partName) { outmsg.AddPart(partName, partByIndex, false); } else { outmsg.AddPart(bodyPartName, bodyPart, true); } } }
public void Execute(ref IBaseMessage inmsg, IPipelineContext pc) { System.IO.StreamReader reader = new System.IO.StreamReader(inmsg.BodyPart.GetOriginalDataStream()); VirtualStream updatedStream = new VirtualStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(updatedStream, reader.CurrentEncoding); writer.AutoFlush = true; pc.ResourceTracker.AddResource(reader); pc.ResourceTracker.AddResource(updatedStream); pc.ResourceTracker.AddResource(writer); while (!reader.EndOfStream) { string body = reader.ReadLine(); foreach (KeyValuePair <string, string> kp in stringReplaceCollection) { body = body.Replace(kp.Key, kp.Value); } foreach (KeyValuePair <string, string> kp in regexReplaceCollection) { body = Regex.Replace(body, kp.Key, kp.Value); } if (reader.EndOfStream) { writer.Write(body); } else { writer.WriteLine(body); } } updatedStream.Position = 0; inmsg.BodyPart.Data = updatedStream; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } try { var attachmentFileName = ContextExtensions.Read(pInMsg.Context, new ContextProperty(PropertyPath)); pInMsg.BodyPart.PartProperties.Write("FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", attachmentFileName); } catch (Exception ex) { EventLog.WriteEntry("SetEmailAttachmentFilename", ex.Message, EventLogEntryType.Error); throw new Exception(ex.Message); } return pInMsg; }
/// <summary> /// Implementation for AsyncTransmitterEndpoint::ProcessMessage /// Transmit the message and optionally return the response message (for Request-Response support) /// </summary> public override IBaseMessage ProcessMessage(IBaseMessage message) { Stream source = message.BodyPart.Data; byte[] content = null; using (var memoryStream = new MemoryStream()) { source.CopyTo(memoryStream); content = memoryStream.ToArray(); } // build url GrabCasterTransmitProperties props = new GrabCasterTransmitProperties(message, propertyNamespace); var idComponent = message.Context.Read(PROP_IDCOMPONENT, PROP_NAMESPACE); var idConfiguration = message.Context.Read(PROP_IDCONFIGURATION, PROP_NAMESPACE); var pointName = message.Context.Read(PROP_POINTNAME, PROP_NAMESPACE); if (idComponent != null && idConfiguration != null) { GrabCaster.Framework.Library.Embedded.ExecuteTrigger( idConfiguration.ToString(), idComponent.ToString(), content); } else { GrabCaster.Framework.Library.Embedded.ExecuteTrigger( props.IdConfiguration, props.IdComponent, content); } //GrabCaster.Framework.Library.Embedded.ExecuteTrigger( // "{82208FAA-272E-48A7-BB5C-4EACDEA538D2}", // "{306DE168-1CEF-4D29-B280-225B5D0D76FD}", // content); return(null); }
/// <summary> /// Copy over all parts of the message from a source message to a destination message, choosing which part should be the body part /// </summary> private void CopyMessageParts(IBaseMessage sourceMessage, IBaseMessage destinationMessage, IBaseMessagePart newBodyPart) { //Explicitly clear the collection in case this has gone through a disassembler with multiple messages and there are leftovers from the last time partNames.Clear(); string bodyPartName = sourceMessage.BodyPartName; for (int partCounter = 0; partCounter < sourceMessage.PartCount; ++partCounter) { string partName = null; IBaseMessagePart messagePart = sourceMessage.GetPartByIndex(partCounter, out partName); partNames.Add(partCounter, partName); if (partName != bodyPartName) { destinationMessage.AddPart(partName, messagePart, false); } else { destinationMessage.AddPart(bodyPartName, newBodyPart, true); } } }
/// <summary> /// Gets the next message from the message set resulting from the disassembler execution. /// </summary> /// <param name="pipelineContext"> /// The IPipelineContext containing the current pipeline context. /// </param> /// <returns> /// A pointer to the IBaseMessage containing the next message from the disassembled document. /// Returns NULL if there are no more messages left. /// </returns> public IBaseMessage GetNext(IPipelineContext pipelineContext) { while (true) { // Check to see see if we have just processed a mediated message. if (this.currentMediatedMessage == null) { // If not, get the next disassembled XML message this.currentXmlMessage = this.btfDasmComp.GetNext(pipelineContext); // If there are no further disassembled XML messages, return null. if (this.currentXmlMessage == null) { return(null); } // Indicate that we have just got the next flat file message by ensuring that // the service mediation component is null. this.serviceMediationDasmNoFurtherMessages = true; } // Check if we have just got the next flat file message. If so, create and initialise // a new service mediation component. if (this.serviceMediationDasmNoFurtherMessages) { this.InitialiseServiceMediation(); this.serviceMediationDasm.Disassemble(pipelineContext, this.currentXmlMessage); } // Get the next mediated message this.currentMediatedMessage = this.serviceMediationDasm.GetNext(pipelineContext); // If a mediated message was found, return it. if (this.currentMediatedMessage != null) { return(this.currentMediatedMessage); } } }
/// <summary> /// Executes the receive pipeline /// </summary> /// <param name="inputMessage">Input message to feed to the pipeline</param> /// <returns>A collection of messages that were generated by the pipeline</returns> public MessageCollection Execute(IBaseMessage inputMessage) { if ( inputMessage == null ) throw new ArgumentNullException("inputMessage"); Pipeline.InputMessages.Add(inputMessage); MessageCollection output = new MessageCollection(); Pipeline.Execute(Context); IBaseMessage om = null; while ( (om = Pipeline.GetNextOutputMessage(Context)) != null ) { output.Add(om); // we have to consume the entire stream for the body part. // Otherwise, the disassembler might enter an infinite loop. // We currently copy the output into a new memory stream if ( om.BodyPart != null && om.BodyPart.Data != null ) { om.BodyPart.Data = CopyStream(om.BodyPart.Data); } } return output; }
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; }
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg) { string errorMessage; if (!Validate(out errorMessage)) { throw new ArgumentException(errorMessage); } var encryptionKey = Convert.FromBase64String(EncryptionKey); var ms = new MemoryStream(); using (var provider = new AesCryptoServiceProvider()) { provider.Key = encryptionKey; provider.Mode = CipherMode.CBC; provider.Padding = PaddingMode.PKCS7; using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV)) { ms.Write(provider.IV, 0, 16); var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); pInMsg.BodyPart.GetOriginalDataStream().CopyTo(cs); cs.FlushFinalBlock(); } } ms.Seek(0, SeekOrigin.Begin); ms.Position = 0; pInMsg.BodyPart.Data = ms; return pInMsg; }