Beispiel #1
0
        public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessagePart bodyPart = pInMsg.BodyPart;

            if (bodyPart != null)
            {
                Stream originalStream = bodyPart.GetOriginalDataStream();

                if (originalStream != null)
                {
                    using (ZipInputStream zipInputStream = new ZipInputStream(originalStream))
                    {
                        if (_password != null && _password.Length > 0)
                        {
                            zipInputStream.Password = _password;
                        }

                        ZipEntry entry = zipInputStream.GetNextEntry();

                        while (entry != null)
                        {
                            MemoryStream memStream = new MemoryStream();
                            byte[]       buffer    = new Byte[1024];

                            int bytesRead = 1024;
                            while (bytesRead != 0)
                            {
                                bytesRead = zipInputStream.Read(buffer, 0, buffer.Length);
                                memStream.Write(buffer, 0, bytesRead);
                            }

                            string fileName  = entry.FileName.ToString();   //file name in zip file
                            string extension = Path.GetExtension(fileName);

                            IBaseMessage outMessage;
                            outMessage = pContext.GetMessageFactory().CreateMessage();
                            outMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);
                            memStream.Position       = 0;
                            outMessage.BodyPart.Data = memStream;


                            IBaseMessageContext context = pInMsg.Context;
                            string receivePortName      = context.Read("ReceivePortName", "http://schemas.microsoft.com/BizTalk/2003/system-properties").ToString();
                            string fullPath             = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();
                            string filePath             = Path.GetDirectoryName(fullPath);

                            outMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);
                            outMessage.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", fileName);
                            outMessage.Context.Promote("ReceivePortName", "http://schemas.microsoft.com/BizTalk/2003/system-properties", receivePortName);

                            _qOutMessages.Enqueue(outMessage);

                            entry = zipInputStream.GetNextEntry();
                        }
                    }
                }
            }
        }
        private string Demote(string original, XPathExpression expr)
        {



           if (expr != null)
           {




               SchemaMetaDataProperty metaDataProperty = m_schemaMetaData.Properties[expr.XPath];
              

               var ret_value = m_context.Read(metaDataProperty.Name, metaDataProperty.Namespace);

               if (ret_value != null)
                return (string)ret_value;

               
           }

           return original;
            
        }
        public static string GetProperty <T>(this IBaseMessageContext context, MessageContextProperty <T, string> property)
            where T : MessageContextPropertyBase, new()
        {
            var value = context.Read(property.Name, property.Namespace);

            return((string)value);
        }
Beispiel #4
0
        public static string GetContextValue(IBaseMessageContext context, string property, string propertyNamespace)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (string.IsNullOrEmpty(property))
            {
                throw new ArgumentNullException("property");
            }
            if (string.IsNullOrEmpty(propertyNamespace))
            {
                throw new ArgumentNullException("propertyNamespace");
            }
            string str = string.Empty;

            try
            {
                object obj = context.Read(property, propertyNamespace);
                if (obj != null)
                {
                    str = obj.ToString();
                }
                return(str);
            }
            catch (Exception ex)
            {
                DECore.TraceProvider.Logger.TraceError(ex);
                return(string.Empty);
            }
        }
        public static TR?GetProperty <T, TR>(this IBaseMessageContext context, MessageContextProperty <T, TR> property)
            where T : MessageContextPropertyBase, new()
            where TR : struct
        {
            var value = context.Read(property.Name, property.Namespace);

            return(value != null ? (TR?)Convert.ChangeType(value, typeof(TR)) : null);
        }
        public static bool TryRead(this IBaseMessageContext ctx, ContextProperty property, out object val)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            return((val = ctx.Read(property.PropertyName, property.PropertyNamespace)) != null);
        }
 private object Extract(IBaseMessageContext context, string prop, string propNS, object fallback, bool isRequired)
 {
     Object o = context.Read(prop, propNS);
     if (!isRequired && null == o)
         return fallback;
     if (null == o)
         throw new NoSuchProperty(propNS + "#" + prop);
     return o;
 }
Beispiel #8
0
        public static object Read(this IBaseMessageContext ctx, ContextProperty property)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            return(ctx.Read(property.PropertyName, property.PropertyNamespace));
        }
