コード例 #1
0
        protected override void SetContextProperties(IBaseMessageContext pipelineContext, Dictionary <string, string> ResolverDictionary)
        {
            // Need to use http_legacy because ESB is looking for hard coded "http" for WCF Basic
            string str = ResolverDictionary["Resolver.TransportLocation"];
            // String should be "http_legacy://something/something"
            string correctedLocation = str.Replace("http_legacy", "http");

            pipelineContext.Write(BtsProperties.OutboundTransportLocation.Name, BtsProperties.OutboundTransportLocation.Namespace, correctedLocation);
            pipelineContext.Write(BtsProperties.OutboundTransportType.Name, BtsProperties.OutboundTransportType.Namespace, this.AdapterName);
        }
 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}'.");
     }
 }
コード例 #3
0
        /// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message</param>
        /// <returns>Original input message</returns>
        /// <remarks>
        /// IComponent.Execute method is used to initiate
        /// the processing of the message in this pipeline component.
        /// </remarks>
        public Microsoft.BizTalk.Message.Interop.IBaseMessage Execute(Microsoft.BizTalk.Component.Interop.IPipelineContext pc, Microsoft.BizTalk.Message.Interop.IBaseMessage inmsg)
        {
            //
            // TODO: implement component logic
            //
            // this way, it's a passthrough pipeline component
            IBaseMessageContext context = inmsg.Context;
            Stream            inStream  = inmsg.BodyPart.Data;
            XslTransmitHelper transmit  = new XslTransmitHelper(this.XslPath, this.XPathSourceFileName, this.EnableValidateNamespace, this.AllowPassThruTransmit);

            if (!string.IsNullOrEmpty(this.XPathSourceFileName))
            {
                string sourceFileName = transmit.GetSourceFileName(XmlReader.Create(inStream), this.XPathSourceFileName);
                if (!string.IsNullOrEmpty(sourceFileName))
                {
                    context.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourceFileName);
                    context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourceFileName);
                }
                inStream.Seek(0, SeekOrigin.Begin);
            }
            var outStream = transmit.Transmit(inStream);

            inmsg.BodyPart.Data = outStream;
            pc.ResourceTracker.AddResource(outStream);



            return(inmsg);
        }
コード例 #4
0
        /// <summary>
        /// Synchronously executes the task using the specified <see cref="RuntimeTaskExecutionContext"/> execution context object.
        /// </summary>
        /// <param name="context">The execution context.</param>
        public override void Run(RuntimeTaskExecutionContext context)
        {
            var callToken = TraceManager.CustomComponent.TraceIn();

            IBaseMessageFactory msgFactory     = context.PipelineContext.GetMessageFactory();
            IBaseMessage        responseMsg    = msgFactory.CreateMessage();
            IBaseMessageContext responseMsgCtx = msgFactory.CreateMessageContext();
            IBaseMessageContext requestMsgCtx  = context.Message.Context;

            responseMsg.Context = responseMsgCtx;

            if (BizTalkUtility.ContainsResponsePart(context.Message))
            {
                IBaseMessagePart responsePart = BizTalkUtility.GetResponsePart(context.Message);
                responseMsg.AddPart(context.Message.BodyPartName, responsePart, true);
            }
            else
            {
                responseMsg.AddPart(context.Message.BodyPartName, context.Message.BodyPart, true);
            }

            responseMsgCtx.Promote(EpmRRCorrelationToken.Name.Name, EpmRRCorrelationToken.Name.Namespace, requestMsgCtx.Read(EpmRRCorrelationToken.Name.Name, EpmRRCorrelationToken.Name.Namespace));
            responseMsgCtx.Promote(RouteDirectToTP.Name.Name, RouteDirectToTP.Name.Namespace, true);
            responseMsgCtx.Promote(CorrelationToken.Name.Name, CorrelationToken.Name.Namespace, requestMsgCtx.Read(CorrelationToken.Name.Name, CorrelationToken.Name.Namespace));
            responseMsgCtx.Promote(ReqRespTransmitPipelineID.Name.Name, ReqRespTransmitPipelineID.Name.Namespace, requestMsgCtx.Read(ReqRespTransmitPipelineID.Name.Name, ReqRespTransmitPipelineID.Name.Namespace));
            responseMsgCtx.Write(ReceivePipelineResponseConfig.Name.Name, ReceivePipelineResponseConfig.Name.Namespace, requestMsgCtx.Read(ReceivePipelineResponseConfig.Name.Name, ReceivePipelineResponseConfig.Name.Namespace));

            context.Message = responseMsg;

            TraceManager.CustomComponent.TraceOut(callToken);
        }
 public override void Execute(IBaseMessageContext messageContext)
 {
     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, Value);
         }
         messageContext.Write(PropertyName.Name, PropertyName.Namespace, Value);
     }
     else if (ExtractionMode == ExtractionMode.Promote)
     {
         if (_logger.IsDebugEnabled)
         {
             _logger.DebugFormat("Promoting property {0} with value {1} to context.", PropertyName, Value);
         }
         messageContext.Promote(PropertyName.Name, PropertyName.Namespace, Value);
     }
     else
     {
         base.Execute(messageContext);
     }
 }
