Beispiel #1
0
        /// <summary>
        /// Retrieve the contents of a message into a stream
        /// </summary>
        /// <param name="message"></param>
        /// <param name="bufferSize"></param>
        /// <param name="thresholdSize"></param>
        /// <returns></returns>
        public Stream ProcessRequestReturnStream(XLANGMessage message, int bufferSize, int thresholdSize)
        {
            Stream partStream = null;

            try
            {
                using (VirtualStream virtualStream = new VirtualStream(bufferSize, thresholdSize))
                {
                    using (partStream = (Stream)message[0].RetrieveAs(typeof(Stream)))

                        //Note that when calling this code, if the XmlDocument is quite large, keeping it in a memory with a MemoryStream may have an adverse effect on performance.
                        //In this case, it may be worthwhile to consider an approach that uses a VirtualStream + ReadonlySeekableStream to buffer it to the file system,
                        //if its size is bigger than the thresholdSize parameter.
                        //Keep in mind that:
                        // - If the message size is smaller than the threshold size, the VirtualStream class buffers the stream to a MemoryStream.
                        // - If the message size is bigger than the threshold size, the VirtualStream class buffers the stream to a temporary file.
                        using (ReadOnlySeekableStream readOnlySeekableStream = new ReadOnlySeekableStream(partStream, virtualStream, bufferSize))
                        {
                            using (XmlReader reader = XmlReader.Create(readOnlySeekableStream))
                            {
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                message.Dispose();
            }

            return(partStream);
        }
Beispiel #2
0
 /// <summary>
 /// Applies the XSL transformation specified by <paramref name="map"/> to the specified <paramref
 /// name="sourceMessage"/> and adds the result as a part named <paramref name="destinationPartName"/> to the
 /// <paramref name="destinationMessage"/> message.
 /// </summary>
 /// <param name="sourceMessage">
 /// The <see cref="XLANGMessage"/> to be transformed.
 /// </param>
 /// <param name="map">
 /// The type of the BizTalk map class containing the transform to apply.
 /// </param>
 /// <param name="destinationMessage">
 /// Message to hold the transformation results.
 /// </param>
 /// <param name="destinationPartName">
 /// Name of the message part that will be added to <paramref name="destinationMessage"/> and that contains the
 /// results of the transformation.
 /// </param>
 public static void TransformAndAddPart(XLANGMessage sourceMessage, Type map, XLANGMessage destinationMessage, string destinationPartName)
 {
     if (sourceMessage == null)
     {
         throw new ArgumentNullException("sourceMessage");
     }
     if (map == null)
     {
         throw new ArgumentNullException("map");
     }
     if (destinationMessage == null)
     {
         throw new ArgumentNullException("destinationMessage");
     }
     try
     {
         using (var xmlReader = new XmlTextReader(sourceMessage.AsStream()))
         {
             var response = Transform(xmlReader, map, null);
             destinationMessage.AddPart(string.Empty, destinationPartName);
             destinationMessage[destinationPartName].LoadFrom(response);
         }
     }
     finally
     {
         sourceMessage.Dispose();
     }
 }
Beispiel #3
0
 /// <summary>
 /// Retrieve the contents of simple .NET messages into a string
 /// </summary>
 /// <param name="message"></param>
 public void ConvertToString(XLANGMessage message)
 {
     try
     {
         string content = message[0].RetrieveAs(typeof(string)) as string;
         if (!string.IsNullOrWhiteSpace(content))
         {
         }
     }
     finally
     {
         message.Dispose();
     }
 }
Beispiel #4
0
 /// <summary>
 /// To process a message with an XmlReader instance,
 /// pass the message to .NET code as an XLANGMessage, and retrieve the Part content using XmlReader
 /// </summary>
 /// <param name="message"></param>
 public void ProcessMessage(XLANGMessage message)
 {
     try
     {
         using (XmlReader reader = message[0].RetrieveAs(typeof(XmlReader)) as XmlReader)
             if (reader != null)
             {
             }
     }
     finally
     {
         message.Dispose();
     }
 }
Beispiel #5
0
 /// <summary>
 /// Retrieve the contents of a message into a .NET object.
 /// This technique is valid only when messages are small. Otherwise, this approach could incur in a significant overhead
 /// to de-serialize the actual message into a .NET object
 /// </summary>
 /// <param name="message"></param>
 public void MessageToObject(XLANGMessage message)
 {
     try
     {
         Request request = message[0].RetrieveAs(typeof(Request)) as Request;
         if (request != null)
         {
         }
     }
     finally
     {
         message.Dispose();
     }
 }
Beispiel #6
0
        /// <summary>
        /// XmlDocument in orchestrations is to retrieve the message as an XML string using XmlDocument.OuterXml()
        /// Or using the following to
        /// retrieve the message as a string using an XLANGMessage variable
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string MessageToString(XLANGMessage message)
        {
            string strResults;

            try
            {
                using (Stream stream = message[0].RetrieveAs(typeof(Stream)) as Stream)
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        strResults = reader.ReadToEnd();
                    }
                }
            }
            finally
            {
                message.Dispose();
            }
            return(strResults);
        }
Beispiel #7
0
 /// <summary>
 /// Archives a message.
 /// </summary>
 /// <param name="message">The message to be archived.</param>
 /// <param name="expiryMinutes">The amount of time (in minutes) before the archived message expires and will be automatically deleted from the archive. Specify a value of 0 to use the default configured expiry time.</param>
 /// <param name="includeProperties">A flag indicating if properties should be archived along with the message.</param>
 /// <param name="tag">A tag value to be associated with the archived message.</param>
 /// <param name="autoDisposeXLangMessage">When called from an orchestration, this flag should be set to true to dispose XLANGMessage after use.</param>
 /// <returns>The id of the archived message.</returns>
 public string ArchiveMessage(XLANGMessage xLangMessage, int expiryMinutes, bool includeProperties, string tag, bool autoDisposeXLangMessage)
 {
     try
     {
         ArchiveTag            archiveTag     = new ArchiveTag(tag);
         ArchiveBizTalkMessage bizTalkMessage = new ArchiveBizTalkMessage(xLangMessage, archiveTag, false);
         messageId = bizTalkMessage.Message.MessageId.ToString();
         ArchiveMessageAsync(bizTalkMessage, expiryMinutes, includeProperties, archiveTag);
     }
     catch (Exception ex)
     {
         Logger.WriteWarning(string.Format("Error archiving a message {0} \r\n Details: {1}", this.GetType().Name, ex.ToString()), 14005);
     }
     finally
     {
         if (autoDisposeXLangMessage)
         {
             xLangMessage.Dispose();
         }
     }
     return(messageId);
 }
Beispiel #8
0
        /// <summary>
        /// Handle fault
        /// </summary>
        /// <param name="xlangMsg"></param>
        /// <param name="faultType"></param>
        public static void HandleFault(XLANGMessage xlangMsg, string btsMsgType, FaultType faultType)
        {
            string eventMessage       = string.Empty;
            string serviceName        = string.Empty;
            string serviceType        = string.Empty;
            string transportLocation  = string.Empty;
            string transportDirection = string.Empty;
            string description        = string.Empty;
            Stream faultStream        = null;;

            try
            {
                faultStream = (Stream)xlangMsg[0].RetrieveAs(typeof(Stream));

                if (faultType == FaultType.DeliveryException)
                {
                    serviceName = GetMsgProperty(xlangMsg, typeof(ErrorReport.SendPortName));
                    description = GetMsgProperty(xlangMsg, typeof(ErrorReport.Description));
                    if (!string.IsNullOrEmpty(serviceName))
                    {
                        serviceType        = "Send";
                        transportLocation  = GetMsgProperty(xlangMsg, typeof(ErrorReport.OutboundTransportLocation)).ToString();
                        transportDirection = "Outbound";
                    }
                    else
                    {
                        serviceName        = GetMsgProperty(xlangMsg, typeof(ErrorReport.ReceivePortName));
                        serviceType        = "Receive";
                        transportLocation  = GetMsgProperty(xlangMsg, typeof(ErrorReport.InboundTransportLocation));
                        transportDirection = "Inbound";
                    }

                    eventMessage = String.Format("A message of type '{0}' could not be routed by BizTalk.", btsMsgType) + Environment.NewLine +
                                   String.Format("{0} Port = {1}", serviceType, serviceName) + Environment.NewLine +
                                   String.Format("{0} Transport Location = {1}", transportDirection, transportLocation) + Environment.NewLine +
                                   description;
                }
                else if (faultType == FaultType.SoapException)
                {
                    serviceName       = GetMsgProperty(xlangMsg, typeof(BTS.SPName));
                    transportLocation = GetMsgProperty(xlangMsg, typeof(BTS.InboundTransportLocation));

                    eventMessage = "A SOAP Fault message was encountered by BizTalk." + Environment.NewLine +
                                   String.Format("Send Port = {0}", serviceName) + Environment.NewLine +
                                   String.Format("Outbound Transport Location = {0}", transportLocation) + Environment.NewLine + Environment.NewLine +
                                   "Refer 'FaultMsgBody' node in the archived message for more details.";
                }
                else
                {
                    serviceName = GetMsgProperty(xlangMsg, typeof(Microsoft.BizTalk.XLANGs.BTXEngine.SendingOrchestrationType));
                    serviceName = serviceName.Contains(",") ? serviceName.Substring(0, serviceName.IndexOf(",")) : serviceName;

                    eventMessage = "A System Exception was encountered by BizTalk " + Environment.NewLine +
                                   String.Format("Orchestration Name = {0}", serviceName) + Environment.NewLine + Environment.NewLine +
                                   "Refer 'FaultMsgBody' node in the archived message for more details.";
                }

                eventMessage += Environment.NewLine + Environment.NewLine + "================= Archived Message =================" + Environment.NewLine + Environment.NewLine;

                StreamReader reader = new StreamReader(faultStream);
                eventMessage += reader.ReadToEnd() + Environment.NewLine;

                eventMessage += Environment.NewLine + "================= Context Properties =================" + Environment.NewLine;

                foreach (DictionaryEntry dictionary in GetContext(xlangMsg))
                {
                    XmlQName qName = (XmlQName)dictionary.Key;
                    eventMessage += qName.Namespace + "#" + qName.Name + " : " + dictionary.Value.ToString() + Environment.NewLine;
                }

                EsbFaultEvent faultEvent = ExceptionEventDetails.Instance.ExceptionEvents.FirstOrDefault <EsbFaultEvent>
                                               (e => e.FaultSvcName.Equals(serviceName, StringComparison.OrdinalIgnoreCase) &&
                                               e.FaultType.Equals(faultType.ToString(), StringComparison.OrdinalIgnoreCase));

                if (faultEvent != null)
                {
                    Logger.WriteEvent(faultEvent.EventSource, eventMessage, (EventLogEntryType)Enum.Parse(typeof(EventLogEntryType), faultEvent.EventType), faultEvent.EventId);
                }
                else
                {
                    throw new Exception(string.Format("'{0}' fault is not configured for the service '{1}' in [AvistaESBLookup].[dbo].[EsbFaultEvents] table", faultType.ToString(), serviceName));
                }
            }
            catch (Exception ex)
            {
                eventMessage = "A Fault was encountered by BizTalk and a further error occurred while handling the message. " + Environment.NewLine + "Error Details: " + ex.ToString()
                               + Environment.NewLine + Environment.NewLine + "Original Fault Details: " + Environment.NewLine + eventMessage;

                Logger.WriteError(eventMessage, 14004);
            }
            finally
            {
                if (xlangMsg != null)
                {
                    xlangMsg.Dispose();
                    xlangMsg = null;
                }
                if (faultStream != null)
                {
                    faultStream = null;
                }
            }
        }
        public static void ArchiveMessage(XLANGMessage Message)
        {
            try
            {
                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;
                bool          IsArchive       = true;
                bool          ReadFullContext = true;
                Hashtable     HContext        = new Hashtable();
                StringBuilder SBContext       = new StringBuilder();
                string        InterchangeID   = "NA";

                string ServiceName = Microsoft.XLANGs.Core.Service.RootService.Name; //Get the Calling Orchestration Name

                if (IsArchive == true)
                {
                    ArchiveMsg(Message, FullFilePath);
                }

                if (ReadFullContext == true)
                {
                    HContext = GetContext(Message);
                    foreach (DictionaryEntry item in HContext)
                    {
                        SBContext.Append($"{(item.Key as XmlQName).Name},{ (item.Key as XmlQName).Namespace},{item.Value}");
                        SBContext.Append(";");

                        if ((item.Key as XmlQName).Name == "InterchangeID")
                        {
                            InterchangeID = item.Value.ToString();
                        }
                    }
                }



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

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

                command.Parameters.Add("@ActivityID", SqlDbType.VarChar).Value      = ActivityID;
                command.Parameters.Add("@CorrelationID", SqlDbType.VarChar).Value   = InterchangeID;
                command.Parameters.Add("@StartTime", SqlDbType.VarChar).Value       = DateTime.Now.ToString();
                command.Parameters.Add("@EndTime", SqlDbType.VarChar).Value         = DateTime.Now.ToString();
                command.Parameters.Add("@ServiceName", SqlDbType.VarChar).Value     = ServiceName;
                command.Parameters.Add("@MsgContext", SqlDbType.VarChar).Value      = SBContext.ToString();
                command.Parameters.Add("@StreamMsgPayload", SqlDbType.Binary).Value = (Stream)Message[0].RetrieveAs(typeof(Stream));
                string       RawText;
                StreamReader reader = new StreamReader((Stream)Message[0].RetrieveAs(typeof(Stream)), Encoding.UTF8);
                RawText = reader.ReadToEnd();
                command.Parameters.Add("@RawMsgPayload", SqlDbType.VarChar).Value          = RawText;
                command.Parameters.Add("@Status", SqlDbType.VarChar, 255).Value            = "Success";
                command.Parameters.Add("@MessageArchiveLocation", SqlDbType.VarChar).Value = ShareLocation + ActivityID + "." + FileExtension;

                Conn.Open();
                command.ExecuteNonQuery();
                Conn.Close();
                reader.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.ToString());
            }
            finally
            {
                Message.Dispose();
            }
        }
