예제 #1
0
        /// <summary>
        /// Method to be called at the end of a failed orchestration processing step.
        /// </summary>
        /// <param name="trackingContext"><see cref="TrackingContext"/>
        /// Structure containing the appropriate activity identifiers.
        /// </param>
        /// <param name="faultMessage">
        /// The fault message that causes the processing step to fail.
        /// </param>
        /// <remarks>
        /// It will end the processing step activity, setting its <see cref="Status"/> to <see cref="TrackingStatus.Failed"/>.
        /// </remarks>
        public static void Fail(TrackingContext trackingContext, XLANGMessage faultMessage)
        {
            string errorDescription = null;

            if (faultMessage != null)
            {
                var faultDocument = (XmlDocument)faultMessage[0].RetrieveAs(typeof(XmlDocument));
                // TODO: extract error info from fault message
                errorDescription = faultDocument.OuterXml;
            }

            Terminate(trackingContext, TrackingStatus.Failed, errorDescription);
        }
        /// <summary>
        /// Method intended to be called near the start of an orchestration after all of its activating parallel receives (<see
        /// cref="ParallelPreInitiate"/>) have completed, or failed, to create a BAM process tracking activity.
        /// </summary>
        /// <param name="keyMessage">
        /// The message that contains the key business values to be captured for tracking purposes.
        /// </param>
        /// <returns>
        /// The <see cref="TrackingContext"/> that contains the BAM tracking activities identifiers for the current process.
        /// Notice that, contrary to <see cref="Initiate(XLANGMessage)"/>, <see cref="TrackingContext.MessagingStepActivityId"/>
        /// will not be filled.
        /// </returns>
        /// <remarks>
        /// The BAM process tracking activity, whose parallel activating messages have already all been received (<see
        /// cref="ParallelPreInitiate"/>), will be created thereby providing the missing half of the process-to-activating
        /// messages associations. The name used for the process instance is the containing namespace of the calling
        /// orchestration.
        /// </remarks>
        public static TrackingContext ParallelInitiate(XLANGMessage keyMessage)
        {
            var process = Initiate(
                Service.RootService.InstanceId,
                Service.RootService.GetType().Namespace,
                keyMessage.GetProperty(TrackingProperties.Value1),
                keyMessage.GetProperty(TrackingProperties.Value2),
                keyMessage.GetProperty(TrackingProperties.Value3));

            // set up orchestration's tracking context
            return(new TrackingContext {
                ProcessActivityId = process.ActivityId
            });
        }
        /// <summary>
        /// Reads a property in the context of the message
        /// </summary>
        /// <typeparam name="TContextProperty">Type of the target property</typeparam>
        /// <typeparam name="TExpected">Expected type of the value</typeparam>
        /// <param name="message">BizTalk pipeline message</param>
        /// <param name="isMandatory">Indication if it is mandatory for the property to be present</param>
        /// <returns>Value from the property, if present</returns>
        /// <exception cref="BizTalk.Extended.Core.Exceptions.ContextPropertyNotFoundException">Thrown when a mandatory property is not present</exception>
        public static TExpected ReadContextProperty <TContextProperty, TExpected>(this XLANGMessage message, bool isMandatory) where TContextProperty : MessageContextPropertyBase, new()
        {
            Guard.NotNull(message, "message");

            object value = message.GetPropertyValue(typeof(TContextProperty));

            if (value == null && isMandatory)
            {
                var propertyInstance = new TContextProperty();
                throw new ContextPropertyNotFoundException(propertyInstance.Name.Name, propertyInstance.Name.Namespace);
            }

            return(ContextPropertySerializer.DeserializeFromContextPropertyValue <TExpected>(value));
        }
예제 #4
0
        /// <summary>
        /// Gets the target namespace for the specified part of an XLANG message.
        /// </summary>
        /// <param name="msg">The XLANG message.</param>
        /// <param name="partNumber">The part number.</param>
        /// <returns>The target namespace.</returns>
        public static string GetNamespace(XLANGMessage msg, int partNumber)
        {
            XLANGPart part = msg[partNumber];

            System.Xml.Schema.XmlSchema sch = part.XmlSchema;
            if (sch == null)
            {
                return(String.Empty);
            }
            else
            {
                return(sch.TargetNamespace);
            }
        }
예제 #5
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();
     }
 }
예제 #6
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();
     }
 }
예제 #7
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();
     }
 }
