예제 #1
0
        /// <summary>
        /// Executes a pipeline component to process the input message and returns the result message.
        /// </summary>
        /// <param name="pContext">A reference to <see cref="Microsoft.BizTalk.Component.Interop.IPipelineContext"/> object that contains the current pipeline context.</param>
        /// <param name="pInMsg">A reference to <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object that contains the message to process.</param>
        /// <returns>A reference to the returned <see cref="Microsoft.BizTalk.Message.Interop.IBaseMessage"/> object which will contain the output message.</returns>
        public override IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            if (pContext != null && pInMsg != null)
            {
                PolicyExecutionInfo policyExecInfo = !String.IsNullOrEmpty(PolicyVersion) ? new PolicyExecutionInfo(PolicyName, System.Version.Parse(PolicyVersion)) : new PolicyExecutionInfo(PolicyName);

                string ctxPropName, ctxPropNamespace;

                for (int i = 0; i < pInMsg.Context.CountProperties; i++)
                {
                    ctxPropName      = null;
                    ctxPropNamespace = null;

                    object ctxPropValue = pInMsg.Context.ReadAt(i, out ctxPropName, out ctxPropNamespace);
                    policyExecInfo.AddParameter(String.Format("{0}{1}{2}", ctxPropNamespace, BizTalkUtility.ContextPropertyNameSeparator, ctxPropName), ctxPropValue);
#if DEBUG
                    TraceManager.PipelineComponent.TraceDetails("DETAIL: Context property added: {0}{1}{2} = {3}", ctxPropNamespace, BizTalkUtility.ContextPropertyNameSeparator, ctxPropName, ctxPropValue);
#endif
                }

                using (RuntimeTaskExecutionContext taskExecContext = new RuntimeTaskExecutionContext(pContext, pInMsg))
                {
                    IList <IMessagingRuntimeExtenderTask> registeredTasks = RuntimeTaskFactory.GetRegisteredTasks(taskExecContext);

                    try
                    {
                        PolicyExecutionResult policyExecResult = PolicyHelper.Execute(policyExecInfo, registeredTasks);

                        if (policyExecResult.Success)
                        {
                            foreach (IMessagingRuntimeExtenderTask task in taskExecContext.Extensions.FindAll <IMessagingRuntimeExtenderTask>())
                            {
                                if (task.CanRun)
                                {
                                    task.Run(taskExecContext);
                                }
                            }

                            return(taskExecContext.Message);
                        }
                    }
                    finally
                    {
                        policyExecInfo.ClearParameters();

                        registeredTasks.Clear();
                        registeredTasks = null;
                    }
                }
            }
            return(pInMsg);
        }
예제 #2
0
        /// <summary>
        /// Retrieves the specified <see cref="System.Configuration.ConfigurationSection"/> for a given application running of the specified machine.
        /// </summary>
        /// <param name="sectionName">The name of the section to be retrieved.</param>
        /// <param name="applicationName">The name of the application for which a configuration section is being requested.</param>
        /// <param name="machineName">The name of the machine on which the requesting application is running.</param>
        /// <returns>The specified <see cref="System.Configuration.ConfigurationSection"/>, or a null reference if a section by that name is not found.</returns>
        public ConfigurationSection GetSection(string sectionName, string applicationName, string machineName)
        {
            var callToken = TraceManager.RulesComponent.TraceIn(sectionName, this.configPolicy, this.configVersion);

            try
            {
                PolicyExecutionInfo policyExecInfo = new PolicyExecutionInfo(PolicyName, PolicyVersion);

                policyExecInfo.AddParameter(WellKnownContractMember.MessageParameters.SectionName, sectionName);
                policyExecInfo.AddParameter(WellKnownContractMember.MessageParameters.ApplicationName, applicationName);
                policyExecInfo.AddParameter(WellKnownContractMember.MessageParameters.MachineName, machineName);

                ConfigurationSection configSection = ConfigurationSectionFactory.GetSection(sectionName);

                if (configSection != null)
                {
                    PolicyExecutionResult execResult = PolicyHelper.Execute(policyExecInfo, RulesEngineFactFactory.GetFacts(configSection));

                    if (execResult.Success)
                    {
                        // If policy invocation was successful, we need to update the policy version number of reflect the true version of the policy.
                        this.actualConfigVersion = new Version(execResult.PolicyVersion.Major, execResult.PolicyVersion.Minor);

                        if (SourceChanged != null)
                        {
                            SourceChanged(this, new ConfigurationSourceChangedEventArgs(this, new string[] { sectionName }));
                        }

                        return(configSection);
                    }
                    else
                    {
                        throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ConfigPolicyExecutionFailed, execResult.PolicyName), execResult.Errors.Count > 0 ? execResult.Errors[0] : null);
                    }
                }
                else
                {
                    throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, ExceptionMessages.ConfigurationSectionNotSupported, sectionName, Resources.RulesEngineConfigurationSourceElementDisplayName));
                }
            }
            finally
            {
                TraceManager.RulesComponent.TraceOut(callToken);
            }
        }