Beispiel #9
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessagePart    bodyPart = pInMsg.BodyPart;
            IBaseMessageContext context  = pInMsg.Context;

            // Check if the zip Component is activated
            if (!this.Enabled)
            {
                return(pInMsg);
            }

            string fileName = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();

            if (bodyPart != null)
            {
                string bodyPartName = pInMsg.BodyPartName;
                try
                {
                    Stream currentPartSource = pInMsg.BodyPart.GetOriginalDataStream();
                    byte[] currentPartBuffer = new byte[currentPartSource.Length];
                    currentPartSource.Read(currentPartBuffer, 0, currentPartBuffer.Length);
                    byte[] compressedPartBuffer;

                    using (var outStream = new MemoryStream())
                    {
                        outStream.Write(currentPartBuffer, 0, currentPartBuffer.Length);
                        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
                        {
                            var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);

                            using (Stream entryStream = fileInArchive.Open())
                                using (var fileToCompression = new MemoryStream(currentPartBuffer))
                                {
                                    fileToCompression.CopyTo(entryStream);
                                }
                        }
                        compressedPartBuffer = outStream.ToArray();
                    }

                    MemoryStream tempMemStream = new MemoryStream(currentPartBuffer);
                    pInMsg.BodyPart.Data = tempMemStream;

                    string sourcePartName = fileName + this.FileExtension;

                    pInMsg.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourcePartName);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return(pInMsg);

            #endregion
        }
Beispiel #10
0
        //https://docs.microsoft.com/en-us/biztalk/core/how-to-use-message-context-properties
        //https://docs.microsoft.com/en-us/biztalk/core/file-adapter-property-schema-and-properties
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessageContext context = pInMsg.Context;
            object obj = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties");
            //fileName = ((string)obj).Substring(((string)obj).LastIndexOf("\\") + 1);
            string fullPath = Path.GetFullPath((string)obj);
            string fileName = Path.GetFileName(fullPath);
            string filePath = Path.GetDirectoryName(fullPath);

            Byte[]           TextFileBytes = null;
            IBaseMessagePart msgBodyPart   = pInMsg.BodyPart;

            //Creating outMessage
            IBaseMessage outMessage;

            outMessage = pContext.GetMessageFactory().CreateMessage();

            if (msgBodyPart != null)
            {
                outMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);
                Stream msgBodyPartStream = msgBodyPart.GetOriginalDataStream();
                TextFileBytes = StreamToByteArray(msgBodyPartStream);
                outMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);


                IDictionary <string, Byte[]> lst = new Dictionary <string, Byte[]>();
                lst.Add(fileName, TextFileBytes);

                MemoryStream ms = new MemoryStream();
                ms.Seek(0, SeekOrigin.Begin);

                using (ZipFile zip = new ZipFile())
                {
                    //zip.Password = _password;
                    if (_password != null)
                    {
                        zip.Password = _password;
                    }
                    zip.Encryption       = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

                    foreach (KeyValuePair <string, Byte[]> item in (IDictionary <string, Byte[]>)lst)
                    {
                        zip.AddEntry(item.Key, item.Value); //Key:fileName, Value:TextFileBytes
                    }
                    zip.Save(ms);
                }

                ms.Position = 0;
                outMessage.BodyPart.Data = ms;
                outMessage.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", fileName.Substring(0, fileName.IndexOf(".")));
            }
            return(outMessage);
        }
Beispiel #11
0
 /// <summary>
 /// Gets Property Value.
 /// </summary>
 /// <param name="iBaseMsg"></param>
 /// <param name="pName"></param>
 /// <param name="pNamespace"></param>
 /// <returns></returns>
 private string ReadProperty(IBaseMessageContext msgContext, string pName, string pNamespace)
 {
     try
     {
         return(msgContext.Read(pName, pNamespace).ToString());
     }
     catch (Exception)
     {
         return(string.Empty);
     }
 }
Beispiel #12
0
        public static bool TryRead(this IBaseMessageContext ctx, ContextProperty property, out string val)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            val = ctx.Read(property.PropertyName, property.PropertyNamespace) as string;

            return(!string.IsNullOrWhiteSpace(val));
        }
Beispiel #13
0
        public static string GetContextProperty(IBaseMessageContext messageContext, string propertyName, string propertyNamespace)
        {
            string result = "";

            object contextProperty = messageContext.Read(propertyName, propertyNamespace);

            if (contextProperty != null)
            {
                return((string)contextProperty);
            }

            return(result);
        }
Beispiel #14
0
        public string Read(string name, string ns)
        {
            if (name == "MessageID" && ns == systemPropertiesNamespace)
            {
                return(messageID);
            }

            object property = null;

            property = context.Read(name, ns);

            return(property == null ? String.Empty : property.ToString());
        }