예제 #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="config"></param>
        /// <param name="resolver"></param>
        /// <param name="resolution"></param>
        /// <returns></returns>
        private static Dictionary <string, string> ResolveStatic(XLANGMessage message)
        {
            Dictionary <string, string> resolverDictionary = new Dictionary <string, string>();
            string        result        = null;
            StringWriter  stringWriter  = null;
            XmlTextWriter xmlTextWriter = null;

            try
            {
                stringWriter             = new StringWriter();
                xmlTextWriter            = new XmlTextWriter(stringWriter);
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlTextWriter.WriteStartDocument();
                xmlTextWriter.WriteStartElement("ContextProperties");

                foreach (DictionaryEntry dictionary in GetContext(message))
                {
                    XmlQName qName = (XmlQName)dictionary.Key;
                    xmlTextWriter.WriteStartElement("Property");
                    xmlTextWriter.WriteAttributeString("name", qName.Name);
                    xmlTextWriter.WriteAttributeString("namespace", qName.Namespace);
                    xmlTextWriter.WriteString(dictionary.Value.ToString());
                    xmlTextWriter.WriteEndElement();
                }
                xmlTextWriter.WriteFullEndElement();
                xmlTextWriter.WriteEndDocument();
                result = stringWriter.ToString();
            }
            catch
            {
                throw;
            }
            finally
            {
                if (xmlTextWriter != null)
                {
                    xmlTextWriter.Close();
                }
                if (stringWriter != null)
                {
                    stringWriter.Close();
                    stringWriter.Dispose();
                }
            }

            resolverDictionary.Add("MessageContext", result);

            return(resolverDictionary);
        }
예제 #9
0
        /// <summary>
        /// Reads the textual value for a single node from an XLANG message using the specified XPath.
        /// </summary>
        /// <param name="msg">The message.</param>
        /// <param name="xPath">The XPath query identifying the node to be read.</param>
        /// <param name="defaultNamespacePrefix">Name of the default namespace prefix for the message.</param>
        /// <returns>The textual value of the node.</returns>
        public static string ReadNode(XLANGMessage msg, string xPath, string defaultNamespacePrefix)
        {
            // Get the node
            XmlNode n = GetSingleNode(msg, xPath, defaultNamespacePrefix);

            // We need to handle the case when the XPath did not match any node
            if (n != null)
            {
                return(n.InnerText);
            }
            else
            {
                return(null);
            }
        }
예제 #10
0
        public void Logs(XLANGMessage message)
        {
            var    xdoc          = (XmlDocument)message[0].RetrieveAs(typeof(XmlDocument));
            var    names         = new XmlNamespaceManager(xdoc.NameTable);
            string correlationId = null;
            var    connection    = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
            var    sql           = "[Usp_InsertLog]";

            var command = new SqlCommand(sql, connection);

            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@CorrelationId", SqlDbType.VarChar)).Value = correlationId;
            connection.Open();
            int ID = command.ExecuteNonQuery();

            connection.Close();
        }
예제 #11
0
        /// <summary>
        /// Create fault message with Exception object and request xlang message
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="requestMsg"></param>
        /// <param name="faultType"></param>
        /// <returns></returns>
        public static XLANGMessage CreateFaultMessage(Exception exception, XLANGMessage requestMsg, FaultType faultType)
        {
            string faultXml = SerializeExceptionObject(exception);
            string reqXml   = string.Empty;

            try
            {
                Stream reqStream = requestMsg != null ? ((Stream)requestMsg[0].RetrieveAs(typeof(Stream))) : null;
                using (StreamReader reader = new StreamReader(reqStream))
                {
                    reqXml = reader.ReadToEnd();
                }
            }
            catch (Exception) { }

            XLANGMessage result = GetFaultMessage(faultXml, reqXml, faultType);

            return(result);
        }
        public static void TrackDirectReceive(TrackingContext trackingContext, XLANGMessage message, bool trackMessageBody, bool skipMessageContextTracking)
        {
            var messagingStepTracking = new MessagingStep(Tracking.ActivityId.NewActivityId(), message);

            messagingStepTracking.BeginMessagingStepActivity();
            if (trackMessageBody)
            {
                messagingStepTracking.TrackMessageBody();
            }
            if (!skipMessageContextTracking)
            {
                messagingStepTracking.TrackMessageContext();
            }
            messagingStepTracking.TrackStep(TrackingStatus.Received);
            messagingStepTracking.CommitMessagingStepActivity();
            messagingStepTracking.EndMessagingStepActivity();

            new Process(trackingContext.ProcessActivityId).AddStep(messagingStepTracking);
        }