예제 #3
0
        public void ValidateHandleGetConfigurationSectionRequestPolicy()
        {
            PolicyExecutionInfo policyExecInfo = new PolicyExecutionInfo("Contoso.Cloud.Integration.GenericCloudRequestHandling");

            policyExecInfo.AddParameter("http://schemas.microsoft.com/BizTalk/2003/soap-properties#MethodName", "Contoso.Cloud.Integration.ServiceContracts/IOnPremiseConfigurationService/GetConfigurationSection");

            IList <IMessagingRuntimeExtenderTask> registeredTasks = RuntimeTaskFactory.GetRegisteredTasks();
            PolicyExecutionResult policyExecResult = PolicyHelper.Execute(policyExecInfo, registeredTasks);

            IEnumerable <ExternalComponentInvokeTask> execTasks = registeredTasks.OfType <ExternalComponentInvokeTask>();

            Assert.IsTrue(policyExecResult.Success, "Policy execution was not successful");
            Assert.IsFalse(execTasks.Count() == 0, "No ExternalComponentInvokeTask was found in task collection");

            ExternalComponentInvokeTask execTask = execTasks.ElementAt <ExternalComponentInvokeTask>(0);

            Assert.IsNotNull(execTask, "execTask instance has not been found");
            Assert.IsFalse(String.IsNullOrEmpty(execTask.AssemblyName), "AssemblyName is null or empty");
            Assert.IsFalse(String.IsNullOrEmpty(execTask.TypeName), "TypeName is null or empty");
        }