Beispiel #15
0
        private object Extract(IBaseMessageContext context, string prop, string propNs, object fallback, bool isRequired)
        {
            Object o = context.Read(prop, propNs);

            if (!isRequired && null == o)
            {
                return(fallback);
            }
            if (null == o)
            {
                throw new NoSuchProperty(propNs + "#" + prop);
            }
            return(o);
        }
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

            if (!Validate(out errorMessage))
            {
                throw new ArgumentException(errorMessage);
            }

            //component will not be executed if the property is set to true
            if (Disabled)
            {
                return(pInMsg);
            }

            //get the value from the provided property
            IBaseMessageContext context = pInMsg.Context;
            string key = (string)context.Read(new ContextProperty(PropertyPath)); // PropertyPath.Split('#')[1], PropertyPath.Split('#')[0]).ToString();

            //query the sharepoint table
            var    lookupService = new LookupUtilityService(new SharepointLookupRepository());
            string result        = "";

            try
            {
                result = lookupService.GetValue(ListName, key, true);
            }catch (ArgumentException ex)
            {
                if (ThrowException)
                {
                    throw ex;
                }
                else
                {
                    System.Diagnostics.EventLog.WriteEntry(pContext.PipelineName, ex.Message, System.Diagnostics.EventLogEntryType.Warning);
                }
            }

            //promote the result to the provided destination property
            if (PromoteProperty)
            {
                pInMsg.Context.Promote(new ContextProperty(DestinationPath), result);
            }
            else
            {
                pInMsg.Context.Write(new ContextProperty(DestinationPath), result);
            }

            return(pInMsg);
        }
Beispiel #17
0
        public DotNetFileTransmitProperties(IBaseMessage message, string propertyNamespace)
        {
            XmlDocument locationConfigDom = null;

            //  get the adapter configuration off the message
            IBaseMessageContext context = message.Context;
            string config = (string)context.Read("AdapterConfig", propertyNamespace);

            //  the config can be null all that means is that we are doing a dynamic send
            if (null != config)
            {
                locationConfigDom = new XmlDocument();
                locationConfigDom.LoadXml(config);

                this.ReadLocationConfiguration(locationConfigDom);
            }
        }
Beispiel #18
0
        private OrderedDictionary PopulateHeaderFromContext(IBaseMessageContext msgContext)
        {
            OrderedDictionary header = new OrderedDictionary();

            string[] contextPropertiesForHeader = ContextPropertiesForHeader.Split(';');

            foreach (string contextPro in contextPropertiesForHeader)
            {
                string[] propertySet = contextPro.Split('#');
                if (propertySet.Length == 2)
                {
                    string value = (string)msgContext.Read(propertySet[1], propertySet[0]);
                    header.Add(propertySet[1], value ?? string.Empty);
                }
            }

            return(header);
        }
Beispiel #19
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="message"></param>
        /// <param name="propertyNamespace"></param>
        public SftpTransmitProperties(IBaseMessage message, string propertyNamespace)
        {
            //  get the adapter configuration off the message
            IBaseMessageContext context = message.Context;
            string config = (string)context.Read("AdapterConfig", propertyNamespace);

            if (null != config)
            {
                var locationConfigDom = new XmlDocument();
                locationConfigDom.LoadXml(config);

                ReadLocationConfiguration(locationConfigDom);
            }
            else //  the config can be null all that means is that we are doing a dynamic send
            {
                ReadLocationConfiguration(message.Context);
            }
        }
Beispiel #20
0
        public static bool TryRead <T>(this IBaseMessageContext ctx, ContextProperty property, out T val)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }
            object content = ctx.Read(property.PropertyName, property.PropertyNamespace);

            if (content is T)
            {
                val = (T)content;
                return(true);
            }
            else
            {
                val = default(T);
                return(false);
            }
        }
Beispiel #21
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            string errorMessage;

            if (!Validate(out errorMessage))
            {
                throw new ArgumentException(errorMessage);
            }

            //Component will not be executed if the property is set to true
            if (Disabled)
            {
                return(pInMsg);
            }

            IBaseMessageContext context = pInMsg.Context;

            string[] PropertyPathList = PropertyPaths.Split(';');
            string[] HeaderNamesList  = HeaderNames.Split(';');

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < PropertyPathList.Length; i++)
            {
                sb.Append(HeaderNamesList[i] + ":" + (string)context.Read(new ContextProperty(PropertyPathList[i])));

                if (i < PropertyPathList.Length - 1)
                {
                    sb.Append(" ");
                }
            }
            string HttpHeaders = sb.ToString();

            if (PromoteProperty)
            {
                pInMsg.Context.Promote(new ContextProperty(DestinationPath), HttpHeaders);
            }
            else
            {
                pInMsg.Context.Write(new ContextProperty(DestinationPath), HttpHeaders);
            }
            return(pInMsg);
        }