예제 #13
0
        /// <summary>
        /// Validate an XLANG message using a BRE policy.
        /// </summary>
        /// <param name="bizTalkMessage">
        /// The XLANG message.
        /// </param>
        /// <returns>
        /// A <see cref="Validations"/> object containing the results of all validations.
        /// </returns>
        public Validations ValidateMessage(XLANGMessage bizTalkMessage)
        {
            var validations = new Validations();

            if (this.directive == null)
            {
                return(validations);
            }

            if (string.IsNullOrWhiteSpace(this.directive.ValidationPolicyName))
            {
                return(validations);
            }

            // Invoke private method to unwrap message.
            var unwrappedBizTalkMessage =
                (BTXMessage)
                bizTalkMessage.GetType()
                .GetMethod("Unwrap", BindingFlags.Instance | BindingFlags.NonPublic)
                .Invoke(bizTalkMessage, null);

            // Get the XML content (if any) of the body part
            var part = unwrappedBizTalkMessage.BodyPart ?? unwrappedBizTalkMessage[0];

            if (part == null)
            {
                return(validations);
            }

            XmlDocument xmlDocument;

            try
            {
                xmlDocument = (XmlDocument)part.RetrieveAs(typeof(XmlDocument));
            }
            catch
            {
                return(validations);
            }

            return(this.ValidateDocument(xmlDocument, part.GetPartType().FullName));
        }
        /// <summary>
        /// Resolve implementation for use within an Orchestration. This method is typically used by creating an instance of the BRE Resolver Provider class inside an orchestration expression to resolve entities, such as itinerary, maps and endpoint addresses. This method invokes the BRE Policies that were configured through the Config and Resolver connection string values.
        /// </summary>
        /// <param name="resolverInfo">Resolver collection of entries</param>
        /// <param name="message">BizTalk XLangMessage class which is used to pass to the BRE policies if configured properly</param>
        /// <returns>Resolver Dictionary Collection containing resolved entries, such as itinerary name, map name, and endpoint address resolution values</returns>
        public Dictionary <string, string> Resolve(ResolverInfo resolverInfo, XLANGMessage message)
        {
            Dictionary <string, string> dictionary;

            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            Resolution resolution = new Resolution();

            try
            {
                BRE bre = this.CreateResolverDescriptor(resolverInfo.Config, resolverInfo.Resolver);
                if (bre.recognizeMessageFormat || bre.useMsgCtxt)
                {
                    throw new ResolveException("The attributes  recognizeMessageFormat and useMsgCtxt are not supported from orchestrations.");
                }
                ResolverMgr.SetContext(resolution, message);
                XmlDocument document = null;
                if (bre.useMsg)
                {
                    document = (XmlDocument)message[0].RetrieveAs(typeof(XmlDocument));
                }


                IBaseMessage msg = null;
                dictionary = ResolveRules(resolverInfo.Config, resolverInfo.Resolver, document, resolution, bre, null, null, ref msg);
            }
            catch (Exception exception)
            {
                EventLogger.Write(MethodBase.GetCurrentMethod(), exception);
                throw;
            }
            finally
            {
                if (resolution != null)
                {
                    resolution = null;
                }
            }
            return(dictionary);
        }
예제 #15
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);
        }
예제 #16
0
        /// <summary>
        /// Mocks a dynamic send port with the given name by setting the necessary transport properties with the specified custom behaviors
        /// on the outbound message only in the case a TransMock test case is being executed
        /// </summary>
        /// <param name="portName">The name of the send port as defined in the orchestration</param>
        /// <param name="customBehaviorConfig">The custom behavior configuration to be applied</param>
        /// <param name="outboundMessage">The outbound message instance that is to be sent over the dynamic send port</param>
        /// <returns>An instance of the <see cref="MockTransportConfig"/> class which contains the configuration for the mock adapter transport for the dynamic send port</returns>
        public static MockTransportConfig MockDynamicSendPort(
            string portName,
            string customBehaviorConfig,
            XLANGMessage outboundMessage)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("MockDynamicSendPort(portName, originalAdapter, customBehaviorConfig, XLANGMessage) called.");

                bool applyMock = IsTransMockTestCaseExecuting();

                if (applyMock)
                {
                    System.Diagnostics.Debug.WriteLine("Applying mock transport settings");

                    // Clear any previously set transport specific properties
                    ClearOriginalWCFAdapterProperties(outboundMessage);

                    // Then apply the mock transport config properties to the message
                    ApplyMockTransportConfig(outboundMessage, customBehaviorConfig);

                    var mockConfig = new MockTransportConfig(portName);

                    return(mockConfig);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Not executing in TransMock test case. Returning null.");

                    return(null);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(
                    "MockDynamicSendPort(portName, customBehaviorConfig, XLANGMessage) threw an exception: "
                    + ex.Message);

                return(null);
            }
        }