예제 #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)
        {
            Guard.ArgumentNotNull(context, "context");
            Guard.ArgumentNotNull(context.Message, "context.Message");

            var callToken = TraceManager.PipelineComponent.TraceIn();

            Stream messageDataStream = null;
            IEnumerable <object> facts = null;
            string             policyName = PolicyName, ctxPropName = null, ctxPropNamespace = null;
            Version            policyVersion = PolicyVersion;
            RulesEngineRequest request       = null;
            bool responseRequired            = true;

            try
            {
                XmlReaderSettings readerSettings = new XmlReaderSettings()
                {
                    CloseInput = false, CheckCharacters = false, IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true, ValidationType = ValidationType.None
                };

                if (context.Message.BodyPart != null)
                {
                    messageDataStream = BizTalkUtility.EnsureSeekableStream(context.Message, context.PipelineContext);

                    if (messageDataStream != null)
                    {
                        using (XmlReader messageDataReader = XmlReader.Create(messageDataStream, readerSettings))
                        {
                            // Navigate through the XML reader until we find an element with the expected name and namespace.
                            while (!messageDataReader.EOF && messageDataReader.Name != WellKnownContractMember.MessageParameters.Request && messageDataReader.NamespaceURI != WellKnownNamespace.DataContracts.General)
                            {
                                messageDataReader.Read();
                            }

                            // Element was found, let's perform de-serialization from XML into a RulesEngineRequest object.
                            if (!messageDataReader.EOF)
                            {
                                DataContractSerializer serializer = new DataContractSerializer(typeof(RulesEngineRequest));
                                request = serializer.ReadObject(messageDataReader, false) as RulesEngineRequest;

                                if (request != null)
                                {
                                    policyName    = request.PolicyName;
                                    policyVersion = request.PolicyVersion;
                                    facts         = request.Facts;
                                }
                            }
                        }
                    }
                }

                // Check if the policy name was supplied when this component was instantiated or retrieved from a request message.
                if (!String.IsNullOrEmpty(policyName))
                {
                    // If policy version is not specified, use the latest deployed version.
                    PolicyExecutionInfo policyExecInfo = policyVersion != null ? new PolicyExecutionInfo(policyName, policyVersion) : new PolicyExecutionInfo(policyName);

                    // Use all context properties as parameters when invoking a policy.
                    for (int i = 0; i < context.Message.Context.CountProperties; i++)
                    {
                        ctxPropName      = null;
                        ctxPropNamespace = null;

                        object ctxPropValue = context.Message.Context.ReadAt(i, out ctxPropName, out ctxPropNamespace);
                        policyExecInfo.AddParameter(String.Format("{0}#{1}", ctxPropNamespace, ctxPropName), ctxPropValue);
                    }

                    // If we still haven't determined what facts should be passed to the policy, let's use the request message as a single fact.
                    if (null == facts)
                    {
                        if (messageDataStream != null)
                        {
                            // Unwind the data stream back to the beginning.
                            messageDataStream.Seek(0, SeekOrigin.Begin);

                            // Read the entire message into a BRE-compliant type XML document.
                            using (XmlReader messageDataReader = XmlReader.Create(messageDataStream, readerSettings))
                            {
                                facts            = new object[] { new TypedXmlDocument(Resources.DefaultTypedXmlDocumentTypeName, messageDataReader) };
                                responseRequired = false;
                            }
                        }
                    }

                    // Execute a BRE policy.
                    PolicyExecutionResult policyExecResult = PolicyHelper.Execute(policyExecInfo, facts);

                    // CHeck if we need to return a response. We don't need to reply back if we are not handling ExecutePolicy request message.
                    if (responseRequired)
                    {
                        // Construct a response message.
                        RulesEngineResponse response = new RulesEngineResponse(policyExecResult.PolicyName, policyExecResult.PolicyVersion, policyExecResult.Success);

                        // Add all facts that were being used when invoking the policy.
                        response.AddFacts(facts);

                        // Create a response message.
                        IBaseMessagePart  responsePart = BizTalkUtility.CreateResponsePart(context.PipelineContext.GetMessageFactory(), context.Message);
                        XmlWriterSettings settings     = new XmlWriterSettings();

                        // Initialize a new stream that will hold the response message payload.
                        MemoryStream dataStream = new MemoryStream();
                        context.PipelineContext.ResourceTracker.AddResource(dataStream);

                        settings.CloseOutput       = false;
                        settings.CheckCharacters   = false;
                        settings.ConformanceLevel  = ConformanceLevel.Fragment;
                        settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;

                        using (XmlWriter responseWriter = XmlWriter.Create(dataStream, settings))
                        {
                            responseWriter.WriteResponseStartElement("r", WellKnownContractMember.MethodNames.ExecutePolicy, WellKnownNamespace.ServiceContracts.General);

                            DataContractSerializer dcSerializer = new DataContractSerializer(typeof(RulesEngineResponse), String.Concat(WellKnownContractMember.MethodNames.ExecutePolicy, WellKnownContractMember.ResultMethodSuffix), WellKnownNamespace.ServiceContracts.General);
                            dcSerializer.WriteObject(responseWriter, response);

                            responseWriter.WriteEndElement();
                            responseWriter.Flush();
                        }

                        dataStream.Seek(0, SeekOrigin.Begin);
                        responsePart.Data = dataStream;
                    }
                    else
                    {
                        if (facts != null)
                        {
                            TypedXmlDocument xmlDoc = facts.Where((item) => { return(item.GetType() == typeof(TypedXmlDocument)); }).FirstOrDefault() as TypedXmlDocument;

                            if (xmlDoc != null)
                            {
                                // Initialize a new stream that will hold the response message payload.
                                MemoryStream dataStream = new MemoryStream();
                                context.PipelineContext.ResourceTracker.AddResource(dataStream);

                                XmlWriterSettings settings = new XmlWriterSettings
                                {
                                    CloseOutput       = false,
                                    CheckCharacters   = false,
                                    ConformanceLevel  = ConformanceLevel.Fragment,
                                    NamespaceHandling = NamespaceHandling.OmitDuplicates
                                };

                                using (XmlWriter dataWriter = XmlWriter.Create(dataStream, settings))
                                {
                                    xmlDoc.Document.WriteContentTo(dataWriter);
                                    dataWriter.Flush();
                                }

                                dataStream.Seek(0, SeekOrigin.Begin);
                                context.Message.BodyPart.Data = dataStream;
                            }
                        }
                    }
                }
                else
                {
                    throw new ApplicationException(String.Format(CultureInfo.InvariantCulture, ExceptionMessages.PolicyNameNotSpecified));
                }
            }
            finally
            {
                if (messageDataStream != null && messageDataStream.CanSeek && messageDataStream.Position > 0)
                {
                    messageDataStream.Seek(0, SeekOrigin.Begin);
                }

                TraceManager.PipelineComponent.TraceOut(callToken);
            }
        }