Beispiel #22
0
        /// <summary>
        /// Returns the Message Properties based on DbPropList
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected string GetMessageProperties(IBaseMessageContext context)
        {
            //Get Msg Properties
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<MessageProperties>");
            string name;
            string nspace;

            for (int loop = 0; loop < context.CountProperties; loop++)
            {
                context.ReadAt(loop, out name, out nspace);
                string value = context.Read(name, nspace).ToString();
                sb.AppendLine(string.Format("<{0}>{1}</{0}>", name, value));
            }

            sb.AppendLine("</MessageProperties>");
            return(sb.ToString());
        }
        public string ReadProperties(IBaseMessage msg)
        {
            IBaseMessageContext ctx = msg.Context;
            string name;
            string nspace;
            List <ContextProperty> contextProperties = new List <AtomicScope.ContextProperty>();

            for (int i = 0; i < ctx.CountProperties; i++)
            {
                ctx.ReadAt(i, out name, out nspace);
                string value = ctx.Read(name, nspace).ToString();
                contextProperties.Add(new ContextProperty()
                {
                    Name      = name,
                    NameSpace = nspace,
                    Value     = value
                });
            }
            return(JsonConvert.SerializeObject(contextProperties));
        }//Business Layer
        }//Business Layer

        public List <ContextProperty> ReadContextProperty(IBaseMessage msg, string PropertyName, string Namespace)
        {
            IBaseMessageContext ctx = msg.Context;
            string name;
            string nspace;
            List <ContextProperty> contextProperties = new List <AtomicScope.ContextProperty>();

            for (int i = 0; i < ctx.CountProperties; i++)
            {
                ctx.ReadAt(i, out name, out nspace);
                string PropertyValue = ctx.Read(name, nspace).ToString();
                contextProperties.Add(new ContextProperty()
                {
                    Name      = name,
                    NameSpace = nspace,
                    Value     = PropertyValue
                });
            }
            return(contextProperties);
        }
