public virtual void Execute(IBaseMessageContext messageContext)
 {
     if (messageContext == null)
     {
         throw new ArgumentNullException(nameof(messageContext));
     }
     if (ExtractionMode == ExtractionMode.Clear)
     {
         if (_logger.IsDebugEnabled)
         {
             _logger.DebugFormat("Clearing property {0} from context.", PropertyName);
         }
         if (messageContext.IsPromoted(PropertyName.Name, PropertyName.Namespace))
         {
             messageContext.Promote(PropertyName.Name, PropertyName.Namespace, null);
         }
         messageContext.Write(PropertyName.Name, PropertyName.Namespace, null);
     }
     else if (ExtractionMode == ExtractionMode.Ignore)
     {
         if (_logger.IsDebugEnabled)
         {
             _logger.DebugFormat("Ignoring property {0} from context.", PropertyName);
         }
     }
     else
     {
         throw new InvalidOperationException($"Unexpected ExtractionMode '{ExtractionMode}'.");
     }
 }
        public static string ToXml(this IBaseMessageContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            // cache xmlns while constructing xml infoset...
            var nsCache     = new XmlDictionary();
            var xmlDocument = new XElement(
                "context",
                Enumerable.Range(0, (int)context.CountProperties).Select(
                    i => {
                var value = context.ReadAt(i, out var name, out var ns);
                // give each property element a name of 'p' and store its actual name inside the 'n' attribute, which avoids
                // the cost of the name.IsValidQName() check for each of them as the name could be an xpath expression in the
                // case of a distinguished property
                return(name.IndexOf("password", StringComparison.OrdinalIgnoreCase) > -1
                                                        ? null
                                                        : new XElement(
                           (XNamespace)nsCache.Add(ns).Value + "p",
                           new XAttribute("n", name),
                           context.IsPromoted(name, ns) ? new XAttribute("promoted", true) : null,
                           value));
            }));

            // ... and declare/alias all of them at the root element level to minimize xml string size
            for (var i = 0; nsCache.TryLookup(i, out var xds); i++)
            {
                xmlDocument.Add(new XAttribute(XNamespace.Xmlns + "s" + xds.Key.ToString(CultureInfo.InvariantCulture), xds.Value));
            }

            return(xmlDocument.ToString(SaveOptions.DisableFormatting));
        }