예제 #17
0
        public static void ArchiveMsg(XLANGMessage message, string FullFilePath)
        {
            Stream OrchStream = (Stream)message[0].RetrieveAs(typeof(Stream));

            if (OrchStream.CanSeek)
            {
                OrchStream.Position = 0;
            }
            long lstreamlength;

            lstreamlength = OrchStream.Length;
            if (lstreamlength > 0)
            {
                long   lreadbytes = 0;
                Stream S          = File.OpenWrite(FullFilePath);
                {
                    //Writing with Encoding
                    BinaryWriter bw = new BinaryWriter(S, Encoding.UTF8);

                    while (lstreamlength > 0)
                    {
                        if (lstreamlength >= 1000000)
                        {
                            lreadbytes = 1000000;
                        }
                        else
                        {
                            lreadbytes = lstreamlength;
                        }
                        lstreamlength = lstreamlength - lreadbytes;
                        byte[] ba = new byte[lreadbytes];

                        OrchStream.Read(ba, 0, ba.Length);
                        bw.Write(ba);
                    }
                }
                S.Close();
            }
        }
예제 #18
0
        /// <summary>
        /// Gets XLANG message context property
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="prop"></param>
        /// <returns></returns>
        private static string GetMsgProperty(XLANGMessage msg, Type prop)
        {
            if (msg == null)
            {
                throw new System.ArgumentNullException("msg");
            }
            if (null == prop)
            {
                throw new System.ArgumentNullException("prop");
            }
            object obj    = null;
            string result = string.Empty;

            try
            {
                obj = msg.GetPropertyValue(prop);
                if (obj != null)
                {
                    result = obj.ToString();
                }
            }
            catch (InvalidPropertyTypeException ex)
            {
                Logger.WriteWarning(ex.ToString(), 14000);
            }
            catch (Exception ex)
            {
                Logger.WriteError(ex.ToString(), 14000);
                throw ex;
            }
            finally
            {
                if (obj != null)
                {
                    obj = null;
                }
            }
            return(result);
        }
예제 #19
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);
 }
예제 #20
0
        /// <summary>
        /// Create fault message with fault xlang message and request xlang message
        /// </summary>
        /// <param name="faultMsg"></param>
        /// <param name="requestMsg"></param>
        /// <param name="faultType"></param>
        /// <returns></returns>
        public static XLANGMessage CreateFaultMessage(XLANGMessage faultMsg, XLANGMessage requestMsg, FaultType faultType)
        {
            string faultXml = faultMsg != null ? ((XmlDocument)faultMsg[0].RetrieveAs(typeof(XmlDocument))).OuterXml.ToString() : string.Empty;
            string reqXml   = requestMsg != null ? ((XmlDocument)requestMsg[0].RetrieveAs(typeof(XmlDocument))).OuterXml.ToString() : string.Empty;

            XLANGMessage result = GetFaultMessage(faultXml, reqXml, faultType);

            object obj = GetMsgProperty(faultMsg, typeof(BTS.SPName));

            if (obj != null)
            {
                SetMsgProperty(result, typeof(BTS.SPName), obj.ToString());
            }

            obj = GetMsgProperty(faultMsg, typeof(BTS.InboundTransportLocation));
            if (obj != null)
            {
                SetMsgProperty(result, typeof(BTS.InboundTransportLocation), obj.ToString());
            }

            return(result);
        }