Beispiel #25
0
        /// <summary>
        /// Retrieves the value of Property from Message Context by Name and namespace
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected string GetPropertyContext(IBaseMessageContext context, string name, string ns)
        {
            string result = string.Empty;

            if (context != null)
            {
                try
                {
                    var res = context.Read(name, ns);
                    if (res != null)
                    {
                        result = res.ToString();
                    }
                }
                catch
                {
                    //Ignore and return empty string
                }
            }
            return(result);
        }
 public virtual void Execute(IBaseMessageContext messageContext, string originalValue, ref string newValue)
 {
     if (messageContext == null)
     {
         throw new ArgumentNullException(nameof(messageContext));
     }
     if (ExtractionMode == ExtractionMode.Write)
     {
         if (_logger.IsDebugEnabled)
         {
             _logger.DebugFormat("Writing property {0} with value {1} to context.", PropertyName, originalValue);
         }
         messageContext.Write(PropertyName.Name, PropertyName.Namespace, originalValue);
     }
     else if (ExtractionMode == ExtractionMode.Promote)
     {
         if (_logger.IsDebugEnabled)
         {
             _logger.DebugFormat("Promoting property {0} with value {1} to context.", PropertyName, originalValue);
         }
         messageContext.Promote(PropertyName.Name, PropertyName.Namespace, originalValue);
     }
     else if (ExtractionMode == ExtractionMode.Demote)
     {
         var @object = messageContext.Read(PropertyName.Name, PropertyName.Namespace);
         var value   = @object.IfNotNull(o => o.ToString());
         if (!value.IsNullOrEmpty())
         {
             newValue = value;
             if (_logger.IsDebugEnabled)
             {
                 _logger.DebugFormat("Demoting property {0} with value {1} from context.", PropertyName, newValue);
             }
         }
     }
     else
     {
         base.Execute(messageContext);
     }
 }
        IBaseMessage Microsoft.BizTalk.Component.Interop.IComponent.Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            System.Diagnostics.Trace.WriteLine(">>> PgpEncrypt.Execute ()  v.3");
            IBaseMessagePart    bodyPart = pInMsg.BodyPart;
            IBaseMessageContext context  = pInMsg.Context;
            string filename = "";

            if (bodyPart != null)
            {
                filename = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();

                if (filename.Contains("\\"))
                {
                    filename = filename.Substring(filename.LastIndexOf("\\") + 1);
                }
                if (filename.Contains("/"))
                {
                    filename = filename.Substring(filename.LastIndexOf("/") + 1);
                }

                if (!String.IsNullOrEmpty(tempDirectory))
                {
                    if (!Directory.Exists(this.tempDirectory))
                    {
                        Directory.CreateDirectory(this.tempDirectory);
                    }
                }
                filename = Path.Combine(this.tempDirectory, filename);

                string tempFile = Path.Combine(this.tempDirectory, Guid.NewGuid().ToString());

                Stream encStream = PGPWrapper.EncryptStream(bodyPart.Data, this.pubKeyFile, tempFile, this.extension, this.asciiArmorFlag, this.integrityCheckFlag);

                encStream.Seek(0, SeekOrigin.Begin);
                bodyPart.Data = encStream;
                pContext.ResourceTracker.AddResource(encStream);
                context.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", filename + ".pgp");
            }
            return(pInMsg);
        }
        public PowershellTransmitterProperties(IBaseMessage message, string propertyNamespace)
        {
            XmlDocument locationConfigDom = null;

            //  get the adapter configuration off the message
            IBaseMessageContext context = message.Context;
            string config = (string)context.Read("AdapterConfig", propertyNamespace);

            //  the config can be null all that means is that we are doing a dynamic send
            if (null != config)
            {
                locationConfigDom = new XmlDocument();
                locationConfigDom.LoadXml(config);

                Uri = Extract(locationConfigDom, "/Config/uri", string.Empty);

                script   = Extract(locationConfigDom, "/Config/script", string.Empty);
                host     = IfExistsExtract(locationConfigDom, "Config/host", string.Empty);
                user     = IfExistsExtract(locationConfigDom, "Config/user", string.Empty);
                password = IfExistsExtract(locationConfigDom, "Config/password", string.Empty);
            }
        }
        IBaseMessage Microsoft.BizTalk.Component.Interop.IComponent.Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            System.Diagnostics.Trace.WriteLine(">>> PgpDecrypt.Execute () v.3");
            IBaseMessagePart    bodyPart = pInMsg.BodyPart;
            IBaseMessageContext context  = pInMsg.Context;
            string filename = "";

            if (bodyPart != null)
            {
                filename = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();

                if (filename.Contains("\\"))
                {
                    filename = filename.Substring(filename.LastIndexOf("\\") + 1);
                }
                if (filename.Contains("/"))
                {
                    filename = filename.Substring(filename.LastIndexOf("/") + 1);
                }

                if (0 < this.tempDirectory.Length)
                {
                    if (!Directory.Exists(this.tempDirectory))
                    {
                        Directory.CreateDirectory(this.tempDirectory);
                    }
                }
                filename = Path.Combine(this.tempDirectory, filename);
                string tempFile = Path.Combine(this.tempDirectory, Guid.NewGuid().ToString());

                Stream decStream = PGPWrapper.DecryptStream(bodyPart.Data, this.privateKeyFile, this.passphrase, tempFile, this.tempDirectory);

                decStream.Seek(0, SeekOrigin.Begin);
                bodyPart.Data = decStream;
                pContext.ResourceTracker.AddResource(decStream);
                context.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", filename.Replace(".pgp", ""));
            }
            return(pInMsg);
        }
Beispiel #30
0
        public static Guid GetPrimaryCorrelationId(IBaseMessageContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context", "Unable to attempt to get the PrimaryCorrelationId from the message context becasue the context passed was null.");
            }

            var primaryCorrelationIdValue = context.Read(PrimaryCorrelationId_propertyName, PrimaryCorrelationId_propertyNs) as string;

            if (string.IsNullOrWhiteSpace(primaryCorrelationIdValue))
            {
                throw new MissingPrimaryCorrelationIdException(string.Concat("Unable to get the PrimaryCorrelationId from the message context. No value was found for context property \"", PrimaryCorrelationId_propertyName, "\" in namepsace \"", PrimaryCorrelationId_propertyNs, "\"."));
            }

            Guid primaryCorrelationId;

            if (!Guid.TryParse(primaryCorrelationIdValue ?? string.Empty, out primaryCorrelationId))
            {
                throw new InvalidPrimaryCorrelationIdException(string.Concat("Unable to get the PrimaryCorrelationId from the message context. The value for context property \"", PrimaryCorrelationId_propertyName, "\" in namepsace \"", PrimaryCorrelationId_propertyNs, "\" was not a valid System.Guid. Value was \"", primaryCorrelationIdValue, "\"."));
            }

            return(primaryCorrelationId);
        }
        /// <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;
            }
        }