Exemple #3
0
        public static bool IsPromoted(this IBaseMessageContext ctx, ContextProperty property)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            return(ctx.IsPromoted(property.PropertyName, property.PropertyNamespace));
        }
        private static IBaseMessageContext CloneMessageContext(IBaseMessageContext context)
        {
            IBaseMessageContext clonedContext = MessageFactory.CreateMessageContext();

            for (int i = 0; i < context.CountProperties; i++)
            {
                string propertyNamespace = String.Empty;
                string propertyName      = String.Empty;

                object value = context.ReadAt(i, out propertyName, out propertyNamespace);

                if (context.IsPromoted(propertyName, propertyNamespace))
                {
                    clonedContext.Promote(propertyName, propertyNamespace, value);
                }
                else
                {
                    clonedContext.Write(propertyName, propertyNamespace, value);
                }
            }

            return(clonedContext);
        }
        /// <summary>
        /// Updates the BizTalk BaseMessage and Message Context with any new or modified values from the executed BRE Policies.
        /// </summary>
        /// <param name="msgCtxt">BizTalk BaseMessage Context value collection to update</param>
        /// <param name="bre">BRE Descriptor with possible values to read for updating the Message context</param>
        /// <param name="pCtxt">PipelineContext</param>
        /// <param name="baseMsg">BizTalk BaseMessage to update</param>
        private static void UpdateContextProperties(MessageContextFactRetriever msgCtxt, BRE bre, IPipelineContext pCtxt, ref IBaseMessage baseMsg)
        {
            try
            {
                if (pCtxt == null || baseMsg == null)
                {
                    return;
                }
                IBaseMessageContext baseMsgCtxt = baseMsg.Context;
                foreach (var updatedCtxt in msgCtxt.GetDictionaryCollection())
                {
                    string[] NameNameSpaceValues = updatedCtxt.Key.Split('#');

                    // no need to check for old values just overwrite and add
                    // Check to see if we need to promote it
                    string name            = NameNameSpaceValues[1];
                    bool   shouldPromote   = name.Contains("!");
                    bool   isDistinguished = name.Contains("/");

                    string namesp = NameNameSpaceValues[0];

                    // check to determine if we should promote and not distinguished
                    if (shouldPromote && !isDistinguished)
                    {
                        string correctName = name;

                        // remove ! char from key name before promoting
                        if (shouldPromote)
                        {
                            correctName = name.Substring(0, name.Length - 1);
                        }

                        // however check to see if already promoted or not
                        bool isAlreadyPromoted = false;
                        var  ovalue            = baseMsgCtxt.Read(correctName, namesp);
                        if (ovalue != null)
                        {
                            isAlreadyPromoted = baseMsgCtxt.IsPromoted(correctName, namesp);
                        }

                        if (ovalue != null && isAlreadyPromoted)
                        {
                            // we need to remove and re - promote
                            baseMsgCtxt.Write(correctName, namesp, null);
                            baseMsgCtxt.Promote(correctName, namesp, null);
                            baseMsgCtxt.Promote(correctName, namesp, updatedCtxt.Value);
                        }
                        else
                        {
                            // it's not already promoted and we should promote if we can,
                            // this assumes there is a valid property schema, name, and data type associated with it for promotion validation...
                            // dangerous operation which could cause cyclic loop by re-promoting a property that was slated to be demoted *wasPromote*...
                            if (bre.useRepromotionSpecified)
                            {
                                if (bre.useRepromotion)
                                {
                                    try
                                    {
                                        baseMsgCtxt.Write(correctName, namesp, null);
                                        baseMsgCtxt.Promote(correctName, namesp, null);
                                        baseMsgCtxt.Promote(correctName, namesp, updatedCtxt.Value);
                                    }
                                    catch (Exception ex)
                                    {
                                        EventLogger.LogMessage(
                                            string.Format(
                                                "Namespace: {0}\nName: {1}\n caused an exception:\n{2}\nThis item was not promoted.",
                                                namesp, correctName, ex.Message), EventLogEntryType.Error, 1000);
                                    }
                                }
                            }
                        }
                    }
                    else if (shouldPromote && isDistinguished)
                    {
                        // can't promote a distinguished field that contains a "/" in it's name, there's no way for BizTalk to validate it using normal BizTalk Property Schemas...
                        // do nothing.
                    }
                    else if (isDistinguished)
                    {
                        // We don't need to promote it, only write it (Distinguished)
                        // we need to remove and re-write it
                        baseMsgCtxt.Write(name, namesp, null);
                        baseMsgCtxt.Write(name, namesp, updatedCtxt.Value);
                    }
                    //else niether promote nore write so do nothing...
                }
                pCtxt.ResourceTracker.AddResource(baseMsgCtxt);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("BRE_ResolverProvider::UpdateContextProperties", ex.ToString(),
                                    EventLogEntryType.Error, 10000);
                throw;
            }
        }
 public static bool IsPromoted <T, TV>(this IBaseMessageContext context, MessageContextProperty <T, TV> property)
     where T : MessageContextPropertyBase, new()
     where TV : struct
 {
     return(context.GetProperty(property).HasValue&& context.IsPromoted(property.Name, property.Namespace));
 }
 public static bool IsPromoted <T>(this IBaseMessageContext context, MessageContextProperty <T, string> property)
     where T : MessageContextPropertyBase, new()
 {
     return(!context.GetProperty(property).IsNullOrEmpty() && context.IsPromoted(property.Name, property.Namespace));
 }
        private IBaseMessage BuildResponseMessage(IBaseMessage message, IBaseMessageContext context, LoopBackTransmitProperties props)
        {
            Guid callToken  = TraceManager.CustomComponent.TraceIn();
            long startScope = TraceManager.CustomComponent.TraceStartScope("BuildResponseMessage", callToken);

            IBaseMessageFactory messageFactory = _transportProxy.GetMessageFactory();
            IBaseMessage        btsResponse    = messageFactory.CreateMessage();

            TraceManager.CustomComponent.TraceInfo("PropertyCopy: {0}", props.PropertyCopy);
            if (props.PropertyCopy)
            {
                btsResponse.Context = PipelineUtil.CloneMessageContext(context);
            }
            TraceManager.CustomComponent.TraceInfo("CustomPropertyCopy: {0}", props.CustomPropertyCopy);
            if (props.CustomPropertyCopy)
            {
                btsResponse.Context = messageFactory.CreateMessageContext();
                for (int i = 0; i < context.CountProperties; i++)
                {
                    string strName;
                    string strNamespace;
                    object oValue = context.ReadAt(i, out strName, out strNamespace);
                    if (!strNamespace.StartsWith("http://schemas.microsoft.com/BizTalk"))
                    {
                        if (context.IsPromoted(strName, strNamespace))
                        {
                            TraceManager.CustomComponent.TraceInfo("Promoted into context: {1}#{0}={2}", strName, strNamespace, oValue);
                            btsResponse.Context.Promote(strName, strNamespace, oValue);
                        }
                        else
                        {
                            TraceManager.CustomComponent.TraceInfo("Copied into context: {1}#{0}={2}", strName, strNamespace, oValue);
                            btsResponse.Context.Write(strName, strNamespace, oValue);
                        }
                    }
                }
            }
            TraceManager.CustomComponent.TraceInfo("PartCount: {0}", message.PartCount);
            for (int i = 0; i < message.PartCount; i++)
            {
                string        str;
                VirtualStream stream = new VirtualStream();
                StreamReader  rdr    = new StreamReader(message.GetPartByIndex(i, out str).GetOriginalDataStream(), true);
                StreamWriter  wrtr   = new StreamWriter(stream, rdr.CurrentEncoding);
                wrtr.Write(rdr.ReadToEnd());
                rdr.Close();
                wrtr.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                IBaseMessagePart part = messageFactory.CreateMessagePart();
                if (props.PropertyCopy)
                {
                    part.Charset        = message.GetPart(str).Charset;
                    part.ContentType    = message.GetPart(str).ContentType;
                    part.PartProperties = PipelineUtil.CopyPropertyBag(message.GetPart(str).PartProperties, messageFactory);
                }
                btsResponse.AddPart(str, part, message.GetPart(str).PartID.Equals(message.BodyPart.PartID));
                btsResponse.GetPart(str).Data = stream;
            }

            TraceManager.CustomComponent.TraceEndScope("BuildResponseMessage", startScope, callToken);
            TraceManager.CustomComponent.TraceOut(callToken);

            return(btsResponse);
        }