コード例 #6
0
ファイル: Manipulator.cs プロジェクト: radtek/DevOps
        /// <summary>
        /// Writes to message context
        /// </summary>
        /// <param name="value"></param>
        /// <param name="propertyName"></param>
        /// <param name="messageContext"></param>
        /// <returns></returns>
        private IBaseMessageContext WriteToMessageContextAndPromote(string value, string serializedContextProperty, IBaseMessageContext messageContext, bool promoteProperty)
        {
            MessageContextDescription msgContextDes = (MessageContextDescription)SerializeToObject(typeof(MessageContextDescription), serializedContextProperty);

            if (!string.IsNullOrEmpty(value))
            {
                if (!string.IsNullOrEmpty(msgContextDes.PropertyName) && !string.IsNullOrEmpty(msgContextDes.PropertyNamespace))
                {
                    //Check whether writng to OutboundTransportLocation
                    if (msgContextDes.PropertyName.Equals(BtsProperties.OutboundTransportLocation.Name, StringComparison.InvariantCultureIgnoreCase) &&
                        msgContextDes.PropertyNamespace.Equals(BtsProperties.OutboundTransportLocation.Namespace, StringComparison.InvariantCultureIgnoreCase))
                    {
                        FileInfo fileInfo = new FileInfo(value);

                        if (!Directory.Exists(fileInfo.DirectoryName))
                        {
                            Directory.CreateDirectory(fileInfo.DirectoryName);
                        }
                    }

                    if (promoteProperty)
                    {
                        messageContext.Promote(msgContextDes.PropertyName, msgContextDes.PropertyNamespace, value);
                    }
                    else
                    {
                        messageContext.Write(msgContextDes.PropertyName, msgContextDes.PropertyNamespace, value);
                    }
                }
            }

            return(messageContext);
        }
コード例 #7
0
        /// <summary>
        /// Loads a BizTalk message from the set of files exported from
        /// the BizTalk Admin Console or HAT
        /// </summary>
        /// <param name="contextFile">Path to the *_context.xml file</param>
        /// <returns>The loaded message</returns>
        /// <remarks>
        /// Context files have no type information for properties
        /// in the message context, so all properties are
        /// added as strings to the context.
        /// </remarks>
        public static IBaseMessage LoadMessage(string contextFile)
        {
            IBaseMessage        msg  = _factory.CreateMessage();
            IBaseMessageContext ctxt = _factory.CreateMessageContext();

            msg.Context = ctxt;

            XPathDocument     doc   = new XPathDocument(contextFile);
            XPathNavigator    nav   = doc.CreateNavigator();
            XPathNodeIterator props = nav.Select("//Property");

            foreach (XPathNavigator prop in props)
            {
                ctxt.Write(
                    prop.GetAttribute("Name", ""),
                    prop.GetAttribute("Namespace", ""),
                    prop.GetAttribute("Value", "")
                    );
            }

            XPathNodeIterator parts = nav.Select("//MessagePart");

            foreach (XPathNavigator part in parts)
            {
                LoadPart(msg, part, contextFile);
            }
            return(msg);
        }