예제 #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="resolverInfo"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public Dictionary <string, string> Resolve(ResolverInfo resolverInfo, XLANGMessage message)
        {
            #region Argument Check
            if (null == message)
            {
                throw new ArgumentNullException("message");
            }
            #endregion Argument Check

            // Resolve the params from arguments by creating
            // class from schema, and storing the results
            Resolution resolution = new Resolution();
            try
            {
                // Populate context
                ResolverMgr.SetContext(resolution, message);

                Dictionary <string, string> resolverDictionary = new Dictionary <string, string>();

                XmlDocument xmlMessage = (XmlDocument)message[0].RetrieveAs(typeof(XmlDocument));

                resolverDictionary.Add("MessageContent", xmlMessage.OuterXml);

                return(resolverDictionary);
            }
            catch (System.Exception ex)
            {
                Exception exception = new Exception("Error performing Content resolution in orchestration context.", ex);
                Logger.WriteTrace(string.Format("Error occured in {0} \r\n Details: {1}", this.GetType().Name, exception.ToString()));
                throw exception;
            }
            finally
            {
                if (null != resolution)
                {
                    resolution = null;
                }
            }
        }
예제 #22
0
        }//Business Layer

        public void ArchiveMessageXlang(XLANGMessage Xmsg, Stage stage, ActivityInfo activityInfo)
        {
            Dictionary <object, object> HContext = new Dictionary <object, object>();
            StringBuilder SBContext   = new StringBuilder();
            string        ServiceName = Microsoft.XLANGs.Core.Service.RootService.Name; //Get the Calling Orchestration Name

            if (stage.archiveMessagePayloadDB == true)
            {
                var DContext         = GetContext(Xmsg).Cast <DictionaryEntry>().ToDictionary(d => d.Key, d => d.Value);
                var serializedObject = DContext.Select(ctx => new ContextProperty
                {
                    Name      = (ctx.Key as XmlQName).Name,
                    NameSpace = (ctx.Key as XmlQName).Namespace,
                    Value     = Convert.ToString(ctx.Value)
                });
                string      context = JsonConvert.SerializeObject(serializedObject);
                XmlDocument xdoc    = new XmlDocument();
                xdoc = (XmlDocument)Xmsg[0].RetrieveAs(typeof(XmlDocument));
                byte[] messageBody = Encoding.Default.GetBytes(xdoc.InnerXml.ToString());
                activityInfo.ArchiverLinkFriendlyName = stage.archiverLinkFriendlyName;
                ArchiveMessage(messageBody, context, activityInfo);
            }
        }//Business Layer