Beispiel #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xLangMessage"></param>
        /// <param name="tag"></param>
        /// <param name="autoDispose"></param>
        public ArchiveBizTalkMessage(XLANGMessage xLangMessage, ArchiveTag tag, bool autoDispose = true)
        {
            this.Message           = new Message();
            this.MessageProperties = new List <MessageProperty>();
            this.Parts             = new List <Part>();
            this.PartsProperties   = new List <PartProperty>();

            Guid messageId = Guid.NewGuid();

            try
            {
                if (xLangMessage is MessageWrapperForUserCode)
                {
                    //-------------------------------------------------------------------------
                    // Add Message.
                    //-------------------------------------------------------------------------
                    this.Message.MessageId = messageId;
                    if (tag.ArchiveType.Id >= 0)
                    {
                        this.Message.ArchiveTypeId = tag.ArchiveType.Id;
                    }

                    this.Message.Tag = tag.Tag;

                    if (tag.SourceSystem.Id >= 0)
                    {
                        this.Message.SourceSystemId = tag.SourceSystem.Id;
                    }

                    if (tag.TargetSystem.Id >= 0)
                    {
                        this.Message.TargetSystemId = tag.TargetSystem.Id;
                    }

                    this.Message.Description  = tag.Description;
                    this.Message.InsertedDate = DateTime.UtcNow;

                    Type messageWrapperType = typeof(MessageWrapperForUserCode);
                    msgUnwrapMethod = messageWrapperType.GetMethod("Unwrap", BindingFlags.Instance | BindingFlags.NonPublic);

                    MessageWrapperForUserCode messageWrapper = (MessageWrapperForUserCode)xLangMessage;
                    XMessage xMessage = (XMessage)(msgUnwrapMethod.Invoke(messageWrapper, null));

                    if (xMessage != null)
                    {
                        try
                        {
                            //-------------------------------------------------------------------------
                            // Add the parts.
                            //-------------------------------------------------------------------------
                            int partCount = xLangMessage.Count;
                            for (int partIndex = 0; partIndex < partCount; partIndex++)
                            {
                                XLANGPart part = xLangMessage[partIndex];
                                try
                                {
                                    Part prt = GetMessagePart(messageId, partIndex, xMessage, part);
                                    if (prt != null)
                                    {
                                        this.Parts.Add(prt);
                                        //-------------------------------------------------------------------------
                                        // Add the parts properties.
                                        //-------------------------------------------------------------------------
                                        List <PartProperty> prtProperties = GetPartProperties(prt.PartId, part);
                                        foreach (PartProperty p in prtProperties)
                                        {
                                            this.PartsProperties.Add(p);
                                        }
                                    }
                                }
                                finally
                                {
                                    // part is actually a PartWrapperForUserCode. Calling its Dispose method causes
                                    // the PartWrapperForUserCode to be detached from the owning MessageWrapperForUserCode.
                                    part.Dispose();
                                }
                            }
                            //-------------------------------------------------------------------------
                            // Add the message properties.
                            //-------------------------------------------------------------------------
                            Hashtable propertyHashTable = xMessage.GetContextProperties();
                            if (propertyHashTable != null)
                            {
                                XmlQNameTable   propertyTable = new XmlQNameTable(propertyHashTable);
                                int             propertyIndex = 0;
                                MessageProperty msgProperties = new MessageProperty();
                                msgProperties.MessageId = messageId;
                                XElement      ContextData             = new XElement("ContextData");
                                List <string> listOfContextProperties = new List <string>();
                                listOfContextProperties = GetListOfContextProperties();
                                foreach (DictionaryEntry property in propertyTable)
                                {
                                    XmlQName qName = (XmlQName)property.Key;

                                    if (listOfContextProperties.Contains(qName.Name))
                                    {
                                        ContextData.Add(
                                            new XElement("Property", new XAttribute("Name", qName.Name),
                                                         new XAttribute("Namespace", qName.Namespace),
                                                         new XAttribute("Value", property.Value.ToString())));
                                    }

                                    if (qName.Namespace == "http://schemas.microsoft.com/BizTalk/2003/system-properties")
                                    {
                                        if (qName.Name == "InterchangeID")
                                        {
                                            string value = property.Value.ToString().Trim();
                                            this.Message.InterchangeId = GetGUIDWithoutBraces(value);
                                        }
                                        else if (qName.Name == "MessageType")
                                        {
                                            this.Message.MessageType = property.Value.ToString();
                                        }
                                    }
                                    else if (qName.Namespace == "http://schemas.microsoft.com/BizTalk/2003/messagetracking-properties")
                                    {
                                        if (qName.Name == "ActivityIdentity")
                                        {
                                            string value = property.Value.ToString().Trim();
                                            this.Message.ActivityId = GetGUIDWithoutBraces(value);
                                        }
                                    }
                                    propertyIndex++;
                                }
                                msgProperties.ContextData = ContextData.ToString();
                                this.MessageProperties.Add(msgProperties);
                                // If the message type is still unknown, try to get it from part[0].
                                if (string.IsNullOrEmpty(this.Message.MessageType) || this.Message.MessageType == "Unknown")
                                {
                                    if (!string.IsNullOrEmpty(partType))
                                    {
                                        this.Message.MessageType = partType;
                                    }
                                }
                            }
                        }
                        finally
                        {
                            // When the MessageWrapperForUserCode is unrwapped the reference count
                            // for the message is incremented, so we must release it now.
                            xMessage.Release();
                        }
                    }
                    else
                    {
                        throw new Exception("Could not unwrap XMessage from MessageWrapperForUserCode.");
                    }
                }
                else
                {
                    throw new Exception("Expected XLANGMessage to be a MessageWrapperForUserCode. " + xLangMessage.GetType().FullName + " is not a recognized XLANGMessage type.");
                }
            }
            catch (Exception ex)
            {
                Logger.WriteTrace(string.Format("Error constructing BizTalkMessage from XLangMessage {0} \r\n Details: {1}", this.GetType().Name, ex.ToString()));
                throw ex;
            }
            finally
            {
                if (autoDispose)
                {
                    xLangMessage.Dispose();
                }
            }
        }