コード例 #8
0
 public static void SetProperty <T>(this IBaseMessageContext context, MessageContextProperty <T, string> property, string value)
     where T : MessageContextPropertyBase, new()
 {
     if (value != null)
     {
         context.Write(property.Name, property.Namespace, value);
     }
 }
コード例 #9
0
        public void Write(string name, string ns, object value)
        {
            if (value == null || String.IsNullOrEmpty(name) || String.IsNullOrEmpty(ns))
            {
                return;
            }

            context.Write(name, ns, value);
        }
コード例 #10
0
 internal IBaseMessage AddContextValue(string name, string nspace, bool isPromoted, object value)
 {
     if (isPromoted)
     {
         _context.Promote(name, nspace, value);
     }
     else
     {
         _context.Write(name, nspace, value);
     }
     return(this);
 }
コード例 #11
0
        public static void Write(this IBaseMessageContext ctx, ContextProperty property, object val)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (val == null)
            {
                throw new ArgumentNullException("val");
            }

            ctx.Write(property.PropertyName, property.PropertyNamespace, val);
        }
コード例 #12
0
        private string GetContextTransform(IBaseMessageContext context)
        {
            for (int i = 0; i < context.CountProperties; i++)
            {
                string name;
                string ns;

                object obj = context.ReadAt(i, out name, out ns);

                if (name == "XSLTransform")
                {
                    context.Write(name, ns, null);//Remove context as we do not want it to interfere
                    return((string)obj);
                }
            }

            return(null);
        }
コード例 #13
0
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            try
            {
                IBaseMessageContext msgContext = pInMsg.Context;
                msgContext.Write(customPromotedPropertyName, customPromotedPropertyNameSpace, customPromotedPropertyValue);
                msgContext.Promote(customPromotedPropertyName, customPromotedPropertyNameSpace, customPromotedPropertyValue);
            }
            catch (Exception ex)
            {
                if (pInMsg != null)
                {
                    pInMsg.SetErrorInfo(ex);
                }
                throw ex;
            }

            return(pInMsg);
        }
コード例 #14
0
ファイル: Manipulator.cs プロジェクト: radtek/DevOps
        /// <summary>
        /// Write to http header
        /// </summary>
        /// <param name="value"></param>
        /// <param name="headerKeyName"></param>
        /// <param name="messageContext"></param>
        /// <returns></returns>
        private IBaseMessageContext WriteToHttpHeader(string value, string headerKeyName, IBaseMessageContext messageContext)
        {
            string httpHeader = ReadProperty(messageContext, "HttpHeaders", "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties");

            if (!string.IsNullOrEmpty(httpHeader) && httpHeader.EndsWith(Environment.NewLine))
            {
                httpHeader += headerKeyName + ": " + value + Environment.NewLine;
            }
            else if (!string.IsNullOrEmpty(httpHeader))
            {
                httpHeader += Environment.NewLine + headerKeyName + ": " + value + Environment.NewLine;
            }
            else
            {
                httpHeader = headerKeyName + ": " + value + Environment.NewLine;
            }
            messageContext.Write("HttpHeaders", "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties", httpHeader);

            return(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);
        }
コード例 #16
0
 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);
     }
 }