예제 #23
0
        /// <summary>
        /// Reads the textual value for a single node from an XLANG message using the specified XPath.
        /// </summary>
        /// <param name="msg">The message.</param>
        /// <param name="xPath">The XPath query identifying the node to be read.</param>
        /// <param name="defaultNamespacePrefix">Name of the default namespace prefix for the message.</param>
        /// <param name="returnNullAsString"></param>
        /// <param name="isBoolean"></param>
        /// <returns>The textual value of the node.</returns>
        public static string ReadNode(XLANGMessage msg,
                                      string xPath,
                                      string defaultNamespacePrefix,
                                      Boolean returnNullAsString,
                                      Boolean isBoolean)
        {
            // Get the node
            XmlNode n = GetSingleNode(msg, xPath, defaultNamespacePrefix);

            // We need to handle the case when the XPath did not match any node
            if (n != null)
            {
                if (isBoolean)
                {
                    if (Boolean.Parse(n.InnerText))
                    {
                        return("true");
                    }
                    else
                    {
                        return("false");
                    }
                }
                return(n.InnerText);
            }
            else
            {
                if (returnNullAsString == true)
                {
                    return("null");
                }
                else
                {
                    return(null);
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Gets all message context properties assocciated with xlang message
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static Hashtable GetContext(XLANGMessage message)
        {
            foreach (Segment segment in Service.RootService._segments)
            {
                IDictionary fields = Microsoft.XLANGs.Core.Context.FindFields(typeof(XLANGMessage), segment.ExceptionContext);

                foreach (DictionaryEntry field in fields)
                {
                    XMessage msg = (field.Value as XMessage);
                    if (msg == null)
                    {
                        continue;
                    }

                    if (String.Compare(msg.Name, message.Name) != 0)
                    {
                        continue;
                    }

                    return(msg.GetContextProperties());
                }
            }
            return(new Hashtable());
        }
 internal MessagingStep(XLANGMessage message) : this(message.GetTrackingContext().MessagingStepActivityId, message)
 {
 }
예제 #26
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;
                }
            }
        }
        /// <summary>
        /// Get a single node from an XLANG message.
        /// </summary>
        /// <param name="msg">The message.</param>
        /// <param name="xPath">The XPath query identifying the node to be read.</param>
        /// <param name="defaultNamespacePrefix">Name of the default namespace prefix for the message.</param>
        /// <returns>A single <see cref="T:XmlNode"/> matching the XPath query.</returns>
        public static XmlNode GetSingleNode(XLANGMessage msg, string xPath, string defaultNamespacePrefix)
        {
            // Get the XML representation of the message.
            XmlDocument msgXml = ConvertMsgToXml(msg);

            // Get the node
            return GetSingleNodeXml(msgXml, xPath, defaultNamespacePrefix);
        }
 /// <summary>
 /// Gets the target namespace for the specified part of an XLANG message.
 /// </summary>
 /// <param name="msg">The XLANG message.</param>
 /// <param name="partNumber">The part number.</param>
 /// <returns>The target namespace.</returns>
 public static string GetNamespace(XLANGMessage msg, int partNumber)
 {
     XLANGPart part = msg[partNumber];
     System.Xml.Schema.XmlSchema sch = part.XmlSchema;
     if (sch == null)
     {
         return String.Empty;
     }
     else
     {
         return sch.TargetNamespace;
     }
 }
 internal MessagingStep(string activityId, XLANGMessage message) : this(activityId)
 {
     Message = message ?? throw new ArgumentNullException(nameof(message));
 }
 /// <summary>
 /// Converts an XLANG message into an XML document.
 /// </summary>
 /// <param name="msg">The XLANG message.</param>
 /// <returns>The XLANG message as an XML document.</returns>
 /// <remarks>
 /// It is assumed that every XLANG message consists of a single message part only.
 /// </remarks>
 public static XmlDocument ConvertMsgToXml(XLANGMessage msg)
 {
     // Get the XML representation of the message.
     XmlDocument msgXml = (XmlDocument)msg[0].RetrieveAs(typeof(XmlDocument));
     return msgXml;
 }
        /// <summary>
        /// Reads the textual value for a single node from an XLANG message using the specified XPath.
        /// </summary>
        /// <param name="msg">The message.</param>
        /// <param name="xPath">The XPath query identifying the node to be read.</param>
        /// <param name="defaultNamespacePrefix">Name of the default namespace prefix for the message.</param>
        /// <param name="returnNullAsString"></param>
        /// <param name="isBoolean"></param>
        /// <returns>The textual value of the node.</returns>
        public static string ReadNode(XLANGMessage msg, 
                                        string xPath, 
                                        string defaultNamespacePrefix,
                                        Boolean returnNullAsString,
                                        Boolean isBoolean)
        {
            // Get the node
            XmlNode n = GetSingleNode(msg, xPath, defaultNamespacePrefix);

            // We need to handle the case when the XPath did not match any node
            if (n != null)
            {
                if (isBoolean)
                {
                    if (Boolean.Parse(n.InnerText)) return "true"; else return "false";
                }
                return n.InnerText;
            }
            else
            {
                if (returnNullAsString == true) return "null";
                else return null;
            }
        }
        public override void SetEndpoint(Dictionary <string, string> resolverDictionary, XLANGMessage message)
        {
            if (resolverDictionary == null)
            {
                throw new ArgumentNullException("resolverDictionary");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            try
            {
                var transportLocation = resolverDictionary["Resolver.TransportLocation"];

                var outboundTransportCLSID = resolverDictionary["Resolver.OutboundTransportCLSID"];
                var endpointConfig         = resolverDictionary["Resolver.EndpointConfig"];
                var transportType          = resolverDictionary["Resolver.TransportType"];
                var messageExchangePattern = resolverDictionary["Resolver.MessageExchangePattern"];
                var _operation             = resolverDictionary["Resolver.Action"];

                var customProps = new Dictionary <string, string>();
                customProps = endpointConfig.ParseKeyValuePairs(true);
                message.SetMsgProperty(typeof(BTS.OutboundTransportLocation), transportLocation);
                message.SetMsgProperty(typeof(BTS.OutboundTransportType), transportType);
                message.SetMsgProperty(typeof(BTS.OutboundTransportCLSID), outboundTransportCLSID);
                message.SetMsgProperty(typeof(BTS.Operation), _operation);
                message.SetMsgProperty(typeof(BTS.MessageExchangePattern), messageExchangePattern);

                message.SetMsgProperty(typeof(WCF.Action), _operation);
                message.SetMsgProperty(typeof(WCF.HttpMethodAndUrl), customProps.GetValue("HttpMethodAndUrl"));
                message.SetMsgProperty(typeof(WCF.HttpHeaders), customProps.GetValue("HttpHeaders"));
                message.SetMsgProperty(typeof(WCF.VariablePropertyMapping), customProps.GetValue("VariablePropertyMapping"));
                message.SetMsgProperty(typeof(WCF.SuppressMessageBodyForHttpVerbs), customProps.GetValue("SuppressMessageBodyForHttpVerbs"));
                message.SetMsgProperty(typeof(WCF.SecurityMode), customProps.GetValue("SecurityMode"));
                message.SetMsgProperty(typeof(WCF.TransportClientCredentialType), customProps.GetValue("TransportClientCredentialType"));
                message.SetMsgProperty(typeof(WCF.UserName), customProps.GetValue("UserName"));
                message.SetMsgProperty(typeof(WCF.Password), customProps.GetValue("Password"));
                message.SetMsgProperty(typeof(WCF.SendTimeout), customProps.GetValue("SendTimeout"));
                message.SetMsgProperty(typeof(WCF.OpenTimeout), customProps.GetValue("OpenTimeout"));
                message.SetMsgProperty(typeof(WCF.CloseTimeout), customProps.GetValue("CloseTimeout"));
                message.SetMsgProperty(typeof(WCF.ProxyToUse), customProps.GetValue("ProxyToUse"));
                message.SetMsgProperty(typeof(WCF.ProxyAddress), customProps.GetValue("ProxyAddress"));
                SetEndpointContextProperties(message, endpointConfig);
            }
            catch (System.Exception ex)
            {
                EventLogger.LogMessage(ex.Message, System.Diagnostics.EventLogEntryType.Error, 0);
                throw;
            }
        }
 public static void TrackDirectSend(TrackingContext trackingContext, XLANGMessage message)
 {
     TrackDirectSend(trackingContext, message, false, false);
 }
        /// <summary>
        /// Counts the number of nodes that match the specified XPath.
        /// </summary>
        /// <param name="msg">The XLANG message.</param>
        /// <param name="xPath">The XPath query identifying the nodes to be count.</param>
        /// <param name="defaultNamespacePrefix">Name of the default namespace prefix for the message.</param>
        /// <returns>Number of occurances of the node in the XLANG message.</returns>
        public static int NodeCount(XLANGMessage msg, string xPath, string defaultNamespacePrefix)
        {
            // Get the XML representation of the message.
            XmlDocument msgXml = ConvertMsgToXml(msg);

            // Configure the namespace manager
            XmlNamespaceManager nmgr = CreateNamespaceMgr(msgXml, defaultNamespacePrefix);

            // Get the set of nodes matching the XPath
            XmlNodeList nList = msgXml.SelectNodes(xPath, nmgr);
            return nList.Count;
        }
 /// <overloads>
 /// Gets the target namespace for the specified XLANG message.
 /// </overloads>
 /// <summary>
 /// Gets the target namespace for the specified XLANG message that consists of a single part only.
 /// </summary>
 /// <param name="msg">The XLANG message.</param>
 /// <returns>The target namespace.</returns>
 public static string GetNamespace(XLANGMessage msg)
 {
     // Default to the first part - number 0
     return GetNamespace(msg, 0);
 }
 public static void TrackDirectSend(TrackingContext trackingContext, XLANGMessage message, bool trackMessageBody)
 {
     TrackDirectSend(trackingContext, message, trackMessageBody, false);
 }
        /// <summary>
        /// Reads the textual value for a single node from an XLANG message using the specified XPath.
        /// </summary>
        /// <param name="msg">The message.</param>
        /// <param name="xPath">The XPath query identifying the node to be read.</param>
        /// <param name="defaultNamespacePrefix">Name of the default namespace prefix for the message.</param>
        /// <returns>The textual value of the node.</returns>
        public static string ReadNode(XLANGMessage msg, string xPath, string defaultNamespacePrefix)
        {
            // Get the node
            XmlNode n = GetSingleNode(msg, xPath, defaultNamespacePrefix);

            // We need to handle the case when the XPath did not match any node
            if (n != null)
            {
                return n.InnerText;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// Reads the textual value for a single node from an XLANG message using the specified XPath.
        /// </summary>
        /// <param name="msg">The message.</param>
        /// <param name="xPath">The XPath query identifying the node to be read.</param>
        /// <param name="defaultNamespacePrefix">Name of the default namespace prefix for the message.</param>
        /// <param name="returnNullAsNegative"></param>
        /// <returns>The textual value of the node.</returns>
        public static string ReadNode(XLANGMessage msg,
                                        string xPath,
                                        string defaultNamespacePrefix,
                                        Boolean returnNullAsNegative
                                        )
        {
            // Get the node
            XmlNode n = GetSingleNode(msg, xPath, defaultNamespacePrefix);

            // We need to handle the case when the XPath did not match any node
            if (n != null)
            {
                return n.InnerText;
            }
            else
            {
                if (returnNullAsNegative == true) return "-1";
                else return null;
            }
        }
예제 #39
0
        /// <summary>
        /// Nessary Fields in the ConfigDB:
        /// </summary>
        /// <configvalue name="Medega.StrConn.Validator">connstring</configvalue>
        /// <configvalue name="Medega.BulkCopyDestinationTable">MedegaXmlNode</configvalue>
        /// <configvalue name="Medega.BulkloadTimeout">30</configvalue>
        /// <configvalue name="Medega.ElementToBulkload">ROW</configvalue>
        /// <configvalue name="msg"></configvalue>
        /// <configvalue name="msg"></configvalue>
        /// <configvalue name="msg"></configvalue>
        /// <returns></returns>
        public bool LoadGuardNodes(XLANGMessage msg, int MedegaFileId, int Status)
        {
            string strConn, destTable;
            int bulkLoadTimeout;
            string XmlTagRow;
            int FieldCount;

            try
            {
                strConn = RIZIV.BizTalk.Common.BTSConfigReader.Instance.ReadConfigValueAsString("MedegaImport", "Medega.StrConn.Validator");
                destTable = RIZIV.BizTalk.Common.BTSConfigReader.Instance.ReadConfigValueAsString("MedegaImport", "Medega.BulkCopyDestinationTable");
                bulkLoadTimeout = Convert.ToInt32(RIZIV.BizTalk.Common.BTSConfigReader.Instance.ReadConfigValueAsString("MedegaImport", "Medega.BulkloadTimeout"));
                XmlTagRow = RIZIV.BizTalk.Common.BTSConfigReader.Instance.ReadConfigValueAsString("MedegaImport", "Medega.ElementToBulkload");
                FieldCount = Convert.ToInt32(RIZIV.BizTalk.Common.BTSConfigReader.Instance.ReadConfigValueAsString("MedegaImport", "Medega.BulkloadFieldCount"));
            }
            catch(Exception ex)
            {
                throw new Exception("Error while loading the MedegaImport config values from the BTS config DB!", ex);
            }

            try
            {

                Stream stream = (Stream)msg[0].RetrieveAs(typeof(Stream));
                XmlReader xmlReader = new XmlTextReader(stream);

                TransactionOptions options = new TransactionOptions();
                options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                options.Timeout = new TimeSpan(0, bulkLoadTimeout, 0);

                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew, options))
                {
                    using (SqlConnection conn = new SqlConnection(strConn))
                    {
                        using (MedegaDataReader medegaReader = new MedegaDataReader(xmlReader, MedegaFileId, Status, FieldCount, XmlTagRow))
                        {
                            conn.Open();

                            #region Mapping Xml to Table
                            SqlBulkCopy bulkcpy = new SqlBulkCopy(conn);
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(0, "MEMBER_INAMI_NUMBER"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(1, "MEMBER_LASTNAME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(2, "MEMBER_FIRSTNAME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(3, "FEE_DATE"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(4, "ASSOCIATION_ID"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(5, "ASSOCIATION_NAME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(6, "GEOGRAPHIC_ENTITY_NAME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(7, "NIS_CODE"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(8, "ZIP_CODE"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(9, "MANAGER_LASTNAME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(10, "MANAGER_FIRSTNAME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(11, "MANAGER_INAMI_NUMBER"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(12, "PERIOD_START_TIME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(13, "PERIOD_END_TIME"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(14, "MedegaFileId"));
                            bulkcpy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(15, "Status"));
                            #endregion

                            bulkcpy.BulkCopyTimeout = bulkLoadTimeout*60;
                            bulkcpy.DestinationTableName = destTable;
                            bulkcpy.WriteToServer(medegaReader);
                            conn.Close();
                        }
                    }
                    trans.Complete();
                    return true;
                }
            }
            catch (Exception exc)
            {
                throw new Exception("Error while executing the bulkload for Medega", exc);
                return false;
            }
        }