/// <summary> /// called by the messaging engine when a new message arrives /// checks if the incoming message is in a recognizable format /// if the message is in a recognizable format, only this component /// within this stage will be execute (FirstMatch equals true) /// </summary> /// <param name="pc">the pipeline context</param> /// <param name="inmsg">the actual message</param> public bool Probe(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { // // TODO: check whether you're interested in the given message // return(true); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { string ActivityID = Guid.NewGuid().ToString(); string ShareLocation = "D:\\Share\\TrackingArchive\\"; // Should be an UNC Path with desired access granted to the User Account string FileExtension = ".txt"; string FullFilePath = ShareLocation + ActivityID + FileExtension; StringBuilder SBContext = new StringBuilder(); ReadOnlySeekableStream stream = new ReadOnlySeekableStream(inmsg.BodyPart.GetOriginalDataStream()); Stream sourceStream = inmsg.BodyPart.GetOriginalDataStream(); if (!sourceStream.CanSeek) { ReadOnlySeekableStream seekableStream = new ReadOnlySeekableStream(sourceStream); inmsg.BodyPart.Data = seekableStream; sourceStream = inmsg.BodyPart.Data; } if (inmsg.BodyPart != null) { VirtualStream virtualStream = new VirtualStream(sourceStream); PipelineHelper.ArchiveToFileLocation(virtualStream, FullFilePath); PipelineHelper.ArchivetoStorage(pc, inmsg, FullFilePath, true); sourceStream.Position = 0; inmsg.BodyPart.Data = sourceStream; inmsg.BodyPart.Data.Position = 0; } return(inmsg); #endregion }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { inmsg.BodyPart.Data = new WindowsNewLineStream( inmsg.BodyPart.GetOriginalDataStream()); return(inmsg); }
//Get the list of stream types that require reading before the pipeline executes from the pipeline parameters and read a character from the stream //to ensure that the stream reading logic gets exercised (especially important if the stream in question writes to the message context such as in //the case of the Microsoft.BizTalk.Component.XmlDasmStreamWrapper) private void ReadStreamIfNecessary(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg, IBaseMessagePart copiedBodyPart, string streamType) { if (!string.IsNullOrEmpty(streamsToReadBeforeExecution)) { streamsToReadBeforeExecution.Replace(" ", ""); List<string> streamsToReadBeforeExecutionList = new List<string>(streamsToReadBeforeExecution.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)); if (streamsToReadBeforeExecutionList.Contains(streamType)) { TraceManager.PipelineComponent.TraceInfo("{0} - Reading stream to ensure it's read logic get's executed prior to pipeline component execution", callToken); StreamReader reader = new StreamReader(copiedBodyPart.Data); reader.Read(); pc.ResourceTracker.AddResource(reader); copiedBodyPart.Data.Position = 0; } else { TraceManager.PipelineComponent.TraceInfo("{0} - No need to read stream as stream type does not match entries in StreamsToReadBeforeExecution parameter", callToken); } } else { TraceManager.PipelineComponent.TraceInfo("{0} - No need to read stream as there are no entries in StreamsToReadBeforeExecution parameter", callToken); } }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { /************************************************************************************************************************* * This component will read the MessageType from the Message Context Properties. * * BTS.MessageType: Specifies the type of the message. The message type is defined as a concatenation of document * * schema namespace and document root node: http://<MyNamespace>#<MyRootNode>. * * and will promote the Operation property based on the content on the Root node "<MyRootNode>" specified on the * * message type "http://<MyNamespace>#<MyRootNode>" of the message. * * * * Ex: Message Type = "http://schemas.integration.com#GetClientInfo" * * Operation will be defined as "GetClientInfo" * ************************************************************************************************************************/ // Note: // System properties are mostly used internally by BizTalk Messaging Engine and its components. // In general, changing the values set by the engine for those properties is not recommended, because it may affect // the execution logic of the engine. However, there are a large number of properties that you can change. string msgType = Convert.ToString(inmsg.Context.Read("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties")); string operation = msgType.Substring(msgType.LastIndexOf('#') + 1); inmsg.Context.Promote("Operation", "http://schemas.microsoft.com/BizTalk/2003/system-properties", operation); return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { // // TODO: implement component logic // // this way, it's a passthrough pipeline component IBaseMessageContext context = inmsg.Context; Stream inStream = inmsg.BodyPart.Data; XslTransmitHelper transmit = new XslTransmitHelper(this.XslPath, this.XPathSourceFileName, this.EnableValidateNamespace, this.AllowPassThruTransmit); if (!string.IsNullOrEmpty(this.XPathSourceFileName)) { string sourceFileName = transmit.GetSourceFileName(XmlReader.Create(inStream), this.XPathSourceFileName); if (!string.IsNullOrEmpty(sourceFileName)) { context.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourceFileName); context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourceFileName); } inStream.Seek(0, SeekOrigin.Begin); } var outStream = transmit.Transmit(inStream); inmsg.BodyPart.Data = outStream; pc.ResourceTracker.AddResource(outStream); return(inmsg); }
/// <summary> /// called by the messaging engine when a new message arrives /// </summary> /// <param name="pc">the pipeline context</param> /// <param name="inmsg">the actual message</param> public void Disassemble(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { // // TODO: implement message retrieval logic IBaseMessagePart Body = inmsg.BodyPart; if (Body != null) { Stream originalStream = Body.GetOriginalDataStream(); if (originalStream != null) { var xml = XElement.Load(originalStream); var rootElement = xml.Name; // Child elements from source file to split by. var childNodes = xml.Descendants(this.DescendantElement); // This is the total number of elements to be sliced up into // separate files. int cnt = childNodes.Count(); var skip = 0; var take = this.BatchSize; var fileno = 0; // Split elements into chunks and save to disk. while (skip < cnt) { // Extract portion of the xml elements. var c1 = childNodes .Skip(skip) .Take(take); // Setup number of elements to skip on next iteration. skip += take; // File sequence no for split file. fileno += 1; // Filename for split file. // Create a partial xml document. XElement frag = new XElement(rootElement, c1); // Save to disk. var newStream = new MemoryStream(); frag.Save(newStream); newStream.Position = 0; pc.ResourceTracker.AddResource(newStream); IBaseMessage newmsg = pc.GetMessageFactory().CreateMessage(); newmsg.AddPart("Body", pc.GetMessageFactory().CreateMessagePart(), true); newmsg.BodyPart.Data = newStream; newmsg.Context = PipelineUtil.CloneMessageContext(inmsg.Context); //outMsg.Context.Promote("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", "Namespace#Root"); var msgtype = (string.IsNullOrEmpty(rootElement.Namespace.NamespaceName)?"" : rootElement.Namespace.NamespaceName + "#") + rootElement.LocalName; newmsg.Context.Write("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", msgtype); newmsg.Context.Promote("MessageType", "http://schemas.microsoft.com/BizTalk/2003/system-properties", msgtype); _msgs.Enqueue(newmsg); } } } }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { inmsg.BodyPart.Data = new InsertLargeDataTranslatorStream(XmlReader.Create(inmsg.BodyPart.GetOriginalDataStream())) { LargeDataNodeName = _LargeDataNodeName }; return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage ExecuteFour(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { Stream dataStream = new VirtualStream(VirtualStream.MemoryFlag.AutoOverFlowToDisk); pc.ResourceTracker.AddResource(dataStream); using (XmlWriter writer = XmlWriter.Create(dataStream)) { // Start creating the message body writer.WriteStartDocument(); //writer.WriteStartElement("ns0", ROOT_NODE_NAME, TARGET_NAMESPACE); for (int i = 0; i < inmsg.Context.CountProperties; i++) { // Read in current property information string propName = null; string propNamespace = null; object propValue = inmsg.Context.ReadAt(i, out propName, out propNamespace); // Skip properties that we don't care about due to configuration (default is to allow all properties) //if (ExcludeSystemProperties && propNamespace == SYSTEM_NAMESPACE) continue; //if (!String.IsNullOrWhiteSpace(CustomPropertyNamespace) && // propNamespace != CustomPropertyNamespace) continue; // Create Property element //writer.WriteStartElement(PROPERTY_NODE_NAME); //// Create attributes on Property element //writer.WriteStartAttribute(NAMESPACE_ATTRIBUTE); //writer.WriteString(propNamespace); //writer.WriteEndAttribute(); //writer.WriteStartAttribute(NAME_ATTRIBUTE); writer.WriteString(propName); writer.WriteEndAttribute(); // Write value inside property element writer.WriteString(Convert.ToString(propValue)); writer.WriteEndElement(); } // Finish out the message writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); } dataStream.Seek(0, SeekOrigin.Begin); IBaseMessage outmsg = null;// = Utility.CloneMessage(inmsg, pc); //outmsg.BodyPart.Data = dataStream; return(outmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { var readyWarehouseId = RushOrderHelper.WarehouseFinder.GetNextReadyWarehouse(); inmsg.Context.Promote(WAREHOUSE_ID_PROPERTY_NAME, WAREHOUSE_ID_PROPERTY_NAMESPACE, readyWarehouseId); return(inmsg); }
/// <summary> /// called by the messaging engine until returned null, after disassemble has been called /// </summary> /// <param name="pc">the pipeline context</param> /// <returns>an IBaseMessage instance representing the message created</returns> public Microsoft.BizTalk.Message.Interop.IBaseMessage GetNext(Microsoft.BizTalk.Component.Interop.IPipelineContext pc) { // get the next message from the Queue and return it Microsoft.BizTalk.Message.Interop.IBaseMessage msg = null; if ((_msgs.Count > 0)) { msg = ((Microsoft.BizTalk.Message.Interop.IBaseMessage)(_msgs.Dequeue())); } return(msg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { IBaseMessage baseMessage = inmsg; string eventSource = "ProcessEmptyMessage Pipeline Component"; // if message isn't empty if (baseMessage.BodyPart.Data.Length != (long)0) { // not empty if (!string.IsNullOrEmpty(this.ContextPropertyName) && !string.IsNullOrEmpty(this.ContextPropertyNamespace)) { try { baseMessage.Context.Promote(this.ContextPropertyName, this.ContextPropertyNamespace, false); } catch (Exception e) { System.Diagnostics.EventLog.WriteEntry(eventSource, e.Message, EventLogEntryType.Error); } } } else { // if there is something to replace if (!string.IsNullOrEmpty(this.DefaultMessage)) { char NewLine = (char)0x0A; char CariageReturn = (char)0x0D; MemoryStream memoryStream = new MemoryStream(Encoding.GetEncoding(1252).GetBytes(this.DefaultMessage.Replace(@"\r", CariageReturn.ToString()).Replace(@"\n", NewLine.ToString()))); memoryStream.Flush(); memoryStream.Position = (long)0; baseMessage.BodyPart.Data = memoryStream; } // if we should promote the property that will indicate if this file is empty or not if (!string.IsNullOrEmpty(this.ContextPropertyName) && !string.IsNullOrEmpty(this.ContextPropertyNamespace)) { try { baseMessage.Context.Promote(this.ContextPropertyName, this.ContextPropertyNamespace, true); } catch (Exception e) { System.Diagnostics.EventLog.WriteEntry(eventSource, e.Message, EventLogEntryType.Error); } } } return(baseMessage); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { // // TODO: implement component logic // // this way, it's a passthrough pipeline component if (this.PerformBackup) { try { //Get Message Id Guid msgId = inmsg.MessageID; //Get Filename by FileAdapter NS string fileName = inmsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString(); if (string.IsNullOrEmpty(fileName)) { fileName = inmsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/ftp-properties").ToString(); if (string.IsNullOrEmpty(fileName)) { fileName = msgId.ToString(); } } if (!new DirectoryInfo(this.Folder).Exists) { try { Directory.CreateDirectory(this.Folder); } catch { throw; } } SaveStreamToFile(inmsg.BodyPart.Data, fileName, true); inmsg.BodyPart.Data.Position = 0; } catch { throw; } } return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { int PartCount = inmsg.PartCount; string BodyPartName = inmsg.BodyPartName; try { for (int i = 0; i < inmsg.PartCount; i++) { string PartName; IBaseMessagePart CurrentPart = inmsg.GetPartByIndex(i, out PartName); if (!PartName.Equals(BodyPartName)) { Stream CurrentPartSource = CurrentPart.GetOriginalDataStream(); byte[] CurrentPartBuffer = new byte[CurrentPartSource.Length]; CurrentPartSource.Read(CurrentPartBuffer, 0, CurrentPartBuffer.Length); byte[] CompressedPartBuffer; using (MemoryStream TempStream = new MemoryStream()) { using (GZipStream CompressedStream = new GZipStream(TempStream, CompressionMode.Compress, true)) { CompressedStream.Write(CurrentPartBuffer, 0, CurrentPartBuffer.Length); CompressedStream.Close(); } CompressedPartBuffer = TempStream.ToArray(); } MemoryStream TempCompressedStream = new MemoryStream(CompressedPartBuffer); inmsg.GetPartByIndex(i, out PartName).Data = TempCompressedStream; string PropertyName = "FileName"; string PropertySchema = "http://schemas.microsoft.com/BizTalk/2003/mime-properties"; string SourcePartName = inmsg.GetPartByIndex(i, out PartName).PartProperties.Read(PropertyName, PropertySchema).ToString(); SourcePartName += ".gz"; inmsg.GetPartByIndex(i, out PartName).PartProperties.Write("FileName", PropertySchema, SourcePartName); } } } catch (Exception Exception) { //Exception.Message; } return(inmsg); }
/// <summary> /// Instantiate facts that will be used by the InstructionLoaderPolicy /// </summary> private void InstantiateInstructionLoaderPolicyFacts(Microsoft.BizTalk.Component.Interop.IPipelineContext pc) { documentWrapper = new TypedXMLDocumentWrapper(_BREPipelineMetaInstructionCollection.InMsg.BodyPart.GetOriginalDataStream(), pc); sqlConnectionCollection = new SQLDataConnectionCollection(); object property = _BREPipelineMetaInstructionCollection.InMsg.Context.Read("MessageType", ContextPropertyNamespaces._BTSPropertyNamespace); if (property != null) { utility = new MessageUtility(_BREPipelineMetaInstructionCollection.InMsg.BodyPart.GetOriginalDataStream(), property.ToString(), pc); } else { utility = new MessageUtility(_BREPipelineMetaInstructionCollection.InMsg.BodyPart.GetOriginalDataStream(), pc); } }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { if (string.IsNullOrEmpty(_receiverId) || string.IsNullOrEmpty(_senderId)) { return(inmsg); } try { // Set the identificators inmsg.Context.Promote("UNB2_1", _edifactPropertyNamespace, inmsg.Context.Read(_senderId, _propertyNameSpace)); inmsg.Context.Promote("UNB3_1", _edifactPropertyNamespace, inmsg.Context.Read(_receiverId, _propertyNameSpace)); // If no qualifier is set in pipeline use " " since that will resolve as <no qualifier> in Biztalk. if (string.IsNullOrEmpty(_senderIdQualifier)) { inmsg.Context.Promote("UNB2_2", _edifactPropertyNamespace, " "); } else { inmsg.Context.Promote("UNB2_2", _edifactPropertyNamespace, inmsg.Context.Read(_senderIdQualifier, _propertyNameSpace)); } // If no qualifier is set in pipeline use " " since that will resolve as <no qualifier> in Biztalk. if (string.IsNullOrEmpty(_receiverIdQualifier)) { inmsg.Context.Promote("UNB3_2", _edifactPropertyNamespace, " "); } else { inmsg.Context.Promote("UNB3_2", _edifactPropertyNamespace, inmsg.Context.Read(_receiverIdQualifier, _propertyNameSpace)); } } catch { throw; } return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { Stream originalStrm = null; FileStream fileArchive = null; BinaryWriter binWriter = null; const int bufferSize = 1024; try { IBaseMessagePart bodyPart = inmsg.BodyPart; if (bodyPart != null) { string path = filePath + "." + fileExtension; path = path.Replace("%MessageID%", inmsg.MessageID.ToString()); originalStrm = bodyPart.GetOriginalDataStream(); fileArchive = new FileStream(path, FileMode.Create, FileAccess.Write); binWriter = new BinaryWriter(fileArchive); byte[] buffer = new byte[bufferSize]; int sizeRead = 0; while ((sizeRead = originalStrm.Read(buffer, 0, bufferSize)) != 0) { binWriter.Write(buffer, 0, sizeRead); } } } catch (Exception ex) { System.Diagnostics.EventLog.WriteEntry(ex.Source, ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error); } finally { if (binWriter != null) { binWriter.Flush(); binWriter.Close(); } originalStrm.Seek(0, SeekOrigin.Begin); } return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { var callToken = TraceManager.PipelineComponent.TraceIn(); TraceManager.PipelineComponent.TraceInfo(string.Format("{0} - {1} - START StreamingGood pipeline component.", System.DateTime.Now, callToken)); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); if (Enabled) { try { Stream bodyPartStream = inmsg.BodyPart.GetOriginalDataStream(); Base64EncoderStream newStream = new Base64EncoderStream(bodyPartStream, BufferSizeBytes); inmsg.BodyPart.Data = newStream; pc.ResourceTracker.AddResource(newStream); // Rewind output stream to the beginning, so it's ready to be read. inmsg.BodyPart.Data.Position = 0; } catch (Exception ex) { TraceManager.PipelineComponent.TraceError(ex, true, callToken); if (inmsg != null) { inmsg.SetErrorInfo(ex); } throw; } } stopwatch.Stop(); TraceManager.PipelineComponent.TraceInfo(string.Format("{0} - {1} - Stopwatch elapsed time = {2}", System.DateTime.Now, callToken, stopwatch.Elapsed)); TraceManager.PipelineComponent.TraceInfo(string.Format("{0} - {1} - END - StreamingGood pipeline component. Return.", System.DateTime.Now, callToken)); TraceManager.PipelineComponent.TraceOut(callToken); return(inmsg); }
/// <summary> /// Setup the BREPipelineMetaInstructionCollection by copying over the body and context from the input message /// </summary> private void SetupBREPipelineMetaInstructionCollection(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { _BREPipelineMetaInstructionCollection = new BREPipelineMetaInstructionCollection(_XMLFactsApplicationStage, instructionExecutionOrder, partNames, callToken); _BREPipelineMetaInstructionCollection.Pc = pc; // Create a copy of the original body part and copy over it's properties as well IBaseMessagePart copiedBodyPart = pc.GetMessageFactory().CreateMessagePart(); string streamType = inmsg.BodyPart.Data.GetType().ToString(); TraceManager.PipelineComponent.TraceInfo("{0} - Inbound message body had a stream type of {1}", callToken, streamType); // If the input stream is not seekable then wrap it with a ReadOnlySeekableStream so that it can have it's position set if (!inmsg.BodyPart.GetOriginalDataStream().CanSeek) { TraceManager.PipelineComponent.TraceInfo("{0} - Inbound message body stream was not seekable so wrapping it with a ReadOnlySeekableStream", callToken); ReadOnlySeekableStream seekableDataStream = new ReadOnlySeekableStream(inmsg.BodyPart.GetOriginalDataStream()); originalStream = seekableDataStream; pc.ResourceTracker.AddResource(seekableDataStream); } else { TraceManager.PipelineComponent.TraceInfo("{0} - Inbound message body stream was seekable so no need to wrap it", callToken); originalStream = inmsg.BodyPart.GetOriginalDataStream(); } //Explicitly set the stream position to 0 in case the position was shifted while referencing it originalStream.Position = 0; pc.ResourceTracker.AddResource(originalStream); copiedBodyPart.Data = originalStream; ReadStreamIfNecessary(pc, inmsg, copiedBodyPart, streamType); //Copy over part properties copiedBodyPart.PartProperties = inmsg.BodyPart.PartProperties; // Create a new message in the _BREPipelineMetaInstructionCollection and copy over the body and any additional parts _BREPipelineMetaInstructionCollection.InMsg = pc.GetMessageFactory().CreateMessage(); CopyMessageParts(inmsg, _BREPipelineMetaInstructionCollection.InMsg, copiedBodyPart); // Copy over context by reference, this is to ensure that context isn't lost if using an XML Disassembler prior to BRE component // and not reading the stream prior to cloning context _BREPipelineMetaInstructionCollection.InMsg.Context = inmsg.Context; }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { System.IO.Stream st = inmsg.BodyPart.GetOriginalDataStream(); System.IO.StreamReader reader = new System.IO.StreamReader(st); string body = reader.ReadToEnd(); body = body.Replace(_FindString, _ReplaceWith); System.IO.MemoryStream m = new System.IO.MemoryStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(m); writer.AutoFlush = true; writer.Write(body); m.Position = 0; inmsg.BodyPart.Data = m; reader.Close(); return(inmsg); }
/// <summary> /// If the BizTalk message in the _BREPipelineMetaInstructionCollection and/or it's body part are null then instantiate them and copy /// context over from the original message /// </summary> private void RecreateBizTalkMessageAndBodyPartIfNecessary(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { // If the BizTalk message has been nullified then create the message again and copy over the context from the original message if (_BREPipelineMetaInstructionCollection.InMsg == null) { TraceManager.PipelineComponent.TraceInfo("{0} - Instantiating the message since it was null and the pipeline component needs to assign the TypedXMLDocument to it.", callToken); _BREPipelineMetaInstructionCollection.InMsg = pc.GetMessageFactory().CreateMessage(); _BREPipelineMetaInstructionCollection.InMsg.Context = PipelineUtil.CloneMessageContext(inmsg.Context); } // If the message body part is null then instantiate it again so we can assign the typed xml document stream to it if (_BREPipelineMetaInstructionCollection.InMsg.BodyPart == null) { TraceManager.PipelineComponent.TraceInfo("{0} - Instantiating the message body part since it was null and the pipeline component needs to assign the TypedXMLDocument to it.", callToken); IBaseMessagePart messageBodyPart = pc.GetMessageFactory().CreateMessagePart(); _BREPipelineMetaInstructionCollection.InMsg.AddPart("Body", messageBodyPart, true); } }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { XmlDocument message = new XmlDocument(); message.Load(inmsg.BodyPart.Data); message.DocumentElement.RemoveAllAttributes(); XElement xElem = XElement.Load(new XmlNodeReader(message)); XElement xElemStripped = RemoveAllNamespaces(xElem); MemoryStream outStream = new MemoryStream(); xElemStripped.Save(outStream); outStream.Position = 0; inmsg.BodyPart.Data = outStream; return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { if (_ArchiveFiles) { string archiveFileName = inmsg.Context.Read(_FileNameProperty, _FileNamePropertyNamespace) as string; if (archiveFileName != null && !string.IsNullOrEmpty(archiveFileName)) { if (archiveFileName.Contains("\\")) { archiveFileName = archiveFileName.Substring(archiveFileName.LastIndexOf("\\") + 1); } ArchivingStream archivingStream = new ArchivingStream(inmsg.BodyPart.Data, _ArchivePath + "\\" + archiveFileName); pc.ResourceTracker.AddResource(archivingStream); inmsg.BodyPart.Data = archivingStream; } } return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { try { if (inmsg.BodyPart != null) //Verify the message is different from null { MemoryStream memStrm = new MemoryStream(); Stream originalStrm = inmsg.BodyPart.GetOriginalDataStream(); StreamReader sReader = new StreamReader(originalStrm, System.Text.Encoding.Default); string original = sReader.ReadToEnd(); StreamWriter swriter = new StreamWriter(memStrm, System.Text.Encoding.Default); //Modify message if (string.IsNullOrEmpty(original)) { swriter.Write(AppendedValue); swriter.Flush(); memStrm.Seek(0, System.IO.SeekOrigin.Begin); inmsg.BodyPart.Data = memStrm; pc.ResourceTracker.AddResource(memStrm); } else { swriter.Write(original); swriter.Flush(); memStrm.Seek(0, System.IO.SeekOrigin.Begin); inmsg.BodyPart.Data = memStrm; pc.ResourceTracker.AddResource(memStrm); } } } catch (Exception ex) { System.Diagnostics.EventLog.WriteEntry("IKT-Agder.Felles.PipelineComponents", "Occurred an error on validating the message: " + ex.Message + "\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error); throw (ex); } return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { XmlDocument message = new XmlDocument(); message.Load(inmsg.BodyPart.Data); string targetNS = this._TargetNamespace.Trim(); message.DocumentElement.SetAttribute("xmlns", targetNS); MemoryStream outStream = new MemoryStream(); message.Save(outStream); outStream.Position = 0; inmsg.BodyPart.Data = outStream; return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { var encodingIn = this._encodingIn; var encodingOut = this._encodingOut; var val = (object)inmsg.Context.Read(EncodingInProperty.Name.Name, EncodingInProperty.Name.Namespace); if ((val != null)) { encodingIn = Encoding.GetEncoding((string)val); } val = (object)inmsg.Context.Read(EncodingOutProperty.Name.Name, EncodingOutProperty.Name.Namespace); if ((val != null)) { encodingOut = Encoding.GetEncoding((string)val); } inmsg.BodyPart.Data = new TranscodingStream( inmsg.BodyPart.GetOriginalDataStream(), encodingOut, encodingIn); return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { /************************************************************************************************************************* * This component will read the Custom SOAPHeader from the Message Context Properties. * * The custom header name will be defined on the component configuration and we can read it from the targert * * http://schemas.microsoft.com/BizTalk/2003/SOAPHeader * * and will add the header in the OutboundCustomHeaders (used by the WCF-BasicHTTP Adapter) * * Specify the custom SOAP headers for outgoing messages. When this property is used, the property must have * * the <headers> element as the root element. All of the custom SOAP headers must be placed inside the * * <headers> element. * * If the custom SOAP header value is an empty string, you must assign <headers></headers> or <headers> to this* * property. * * * * Ex: BusinessServiceHeader with "http://schemas.microsoft.com/BizTalk/2003/SOAPHeader" namespace * ************************************************************************************************************************/ if (!string.IsNullOrEmpty(this.SOAPHeaderName)) { string soapHeader = Convert.ToString(inmsg.Context.Read(this.SOAPHeaderName, "http://schemas.microsoft.com/BizTalk/2003/SOAPHeader")); if (!string.IsNullOrEmpty(soapHeader)) { XDocument xdoc = XDocument.Parse(soapHeader); xdoc.Declaration = null; Console.WriteLine(xdoc.ToString().Replace(System.Environment.NewLine, "")); string outboundHeader = "<headers>" + xdoc.ToString().Replace(System.Environment.NewLine, "") + "</headers>"; inmsg.Context.Promote("IsDynamicSend", "http://schemas.microsoft.com/BizTalk/2003/system-properties", true); inmsg.Context.Write("OutboundCustomHeaders", "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties", outboundHeader); } } return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { var stream = GetSeekeableMessageStream(inmsg); EdifactCharacterSet targetCharSet; var syntax = inmsg.Context.Read("UNB1_1", "http://schemas.microsoft.com/BizTalk/2006/edi-properties") as string; if (syntax == null || Enum.TryParse <EdifactCharacterSet>(syntax, out targetCharSet) == false) { targetCharSet = _targetCharSet; } var result = new MemoryStream(); var settings = new XmlWriterSettings { Encoding = Encoding.UTF8, OmitXmlDeclaration = true }; var separators = _extraCharsToReplace.ToCharArray(); using (var reader = XmlReader.Create(stream)) using (var writer = XmlWriter.Create(result, settings)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, true); if (reader.IsEmptyElement) { writer.WriteEndElement(); } break; case XmlNodeType.Text: var value = reader.Value; var sb = new StringBuilder(); foreach (var c in value) { var step1 = c.Translate(targetCharSet, _fallbackChar); var step2 = separators.Contains(step1) ? _fallbackChar : step1; var step3 = this.Normalize && char.IsControl(step2) ? ' ' : step2; sb.Append(step3); } writer.WriteString(this.Normalize ? sb.ToString().Trim() : sb.ToString()); break; case XmlNodeType.EndElement: writer.WriteFullEndElement(); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: //writer.WriteProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.SignificantWhitespace: writer.WriteWhitespace(reader.Value); break; } } writer.Flush(); } result.Seek(0, SeekOrigin.Begin); inmsg.BodyPart.Data = result; pc.ResourceTracker.AddResource(result); return(inmsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pipelineContext, Microsoft.BizTalk.Message.Interop.IBaseMessage inputMsg) { System.Diagnostics.Debug.WriteLine("At top of Execute method for DBASE pipeline"); IBaseMessagePart bodyPart = inputMsg.BodyPart; if (bodyPart != null) { try { // First write the ODBC file to disk so can query it. BinaryReader binaryReader = new BinaryReader(bodyPart.Data); string folderName = this.TempDropFolderLocation; if (folderName.Substring(folderName.Length - 1, 1) != "\\") { folderName += "\\"; } string extension = (this.TypeToProcess == odbcType.Excel) ? ".xls" : ".dbf"; string filename = System.IO.Path.GetRandomFileName(); filename = filename.Remove(8); filename += extension; string folderNameAndFileName = folderName + filename; FileStream fileStream = new FileStream(folderNameAndFileName, FileMode.CreateNew); BinaryWriter binaryWriter = new BinaryWriter(fileStream); binaryWriter.Write(binaryReader.ReadBytes(Convert.ToInt32(binaryReader.BaseStream.Length))); binaryWriter.Close(); binaryReader.Close(); // Create the Connection String for the ODBC File string dataSource; if (this.TypeToProcess == odbcType.Excel) { dataSource = "Data Source=" + folderNameAndFileName + ";"; } else // dbf { dataSource = "Data Source=" + folderName + ";"; } string odbcConnectionString = this.connectionString; if (odbcConnectionString.Substring(odbcConnectionString.Length - 1, 1) != ";") { odbcConnectionString += ";"; } odbcConnectionString += dataSource; OleDbConnection oConn = new OleDbConnection(); oConn.ConnectionString = odbcConnectionString; // Create the Select Statement for the ODBC File OleDbDataAdapter oCmd; // Get the filter if there is one string whereClause = ""; if (Filter.Trim() != "") { whereClause = " Where " + Filter.Trim(); } if (this.TypeToProcess == odbcType.Excel) { oCmd = new OleDbDataAdapter(this.SqlStatement.Trim() + whereClause, oConn); } else // dbf { oCmd = new OleDbDataAdapter(this.SqlStatement.Trim() + " From " + filename + whereClause, oConn); } oConn.Open(); // Perform the Select statement from above into a dataset, into a DataSet. DataSet odbcDataSet = new DataSet(); oCmd.Fill(odbcDataSet, this.DataNodeName); oConn.Close(); // Delete the message if (this.DeleteTempMessages) { System.IO.File.Delete(folderNameAndFileName); } // Write the XML From this DataSet into a String Builder System.Text.StringBuilder stringBuilder = new StringBuilder(); System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder); odbcDataSet.Tables[0].WriteXml(stringWriter); System.Xml.XmlDocument fromDataSetXMLDom = new System.Xml.XmlDocument(); fromDataSetXMLDom.LoadXml(stringBuilder.ToString()); // Create the Final XML Document. Root Node Name and Target Namespace // come from properties set on the pipeline System.Xml.XmlDocument finalMsgXmlDom = new System.Xml.XmlDocument(); System.Xml.XmlElement xmlElement; xmlElement = finalMsgXmlDom.CreateElement("ns0", this.RootNodeName, this.NameSpace); finalMsgXmlDom.AppendChild(xmlElement); // Add the XML to the finalMsgXmlDom from the DataSet XML, // After this the XML Message will be complete finalMsgXmlDom.FirstChild.InnerXml = fromDataSetXMLDom.FirstChild.InnerXml; Stream strm = new MemoryStream(); // Save final XML Document to Stream finalMsgXmlDom.Save(strm); strm.Position = 0; bodyPart.Data = strm; pipelineContext.ResourceTracker.AddResource(strm); } catch (System.Exception ex) { throw ex; } } return(inputMsg); }
/// <summary> /// Implements IComponent.Execute method. /// </summary> /// <param name="pc">Pipeline context</param> /// <param name="inmsg">Input message</param> /// <returns>Original input message</returns> /// <remarks> /// IComponent.Execute method is used to initiate /// the processing of the message in this pipeline component. /// </remarks> public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg) { #region Copy input stream try { IBaseMessagePart bodyPart = inmsg.BodyPart; if (bodyPart != null) { Stream originalStream = bodyPart.GetOriginalDataStream(); // Biztalk will not do property promotion in time if we do not touch the stream. Seems to be a quirk of how the send pipeline works. // If original message is returned no property promotion will happen before the EDI assembler component gets the message. if (originalStream != null) { StreamReader sReader = new StreamReader(originalStream); VirtualStream vStream = new VirtualStream(); StreamWriter sWriter = new StreamWriter(vStream); //Write message body to a virutal memory stream sWriter.Write(sReader.ReadToEnd()); sWriter.Flush(); sReader.Close(); vStream.Seek(0, SeekOrigin.Begin); pc.ResourceTracker.AddResource(vStream); inmsg.BodyPart.Data = vStream; } } #endregion #region Property promotion // Set the identificators. Make sure to set " " if missing to get property promoted (will make Biztalk fail the file on missing party) if (string.IsNullOrEmpty((string)inmsg.Context.Read(_senderId, _propertyNameSpace))) { inmsg.Context.Promote("DestinationPartySenderIdentifier", _edifactPropertyNamespace, " "); } else { inmsg.Context.Promote("DestinationPartySenderIdentifier", _edifactPropertyNamespace, inmsg.Context.Read(_senderId, _propertyNameSpace)); } if (string.IsNullOrEmpty((string)inmsg.Context.Read(_receiverId, _propertyNameSpace))) { inmsg.Context.Promote("DestinationPartyReceiverIdentifier", _edifactPropertyNamespace, " "); } else { inmsg.Context.Promote("DestinationPartyReceiverIdentifier", _edifactPropertyNamespace, inmsg.Context.Read(_receiverId, _propertyNameSpace)); } // If no qualifier is set in pipeline use " " since that will resolve as <no qualifier> in Biztalk. if (string.IsNullOrEmpty(_senderIdQualifier)) { inmsg.Context.Promote("DestinationPartySenderQualifier", _edifactPropertyNamespace, " "); } else { // If no value is found on property set space as value (<No qualifier>) if (string.IsNullOrEmpty((string)inmsg.Context.Read(_senderIdQualifier, _propertyNameSpace))) { inmsg.Context.Promote("DestinationPartySenderQualifier", _edifactPropertyNamespace, " "); } else { inmsg.Context.Promote("DestinationPartySenderQualifier", _edifactPropertyNamespace, inmsg.Context.Read(_senderIdQualifier, _propertyNameSpace)); } } // If no qualifier is set in pipeline use " " since that will resolve as <no qualifier> in Biztalk. if (string.IsNullOrEmpty(_receiverIdQualifier)) { inmsg.Context.Promote("DestinationPartyReceiverQualifier", _edifactPropertyNamespace, " "); } else { // If no value is found on property set space as value (<No qualifier>) if (string.IsNullOrEmpty((string)inmsg.Context.Read(_receiverIdQualifier, _propertyNameSpace))) { inmsg.Context.Promote("DestinationPartyReceiverQualifier", _edifactPropertyNamespace, " "); } else { inmsg.Context.Promote("DestinationPartyReceiverQualifier", _edifactPropertyNamespace, inmsg.Context.Read(_receiverIdQualifier, _propertyNameSpace)); } } return(inmsg); #endregion } catch (Exception ex) { if (inmsg != null) { inmsg.SetErrorInfo(ex); } throw; } }