コード例 #17
0
        public static IBaseMessageContext GetMininalContext(IPipelineContext pipelineContext, IBaseMessage message)
        {
            IBaseMessageContext outputContext = pipelineContext.GetMessageFactory().CreateMessageContext();

            foreach (var context in minMessageContext)
            {
                var value = message.Context.Read(context.Item1, context.Item2);
                if (value != null)
                {
                    var isPromoted = message.Context.IsPromoted(context.Item1, context.Item2);
                    if (isPromoted || context.Item3)
                    {
                        outputContext.Promote(context.Item1, context.Item2, value);
                    }
                    else
                    {
                        outputContext.Write(context.Item1, context.Item2, value);
                    }
                }
            }
            return(outputContext);
        }
        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);
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        public static IBaseMessageContext CloneAndExcludeESBProperties(IPipelineContext pipelineContext, IBaseMessage message)
        {
            IBaseMessageContext outputContext = pipelineContext.GetMessageFactory().CreateMessageContext();

            for (int i = 0; i < message.Context.CountProperties; i++)
            {
                var name      = string.Empty;
                var nameSpace = string.Empty;
                var value     = message.Context.ReadAt(i, out name, out nameSpace);
                if (!nameSpace.Equals(itineraryNamespace, StringComparison.InvariantCultureIgnoreCase) && value != null)
                {
                    var isPromoted = message.Context.IsPromoted(name, nameSpace);
                    if (isPromoted)
                    {
                        outputContext.Promote(name, nameSpace, value);
                    }
                    else
                    {
                        outputContext.Write(name, nameSpace, value);
                    }
                }
            }
            return(outputContext);
        }
コード例 #21
0
 public static void DeleteProperty <T, TR>(this IBaseMessageContext context, MessageContextProperty <T, TR> property)
     where T : MessageContextPropertyBase, new()
     where TR : struct
 {
     context.Write(property.Name, property.Namespace, null);
 }
コード例 #22
0
 public static void Write(this IBaseMessageContext ctx, ContextProperty property, object val)
 {
     ctx.Write(property.Name, property.Namespace, val);
 }
コード例 #23
0
        /// <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;
            }
        }
        protected override void SetContextProperties(IBaseMessageContext pipelineContext, System.Collections.Generic.Dictionary <string, string> ResolverDictionary)
        {
            var _transportLocation = ResolverDictionary["Resolver.TransportLocation"];
            var _endpointConfig    = ResolverDictionary["Resolver.EndpointConfig"];
            var _operation         = ResolverDictionary["Resolver.Action"];

            EventLogger.Write(string.Format("Resolver retorna la accion de {0}.", _operation));
            pipelineContext.Write(BtsProperties.OutboundTransportLocation.Name, BtsProperties.OutboundTransportLocation.Namespace, _transportLocation);
            pipelineContext.Write(BtsProperties.OutboundTransportType.Name, BtsProperties.OutboundTransportType.Namespace, AdapterName);

            var customProps = new Dictionary <string, string>();

            customProps = _endpointConfig.ParseKeyValuePairs(true);
            EventLogger.Write("Custom properties");



            pipelineContext.Promote(WebHttpOptions.Operation.Name, WebHttpOptions.Operation.Namespace, _operation);

            pipelineContext.Write(WebHttpOptions.Action.Name, WebHttpOptions.Action.Namespace, _operation);
            pipelineContext.Write(WebHttpOptions.HttpMethodAndUrl.Name, WebHttpOptions.HttpMethodAndUrl.Namespace, customProps.GetValue("HttpMethodAndUrl"));
            pipelineContext.Write(WebHttpOptions.HttpHeaders.Name, WebHttpOptions.HttpHeaders.Namespace, customProps.GetValue("HttpHeaders"));
            pipelineContext.Write(WebHttpOptions.VariablePropertyMapping.Name, WebHttpOptions.VariablePropertyMapping.Namespace, customProps.GetValue("VariablePropertyMapping"));
            pipelineContext.Write(WebHttpOptions.SuppressMessageBodyForHttpVerbs.Name, WebHttpOptions.SuppressMessageBodyForHttpVerbs.Namespace, customProps.GetValue("SuppressMessageBodyForHttpVerbs"));
            pipelineContext.Write(WebHttpOptions.SecurityMode.Name, WebHttpOptions.SecurityMode.Namespace, customProps.GetValue("SecurityMode"));
            pipelineContext.Write(WebHttpOptions.TransportClientCredentialType.Name, WebHttpOptions.TransportClientCredentialType.Namespace, customProps.GetValue("TransportClientCredentialType"));
            pipelineContext.Write(WebHttpOptions.UserName.Name, WebHttpOptions.UserName.Namespace, customProps.GetValue("UserName"));
            pipelineContext.Write(WebHttpOptions.Password.Name, WebHttpOptions.Password.Namespace, customProps.GetValue("Password"));
            pipelineContext.Write(WebHttpOptions.SendTimeout.Name, WebHttpOptions.SendTimeout.Namespace, customProps.GetValue("SendTimeout"));
            pipelineContext.Write(WebHttpOptions.OpenTimeout.Name, WebHttpOptions.OpenTimeout.Namespace, customProps.GetValue("OpenTimeout"));
            pipelineContext.Write(WebHttpOptions.CloseTimeout.Name, WebHttpOptions.CloseTimeout.Namespace, customProps.GetValue("CloseTimeout"));
            pipelineContext.Write(WebHttpOptions.ProxyToUse.Name, WebHttpOptions.ProxyToUse.Namespace, customProps.GetValue("ProxyToUse"));
            pipelineContext.Write(WebHttpOptions.ProxyAddress.Name, WebHttpOptions.ProxyAddress.Namespace, customProps.GetValue("ProxyAddress"));
        }
コード例 #25
0
        public static string ExpandFileName(IBaseMessageContext messageContext, string messageId, string inFileName)
        {
            string outFileName = inFileName;

            bool bUpdateOutFileName = false;

            if (outFileName.Contains("%"))
            {
                if (outFileName.Contains("%SourceFileName%"))
                {
                    string sourceFileName = GetContextProperty(messageContext, "ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties");
                    if (!string.IsNullOrWhiteSpace(sourceFileName))
                    {
                        outFileName        = outFileName.Replace("%SourceFileName%", sourceFileName);
                        bUpdateOutFileName = true;
                    }
                }

                // need to expand macros
                if (outFileName.Contains("%MessageID%"))
                {
                    outFileName        = outFileName.Replace("%MessageID%", messageId.ToUpper());
                    bUpdateOutFileName = true;
                }

                if (outFileName.Contains("%datetime_bts2000%"))
                {
                    string tempDate = DateTime.UtcNow.ToString("yyyyMMddHHmmssf");
                    outFileName        = outFileName.Replace("%datetime_bts2000%", tempDate);
                    bUpdateOutFileName = true;
                }

                if (outFileName.Contains("%datetime%"))
                {
                    string tempDate = DateTime.UtcNow.ToString("yyyy-MM-ddTHHmmss");
                    outFileName        = outFileName.Replace("%datetime%", tempDate);
                    bUpdateOutFileName = true;
                }

                if (outFileName.Contains("%datetime.tz%"))
                {
                    string tempDate = DateTime.UtcNow.ToString("yyyy-MM-ddTHHmmsszzz");
                    outFileName        = outFileName.Replace("%datetime.tz%", tempDate);
                    bUpdateOutFileName = true;
                }

                if (outFileName.Contains("%time%"))
                {
                    string tempDate = DateTime.UtcNow.ToString("HHmmss");
                    outFileName        = outFileName.Replace("%time%", tempDate);
                    bUpdateOutFileName = true;
                }

                if (outFileName.Contains("%time.tz%"))
                {
                    string tempDate = DateTime.UtcNow.ToString("HHmmsszzz");
                    outFileName        = outFileName.Replace("%time.tz%", tempDate);
                    bUpdateOutFileName = true;
                }

                if (bUpdateOutFileName)
                {
                    // update context property
                    messageContext.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", outFileName);
                }
            }

            return(outFileName);
        }
コード例 #26
0
 public static void SetProperty <T, TV>(this IBaseMessageContext context, MessageContextProperty <T, TV> property, TV value)
     where T : MessageContextPropertyBase, new()
     where TV : struct
 {
     context.Write(property.Name, property.Namespace, value);
 }
        /// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message.</param>
        /// <returns>Processed input message with appended or prepended data.</returns>
        /// <remarks>
        /// IComponent.Execute method is used to initiate
        /// the processing of the message in pipeline component.
        /// </remarks>
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            if (Enabled == false)
            {
                return(pInMsg);
            }

            if (null == pContext)
            {
                throw new ArgumentNullException("PC is null");
            }
            if (null == pInMsg)
            {
                throw new ArgumentNullException("pInMsg is null");
            }

            IBaseMessageContext messageContext = pInMsg.Context;

            if (pInMsg.BodyPart == null)
            {
                return(pInMsg);
            }
            IBaseMessagePart bodyPart = pInMsg.BodyPart;


            // send or receive
            string pipelineType = "";

            switch (pContext.StageID.ToString())
            {
            case CategoryTypes.CATID_Decoder:     // should only be here on receive
            case CategoryTypes.CATID_DisassemblingParser:
            case CategoryTypes.CATID_Validate:
            case CategoryTypes.CATID_PartyResolver:
                pipelineType = "Receive";
                break;

            case CategoryTypes.CATID_Encoder:     // should only be here on send
            case CategoryTypes.CATID_Transmitter:
            case CategoryTypes.CATID_AssemblingSerializer:
                pipelineType = "Send";
                break;

            default:
                pipelineType = "Unknown Pipeline Stage - " + pContext.StageID.ToString();
                break;
            }

            if (pipelineType.StartsWith("Unknown"))
            {
                throw new ApplicationException(pipelineType);
            }

            if (pipelineType == "Receive")
            {
                // do Receive
                string relativeURI = "";
                string fullURI     = "";

                Stream originalStrm = bodyPart.GetOriginalDataStream();

                if (originalStrm != null)
                {
                    StreamReader sr   = new StreamReader(originalStrm);
                    string       body = sr.ReadToEnd();

                    AzureClaimCheckPipelineComponentHelper.ParseInboundBody(body, ref fullURI, ref relativeURI);

                    string _storageAccount = "";
                    // if it is relative URI, storage account name must be in pipeline configuraion
                    if (!string.IsNullOrEmpty(relativeURI))
                    {
                        if (!string.IsNullOrEmpty(StorageAccountName))
                        {
                            _storageAccount = StorageAccountName;
                        }
                        else
                        {
                            throw new ApplicationException(string.Format("StorageAccountName not found, required with RelativeURI"));
                        }
                    }

                    // if fullURI then storage account name can be derived
                    if (!string.IsNullOrEmpty(fullURI))
                    {
                        Uri    blobLocation = new Uri(fullURI);
                        string hostURI      = blobLocation.Host;
                        if (!string.IsNullOrEmpty(StorageAccountName))
                        {
                            _storageAccount = hostURI.Substring(0, hostURI.IndexOf("."));
                        }
                        relativeURI = blobLocation.PathAndQuery;
                    }

                    // get SB Properties in not specified in pipeline configuration
                    if (string.IsNullOrEmpty(ClientId))
                    {
                        ClientId = AzureClaimCheckPipelineComponentHelper.GetContextProperty(messageContext, "ClientId", "https://AzureClaimCheck.AzureClaimCheckSBProperties");
                    }
                    if (string.IsNullOrEmpty(MessageTypeId))
                    {
                        MessageTypeId = AzureClaimCheckPipelineComponentHelper.GetContextProperty(messageContext, "MessageTypeId", "https://AzureClaimCheck.AzureClaimCheckSBProperties");
                    }

                    // get ClientId & MessageTypeId from relativeURI in not found in SB Properties or in pipeline configuration
                    // relativeURI should be /ClientId/MessageTypeId/filename
                    string tempRelativeURI = relativeURI;
                    if (string.IsNullOrEmpty(MessageTypeId))
                    {
                        try
                        {
                            tempRelativeURI = tempRelativeURI.Substring(0, tempRelativeURI.LastIndexOf('/'));
                            MessageTypeId   = tempRelativeURI.Substring(tempRelativeURI.LastIndexOf('/') + 1);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    if (string.IsNullOrEmpty(ClientId))
                    {
                        try
                        {
                            tempRelativeURI = tempRelativeURI.Substring(0, tempRelativeURI.LastIndexOf('/'));
                            ClientId        = tempRelativeURI.Substring(tempRelativeURI.LastIndexOf('/') + 1);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    bool bHaveStorageKey = false;
                    if (!string.IsNullOrEmpty(StorageAccountKey))
                    {
                        bHaveStorageKey = true;
                    }

                    // check key vault properties
                    if (!bHaveStorageKey)
                    {
                        if (!string.IsNullOrEmpty(KeyVaultURL))
                        {
                            if (!string.IsNullOrEmpty(KeyVaultClientId))
                            {
                                if (!string.IsNullOrEmpty(KeyVaultClientSecret))
                                {
                                    string keyVaultSecret = string.IsNullOrEmpty(ClientId) ? "" : ClientId;
                                    keyVaultSecret += string.IsNullOrEmpty(MessageTypeId) ? "" : MessageTypeId;
                                    keyVaultSecret += string.IsNullOrEmpty(_KeyVaultSecretSufix) ? "" : _KeyVaultSecretSufix;

                                    string StorageAccountKeyTemp = AzureClaimCheckPipelineComponentHelper.GetKeyVaultSecret(KeyVaultURL, KeyVaultClientId, KeyVaultClientSecret, keyVaultSecret).GetAwaiter().GetResult();
                                    StorageAccountKey = StorageAccountKeyTemp;
                                }
                            }
                        }
                    }

                    // find the container, reletive filename & filename
                    string container          = "";
                    string inFileNameRelative = "";
                    string inFileName         = "";

                    tempRelativeURI = relativeURI;
                    if (tempRelativeURI.StartsWith("/"))
                    {
                        tempRelativeURI = tempRelativeURI.Substring(1);
                    }
                    container          = tempRelativeURI.Substring(0, tempRelativeURI.IndexOf("/"));
                    inFileNameRelative = tempRelativeURI.Substring(tempRelativeURI.IndexOf("/") + 1);
                    inFileName         = inFileNameRelative.Substring(inFileNameRelative.LastIndexOf("/") + 1);

                    // check for storage key
                    if (!bHaveStorageKey)
                    {
                        if (string.IsNullOrEmpty(StorageAccountName))
                        {
                            throw new ApplicationException(string.Format("StorageAccountName not found"));
                        }
                        if (string.IsNullOrEmpty(StorageAccountKey))
                        {
                            throw new ApplicationException(string.Format("StorageAccountKey not found"));
                        }
                    }

                    // connect to storage account
                    StorageCredentials  creds         = new StorageCredentials(_storageAccount, StorageAccountKey);
                    CloudStorageAccount storAccount   = new CloudStorageAccount(creds, true);
                    CloudBlobClient     blobClient    = storAccount.CreateCloudBlobClient();
                    CloudBlobContainer  blobContainer = blobClient.GetContainerReference(container);
                    CloudBlob           blob          = blobContainer.GetBlobReference(inFileNameRelative);

                    MemoryStream strm = new MemoryStream();

                    blob.DownloadToStream(strm);
                    strm.Seek(0, SeekOrigin.Begin);

                    // set context properties
                    messageContext.Write("EventGridSubscriptionResponse", "https://AzureClaimCheck.AzureClaimCheckProperties", "False");
                    messageContext.Write("OriginalStoragePath", "https://AzureClaimCheck.AzureClaimCheckProperties", string.IsNullOrEmpty(fullURI) ? relativeURI : fullURI);
                    messageContext.Write("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", inFileName);

                    messageContext.Write("ClientId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", ClientId);
                    messageContext.Write("MessageTypeId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", MessageTypeId);

                    bodyPart.Data = strm;
                    pContext.ResourceTracker.AddResource(strm);
                }
            }
            else
            {
                // do Send

                // prepare outbound file name
                string outFileName = AzureClaimCheckPipelineComponentHelper.ExpandFileName(messageContext, pInMsg.MessageID.ToString(), StorageOutboundFileName);

                bool bHaveStorageKey = false;
                if (!string.IsNullOrEmpty(StorageAccountKey))
                {
                    bHaveStorageKey = true;
                }

                // check key vault properties
                if (!bHaveStorageKey)
                {
                    if (!string.IsNullOrEmpty(KeyVaultURL))
                    {
                        if (!string.IsNullOrEmpty(KeyVaultClientId))
                        {
                            if (!string.IsNullOrEmpty(KeyVaultClientSecret))
                            {
                                string keyVaultSecret = string.IsNullOrEmpty(ClientId) ? "" : ClientId;
                                keyVaultSecret += string.IsNullOrEmpty(MessageTypeId) ? "" : MessageTypeId;
                                keyVaultSecret += string.IsNullOrEmpty(_KeyVaultSecretSufix) ? "" : _KeyVaultSecretSufix;

                                string StorageAccountKeyTemp = AzureClaimCheckPipelineComponentHelper.GetKeyVaultSecret(KeyVaultURL, KeyVaultClientId, KeyVaultClientSecret, keyVaultSecret).GetAwaiter().GetResult();
                                StorageAccountKey = StorageAccountKeyTemp;
                            }
                        }
                    }
                }

                // check for storage key
                if (!bHaveStorageKey)
                {
                    if (string.IsNullOrEmpty(StorageAccountName))
                    {
                        throw new ApplicationException(string.Format("StorageAccountName not found"));
                    }
                    if (string.IsNullOrEmpty(StorageAccountKey))
                    {
                        throw new ApplicationException(string.Format("StorageAccountKey not found"));
                    }
                }

                string outFileNameRelative = string.Format("{0}/{1}/{2}", ClientId, MessageTypeId, outFileName);

                // connect to storage account
                StorageCredentials  creds         = new StorageCredentials(StorageAccountName, StorageAccountKey);
                CloudStorageAccount storAccount   = new CloudStorageAccount(creds, true);
                CloudBlobClient     blobClient    = storAccount.CreateCloudBlobClient();
                CloudBlobContainer  blobContainer = blobClient.GetContainerReference(StorageOutboundContainer);
                blobContainer.CreateIfNotExists();
                CloudBlockBlob blob = blobContainer.GetBlockBlobReference(outFileNameRelative);

                blob.UploadFromStream(bodyPart.GetOriginalDataStream());

                string fullFileName = blob.Uri.AbsolutePath;

                // create service bus message body
                MemoryStream strm = new MemoryStream(Encoding.UTF8.GetBytes(fullFileName));
                strm.Seek(0, SeekOrigin.Begin);
                bodyPart.Data = strm;
                pContext.ResourceTracker.AddResource(strm);

                // set context properties for SB message
                if (!string.IsNullOrEmpty(ClientId))
                {
                    messageContext.Write("ClientId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", ClientId);
                }
                if (!string.IsNullOrEmpty(MessageTypeId))
                {
                    messageContext.Write("MessageTypeId", "https://AzureClaimCheck.AzureClaimCheckSBProperties", MessageTypeId);
                }
            }

            return(pInMsg);
        }