static void SaveToFile(string filename, RuleSet rs)
        {
            // save it to a file
            RuleStore ruleStore = new FileRuleStore(filename);

            ruleStore.Save(rs);
        }
Beispiel #2
0
        public void ExecutePolicy(string filename)
        {
            var ruleStore   = new FileRuleStore(filename);
            var ruleSetInfo = GetRuleSetInfo(filename);
            var ruleSet     = ruleStore.GetRuleSet(ruleSetInfo);

            ExecutePolicy(ruleSet);
        }
Beispiel #3
0
        public RuleSet LoadRuleFromFile(string filename, string rulesetName)
        {
            RuleStore             store    = new FileRuleStore(filename);
            RuleSetInfoCollection ruleSets = store.GetRuleSets(rulesetName, RuleStore.Filter.Latest);

            if (ruleSets.Count != 1)
            {
                throw new ApplicationException(string.Format("EXCEPTION: No Ruleset named {0} exists in rule store {1}", rulesetName, filename));
            }
            return(store.GetRuleSet(ruleSets[0]));
        }
Beispiel #4
0
        private static List <RuleSetInfoCollection> GetDependentRuleSetsOnVocabulary(string brlFileName)
        {
            List <RuleSetInfoCollection> list = new List <RuleSetInfoCollection>();
            FileRuleStore            frs      = new FileRuleStore(brlFileName);
            VocabularyInfoCollection coll     = frs.GetVocabularies(RuleStore.Filter.All);

            foreach (VocabularyInfo item in coll)
            {
                list.Add(frs.GetDependentRuleSets(item));
            }
            return(list);
        }
Beispiel #5
0
        /// <summary>
        /// ITestStep.Execute() implementation
        /// </summary>
        /// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public void Execute(System.Xml.XmlNode testConfig, Context context)
        {
            // Using Policy Tester

            // Retrieve Rule-Set from Policy file
            string RuleStoreName             = context.ReadConfigAsString(testConfig, "RuleStoreName");
            string RuleSetInfoCollectionName = context.ReadConfigAsString(testConfig, "RuleSetInfoCollectionName");
            string DebugTracking             = context.ReadConfigAsString(testConfig, "DebugTracking");
            string SampleXML  = context.ReadConfigAsString(testConfig, "SampleXML");
            string XSD        = context.ReadConfigAsString(testConfig, "XSD");
            string ResultFile = context.ReadConfigAsString(testConfig, "ResultFile");

            RuleStore             ruleStore = new FileRuleStore(RuleStoreName);
            RuleSetInfoCollection rsInfo    = ruleStore.GetRuleSets(RuleSetInfoCollectionName, RuleStore.Filter.Latest);

            if (rsInfo.Count != 1)
            {
                // oops ... error
                throw new ApplicationException();
            }

            RuleSet ruleset = ruleStore.GetRuleSet(rsInfo[0]);

            // Create an instance of the DebugTrackingInterceptor
            DebugTrackingInterceptor dti = new DebugTrackingInterceptor(DebugTracking);

            // Create an instance of the Policy Tester class
            PolicyTester policyTester = new PolicyTester(ruleset);

            XmlDocument xd1 = new XmlDocument();

            xd1.Load(SampleXML);

            TypedXmlDocument doc1 = new TypedXmlDocument(XSD, xd1);

            // Execute Policy Tester
            try
            {
                policyTester.Execute(doc1, dti);
            }
            catch (Exception e)
            {
                context.LogException(e);
                throw;
            }

            FileInfo     f = new FileInfo(ResultFile);
            StreamWriter w = f.CreateText();

            w.Write(doc1.Document.OuterXml);
            w.Close();
        }
        private static void ExportPolicies()
        {
            // RuleSetDeploymentDriver has the following important methods
            Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver();

            // SqlRuleStore - gives access t0 the rule engine database
            SqlRuleStore sqlRuleStore = (SqlRuleStore)dd.GetRuleStore();

            // Establish the export file
            FileRuleStore fileRuleStore = new FileRuleStore(policyExportPath);

            CopyPolicies(sqlRuleStore, fileRuleStore, dd);
        }
Beispiel #7
0
        public static void ExportVocabularies()
        {
            // RuleSetDeploymentDriver has the following important methods
            Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver();

            // SqlRuleStore - gives access t0 the rule engine database
            SqlRuleStore sqlRuleStore = (SqlRuleStore)dd.GetRuleStore();

            // Establish the export file
            FileRuleStore fileRuleStore = new FileRuleStore(vocabExportPath);

            CopyVocabularies(sqlRuleStore, fileRuleStore);
        }
        public void ExecutePolicy()
        {
            // Retrieve Rule-Set from the filestore

            RuleStore ruleStore = new FileRuleStore("MedicalInsurancePolicy.xml");

            //Grab the latest version of the rule-set

            RuleSetInfoCollection rsInfo = ruleStore.GetRuleSets("MedicalInsurancePolicy", RuleStore.Filter.Latest);

            if (rsInfo.Count != 1)
            {
                // oops ... error
                throw new ApplicationException();
            }

            RuleSet ruleset = ruleStore.GetRuleSet(rsInfo[0]);

            // Create an instance of the DebugTrackingInterceptor to provide an output trace
            DebugTrackingInterceptor dti = new DebugTrackingInterceptor("outputtrace.txt");

            //Create an instance of the Policy Tester class
            PolicyTester policyTester = new PolicyTester(ruleset);

            //Create the set of short term facts

            //XML facts

            XmlDocument xd1 = new XmlDocument();

            xd1.Load(@"..\..\sampleClaim.xml");

            TypedXmlDocument doc1 = new TypedXmlDocument("MedicalClaims", xd1);

            // .NET facts
            Microsoft.Samples.BizTalk.MedicalClaimsProcessingandTestingPolicies.Claims.ClaimResults results = new Microsoft.Samples.BizTalk.MedicalClaimsProcessingandTestingPolicies.Claims.ClaimResults();

            object[] shortTermFacts = new object[] { doc1, results, new TimeStamp(DateTime.Now) };

            //Execute Policy Tester
            try
            {
                policyTester.Execute(shortTermFacts, dti);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }
            System.Console.WriteLine("Status: " + results.Status);
            System.Console.WriteLine("Reason: " + results.Reason);
        }
        /// <summary>
        /// Exports all rules to a temporary location
        /// </summary>
        /// <param name="filePath"></param>
        public void ExportAll(string filePath)
        {
            var ruleStore       = _driver.GetRuleStore();
            var exportRuleStore = new FileRuleStore(filePath);

            foreach (VocabularyInfo vocabularyInfo in ruleStore.GetVocabularies(RuleStore.Filter.All))
            {
                exportRuleStore.Add(ruleStore.GetVocabulary(vocabularyInfo));
            }
            foreach (RuleSetInfo ruleSetInfo in ruleStore.GetRuleSets(RuleStore.Filter.All))
            {
                exportRuleStore.Add(ruleStore.GetRuleSet(ruleSetInfo));
            }
        }
        static RuleSet LoadFromFile(string filename, string rulesetName)
        {
            // load the ruleset from a file
            RuleStore             ruleStore = new FileRuleStore(filename);
            RuleSetInfoCollection rsInfo    = ruleStore.GetRuleSets(rulesetName, RuleStore.Filter.Latest);

            if (rsInfo.Count != 1)
            {
                // oops ... error
                throw new ApplicationException();
            }
            RuleSet newRS = ruleStore.GetRuleSet(rsInfo[0]);

            return(newRS);
        }
        public static Vocabulary[] LoadVocabFromFile(string filename, string vocabName)
        {
            RuleStore store = new FileRuleStore(filename);
            VocabularyInfoCollection vocabularies = store.GetVocabularies(vocabName, RuleStore.Filter.All);

            if (vocabularies.Count < 1)
            {
                throw new ApplicationException(string.Format("EXCEPTION: No Vocabulary named {0} exists in rule store {1}", vocabName, filename));
            }
            Vocabulary[] vocabularyArray = new Vocabulary[vocabularies.Count];
            for (int i = 0; i < vocabularies.Count; i++)
            {
                vocabularyArray[i] = store.GetVocabulary(vocabularies[i]);
            }
            return(vocabularyArray);
        }
        }         // End of Cleanup()

        public void Execute()
        {
            //Using Policy Tester

            // Retrieve Rule-Set from Policy file
            RuleStore             ruleStore = new FileRuleStore("LoanProcessing.xml");
            RuleSetInfoCollection rsInfo    = ruleStore.GetRuleSets("LoanProcessing", RuleStore.Filter.Latest);

            if (rsInfo.Count != 1)
            {
                // oops ... error
                throw new ApplicationException();
            }

            RuleSet ruleset = ruleStore.GetRuleSet(rsInfo[0]);

            // Create an instance of the DebugTrackingInterceptor
            DebugTrackingInterceptor dti = new DebugTrackingInterceptor("outputtraceforLoanPocessing.txt");

            //Create an instance of the Policy Tester class
            PolicyTester policyTester = new PolicyTester(ruleset);

            XmlDocument xd1 = new XmlDocument();

            xd1.Load("sampleLoan.xml");

            TypedXmlDocument doc1 = new TypedXmlDocument("Microsoft.Samples.BizTalk.LoansProcessor.Case", xd1);

            //Execute Policy Tester
            try
            {
                policyTester.Execute(doc1, dti);
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }

            FileInfo     f = new FileInfo("LoanPocessingResults.xml");
            StreamWriter w = f.CreateText();

            w.Write(doc1.Document.OuterXml);
            w.Close();
        }
Beispiel #13
0
        /// <summary>
        ///     TestStepBase.Execute() implementation
        /// </summary>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public override void Execute(Context context)
        {
            var fi = new FileInfo(RuleStoreName);

            if (!fi.Exists)
            {
                throw new FileNotFoundException("RuleStoreName", RuleStoreName);
            }

            var ruleStore = new FileRuleStore(fi.FullName);
            var rsInfo    = ruleStore.GetRuleSets(RuleSetInfoCollectionName, RuleStore.Filter.Latest);

            if (rsInfo.Count != 1)
            {
                // oops ... error
                throw new InvalidOperationException(string.Format("RuleStore {0} did not contain RuleSet {1}",
                                                                  RuleStoreName, RuleSetInfoCollectionName));
            }

            var ruleset = ruleStore.GetRuleSet(rsInfo[0]);


            // load the facts into array
            var facts = new List <object>(FactsList.Count);

            // Create an instance of the Policy Tester class
            using (var policyTester = new PolicyTester(ruleset))
            {
                foreach (var currentFact in FactsList)
                {
                    switch (currentFact.GetType().ToString())
                    {
                    case "ObjectFact":
                    {
                        var fact = currentFact as ObjectFact;

                        object[] objectArgs = null;
                        if (null != fact.Args)
                        {
                            objectArgs = fact.Args.Split(',').Cast <object>().ToArray();
                        }

                        Type type;
                        if (fact.AssemblyPath.Length > 0)
                        {
                            var asm = Assembly.Load(fact.AssemblyPath);
                            if (asm == null)
                            {
                                // fail
                                throw (new InvalidOperationException("failed to create type " + fact.Type));
                            }
                            type = asm.GetType(fact.Type, true, false);
                        }
                        else
                        {
                            // must be in path
                            type = Type.GetType(fact.Type);
                        }

                        facts.Add(Activator.CreateInstance(type, objectArgs));
                        break;
                    }

                    case "DocumentFact":
                    {
                        var fact = currentFact as DocumentFact;
                        var xd1  = new XmlDocument();
                        xd1.Load(fact.InstanceDocument);
                        var txd = new TypedXmlDocument(fact.SchemaType, xd1);
                        facts.Add(txd);
                        break;
                    }

                    case "DataConnectionFact":
                    {
                        var fact = currentFact as DataConnectionFact;
                        var conn = new SqlConnection(fact.ConnectionString);
                        conn.Open();
                        var dc = new DataConnection(fact.Dataset, fact.TableName, conn);
                        facts.Add(dc);
                        break;
                    }

                    case "dataTable":
                    case "dataRow":
                    {
                        var fact = currentFact as DataTableFact;

                        var conn = new SqlConnection(fact.ConnectionString);
                        conn.Open();
                        var myCommand = new SqlCommand(fact.Command, conn)
                        {
                            CommandType = CommandType.Text
                        };
                        var dAdapt = new SqlDataAdapter();
                        dAdapt.TableMappings.Add("Table", fact.TableName);
                        dAdapt.SelectCommand = myCommand;
                        var ds = new DataSet(fact.Dataset);
                        dAdapt.Fill(ds);
                        var tdt = new TypedDataTable(ds.Tables[fact.TableName]);
                        if (fact.Type == "dataRow")
                        {
                            var tdr = new TypedDataRow(ds.Tables[fact.TableName].Rows[0], tdt);
                            facts.Add(tdr);
                        }
                        else
                        {
                            facts.Add(tdt);
                        }
                        break;
                    }
                    }
                }

                // Create an instance of the DebugTrackingInterceptor
                using (var dti = new DebugTrackingInterceptor(DebugTracking))
                {
                    // Execute Policy Tester
                    try
                    {
                        policyTester.Execute(facts.ToArray(), dti);
                    }
                    catch (Exception e)
                    {
                        context.LogException(e);
                        throw;
                    }
                }
            }

            // write out all document instances passed in
            foreach (var fact in facts)
            {
                switch (fact.GetType().Name)
                {
                case "TypedXmlDocument":
                {
                    var txd = (TypedXmlDocument)fact;

                    context.LogData("TypedXmlDocument result: ", txd.Document.OuterXml);
                    using (var data = StreamHelper.LoadMemoryStream(txd.Document.OuterXml))
                    {
                        if (txd.DocumentType == "UBS.CLAS.PoC.Schemas.INSERTS")
                        {
                            SubSteps.Aggregate(data, (current, subStep) => subStep.Execute(current, context));
                        }
                    }

                    break;
                }

                case "DataConnection":
                {
                    var dc = (DataConnection)fact;
                    dc.Update();     // persist any changes
                    break;
                }

                case "TypedDataTable":
                {
                    var tdt = (TypedDataTable)fact;
                    tdt.DataTable.AcceptChanges();
                    break;
                }

                case "TypedDataRow":
                {
                    var tdr = (TypedDataRow)fact;
                    tdr.DataRow.AcceptChanges();
                    break;
                }
                }
            }
        }
        /// <summary>
        /// TestStepBase.Execute() implementation
        /// </summary>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public override void Execute(Context context)
        {
            var fi = new System.IO.FileInfo(RuleStoreName);

            if (!fi.Exists)
            {
                throw new FileNotFoundException("RuleStoreName", RuleStoreName);
            }

            var ruleStore = new FileRuleStore(fi.FullName);
            var rsInfo    = ruleStore.GetRuleSets(RuleSetInfoCollectionName, RuleStore.Filter.Latest);

            if (rsInfo.Count != 1)
            {
                // oops ... error
                throw new ApplicationException(String.Format("RuleStore {0} did not contain RuleSet {1}", RuleStoreName, RuleSetInfoCollectionName));
            }

            var ruleset = ruleStore.GetRuleSet(rsInfo[0]);

            // Create an instance of the DebugTrackingInterceptor
            var dti = new DebugTrackingInterceptor(DebugTracking);

            // Create an instance of the Policy Tester class
            var policyTester = new PolicyTester(ruleset);

            // load the facts into array
            var facts = new object[_factsList.Count];
            var i     = 0;

            foreach (var currentFact in _factsList)
            {
                switch (currentFact.GetType().ToString())
                {
                case "ObjectFact":
                {
                    var fact = currentFact as ObjectFact;

                    object[] objectArgs = null;
                    if (null != fact.Args)
                    {
                        objectArgs = fact.Args.Split(new char[] { ',' });
                    }

                    System.Reflection.Assembly asm;
                    Type type;
                    if (fact.AssemblyPath.Length > 0)
                    {
                        asm = System.Reflection.Assembly.LoadWithPartialName(fact.AssemblyPath);
                        if (asm == null)
                        {
                            // fail
                            throw (new Exception("failed to create type " + fact.Type));
                        }
                        type = asm.GetType(fact.Type, true, false);
                    }
                    else
                    {
                        // must be in path
                        type = Type.GetType(fact.Type);
                    }

                    facts[i] = Activator.CreateInstance(type, objectArgs);
                    break;
                }

                case "DocumentFact":
                {
                    var fact = currentFact as DocumentFact;
                    var xd1  = new XmlDocument();
                    xd1.Load(fact.InstanceDocument);
                    var txd = new TypedXmlDocument(fact.SchemaType, xd1);
                    facts[i] = txd;
                    break;
                }

                case "DataConnectionFact":
                {
                    var fact = currentFact as DataConnectionFact;
                    var conn = new SqlConnection(fact.ConnectionString);
                    conn.Open();
                    var dc = new DataConnection(fact.Dataset, fact.TableName, conn);
                    facts[i] = dc;
                    break;
                }

                case "dataTable":
                case "dataRow":
                {
                    var fact = currentFact as DataTableFact;

                    var dAdapt = new SqlDataAdapter();
                    dAdapt.TableMappings.Add("Table", fact.TableName);
                    var conn = new SqlConnection(fact.ConnectionString);
                    conn.Open();
                    var myCommand = new SqlCommand(fact.Command, conn)
                    {
                        CommandType = CommandType.Text
                    };
                    dAdapt.SelectCommand = myCommand;
                    var ds = new DataSet(fact.Dataset);
                    dAdapt.Fill(ds);
                    var tdt = new TypedDataTable(ds.Tables[fact.TableName]);
                    if (fact.Type == "dataRow")
                    {
                        var tdr = new TypedDataRow(ds.Tables[fact.TableName].Rows[0], tdt);
                        facts[i] = tdr;
                    }
                    else
                    {
                        facts[i] = tdt;
                    }
                    break;
                }
                }
                i++;
            }

            // Execute Policy Tester
            try
            {
                policyTester.Execute(facts, dti);
            }
            catch (Exception e)
            {
                context.LogException(e);
                throw;
            }
            finally
            {
                dti.CloseTraceFile();
            }

            // write out all document instances passed in
            foreach (object fact in facts)
            {
                switch (fact.GetType().Name)
                {
                case "TypedXmlDocument":
                {
                    var txd = (TypedXmlDocument)fact;

                    context.LogData("TypedXmlDocument result: ", txd.Document.OuterXml);
                    Stream data = StreamHelper.LoadMemoryStream(txd.Document.OuterXml);

                    // Validate if configured...
                    // HACK: We need to prevent ExecuteValidator for /each/ TypedXmlDocument
                    if (txd.DocumentType == "UBS.CLAS.PoC.Schemas.INSERTS")
                    {
                        foreach (var subStep in SubSteps)
                        {
                            data = subStep.Execute(data, context);
                        }
                    }

                    break;
                }

                case "DataConnection":
                {
                    var dc = (DataConnection)fact;
                    dc.Update();         // persist any changes
                    break;
                }

                case "TypedDataTable":
                {
                    var tdt = (TypedDataTable)fact;
                    tdt.DataTable.AcceptChanges();
                    break;
                }

                case "TypedDataRow":
                {
                    var tdr = (TypedDataRow)fact;
                    tdr.DataRow.AcceptChanges();
                    break;
                }
                }
            }
        }
        public void CreatePolicy()
        {
            //Creating XML document bindings on the Case XSD schema

            //Document Binding that binds to the schema name and specifies the selector

            XPathPair          xp_root = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']", "Root");
            XMLDocumentBinding xmlCase = new XMLDocumentBinding("Microsoft.Samples.BizTalk.LoansProcessor.Case", xp_root);

            //DocumentField Bindings that bind to the fields int the schema that are used in the defintion of "Income Rule" and the associated negation rule (the ELSE part)

            XPathPair xp_basicSalary = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='Income']/*[local-name()='BasicSalary']", "Income/BasicSalary");
            XMLDocumentFieldBinding xmlCase_basicSalary = new XMLDocumentFieldBinding((Type.GetType("System.Int32")), xp_basicSalary, xmlCase);

            XPathPair xp_otherIncome = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='Income']/*[local-name()='OtherIncome']", "Income/OtherIncome");
            XMLDocumentFieldBinding xmlCase_otherIncome = new XMLDocumentFieldBinding(Type.GetType("System.Int32"), xp_otherIncome, xmlCase);

            Constant c1 = new Constant("Income status is valid");

            XPathPair xp_incomeStatus = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='IncomeStatus']", "IncomeStatus");
            XMLDocumentFieldBinding xmlCase_incomeStatus = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_incomeStatus, xmlCase, c1);

            Constant c1_1 = new Constant("Income status is not valid");
            XMLDocumentFieldBinding xmlCase_incomeStatusNegation = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_incomeStatus, xmlCase, c1_1);

            // Wrapping the XML bindings as User Functions

            UserFunction uf_basicSalary          = new UserFunction(xmlCase_basicSalary);
            UserFunction uf_otherIncome          = new UserFunction(xmlCase_otherIncome);
            UserFunction uf_incomeStatus         = new UserFunction(xmlCase_incomeStatus);
            UserFunction uf_incomeStatusNegation = new UserFunction(xmlCase_incomeStatusNegation);

            // Condition 1: IF Basic Salary and Other Income > 0

            Constant    zero = new Constant(0);
            GreaterThan ge1  = new GreaterThan(uf_basicSalary, zero);
            GreaterThan ge2  = new GreaterThan(uf_otherIncome, zero);

            LogicalExpressionCollection andList4 = new LogicalExpressionCollection();

            andList4.Add(ge1);
            andList4.Add(ge2);
            LogicalAnd la4 = new LogicalAnd(andList4);

            //Action 1 - THEN set Income Status in the incoming Case document to be Valid

            ActionCollection actionList1 = new ActionCollection();

            actionList1.Add(uf_incomeStatus);

            /*  Name: Income Rule
             *
             *      Description:
             *      IF Basic Salary and Other Income > 0
             *      THEN set Income Status in the incoming Case document to be Valid
             *
             */

            Microsoft.RuleEngine.Rule r1 = new Microsoft.RuleEngine.Rule("Income Status Rule", la4, actionList1);

            //Negation of Income Rule

            LogicalNot ln1 = new LogicalNot(la4);

            ActionCollection actionList1_1 = new ActionCollection();

            actionList1_1.Add(uf_incomeStatusNegation);

            Microsoft.RuleEngine.Rule r1_1 = new Microsoft.RuleEngine.Rule("Negation of Income Status Rule", ln1, actionList1_1);

            //Creating DB bindings on the NorthWind DB -> CustInfo table

            // DataRow Binding to bind to the Data Table, and provide the Data Set name (defaulting here to the DB name)

            DataConnectionBinding drb_CustInfo = new DataConnectionBinding("CustInfo", "Northwind");

            // Column bindings to bind to the columns in the Data Table that need to be used in the Commitments Status Rule

            DatabaseColumnBinding col_ID = new DatabaseColumnBinding(Type.GetType("System.String"), "ID", drb_CustInfo);
            DatabaseColumnBinding col_creditCardBalance = new DatabaseColumnBinding(Type.GetType("System.Int32"), "CreditCardBalance", drb_CustInfo);

            // Creating the XML Document Field Bindings required in rule defintion

            XPathPair xp_ID = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='ID']", "ID");
            XMLDocumentFieldBinding xmlCase_ID = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_ID, xmlCase);

            Constant c3 = new Constant("Compute Commitments");

            XPathPair xp_commitmentsStatus = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='CommitmentsStatus']", "CommitmentsStatus");
            XMLDocumentFieldBinding xmlCase_commitmentsStatus = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_commitmentsStatus, xmlCase, c3);

            // Wrapping the DB and XML bindings as User Functions

            UserFunction uf_xmlID             = new UserFunction(xmlCase_ID);
            UserFunction uf_commitmentsStatus = new UserFunction(xmlCase_commitmentsStatus);
            UserFunction uf_dbID    = new UserFunction(col_ID);
            UserFunction uf_balance = new UserFunction(col_creditCardBalance);

            //Condition 2 : IF the ID in the XML document is equal to the ID in the DB record, and the Credit Card Balance for that record is > 500

            Equal       eq2         = new Equal(uf_dbID, uf_xmlID);
            Constant    c2          = new Constant(500);
            GreaterThan greaterThan = new GreaterThan(uf_balance, c2);

            LogicalExpressionCollection andList2 = new LogicalExpressionCollection();

            andList2.Add(eq2);
            andList2.Add(greaterThan);
            LogicalAnd la2 = new LogicalAnd(andList2);

            //Action 2 Set the Commitments Status field to "Compute Commitments"

            ActionCollection actionList2 = new ActionCollection();

            actionList2.Add(uf_commitmentsStatus);

            /* Rule 2 -
             *                              Name: Commitments Rule
             *
             *                               IF the ID in the Document is = to the ID column in the DB
             *
             *                               AND
             *
             *                               IF Credit Card Balance > 500
             *
             *                               Set Commitments Status in the XML document to be equal to "Compute Commitments"
             */

            Microsoft.RuleEngine.Rule r2 = new Microsoft.RuleEngine.Rule("Commitments Status Rule", la2, actionList2);

            //Negation of Commitments Status Rule (the ELSE part)

            LogicalNot ln2 = new LogicalNot(greaterThan);

            LogicalExpressionCollection andList2negation = new LogicalExpressionCollection();

            andList2negation.Add(eq2);
            andList2negation.Add(ln2);
            LogicalAnd la2negation = new LogicalAnd(andList2negation);

            // Creating the XML Document Field Bindings required in rule defintion

            Constant ignore_string = new Constant("Ignore Commitments");
            XMLDocumentFieldBinding xmlCase_commitmentsStatusNegation = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_commitmentsStatus, xmlCase, ignore_string);
            UserFunction            uf_commitmentsStatusNegation      = new UserFunction(xmlCase_commitmentsStatusNegation);

            ActionCollection actionList2_1 = new ActionCollection();

            actionList2_1.Add(uf_commitmentsStatusNegation);

            Microsoft.RuleEngine.Rule r2_1 = new Microsoft.RuleEngine.Rule("Negation of Commitments Rule", la2negation, actionList2_1);

            // Creating the XML Document Field Bindings required in the Employment Status rule

            XPathPair xp_employmentTime = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='EmploymentType']/*[local-name()='TimeInMonths']", "EmploymentType/TimeInMonths");
            XMLDocumentFieldBinding xmlCase_employmentTime = new XMLDocumentFieldBinding(Type.GetType("System.Int32"), xp_employmentTime, xmlCase);

            UserFunction uf_employmentTime = new UserFunction(xmlCase_employmentTime);
            Constant     action3           = new Constant("Employment Status is valid");

            XPathPair xp_employmentStatus = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='EmploymentStatus']", "EmploymentStatus");
            XMLDocumentFieldBinding xmlCase_employmentStatus = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_employmentStatus, xmlCase, action3);

            UserFunction uf_employmentStatus = new UserFunction(xmlCase_employmentStatus);

            // Condition 3: IF Employment Time > 18 months

            Constant         lengthOfEmployment = new Constant(18);
            GreaterThanEqual greaterThanEqual1  = new GreaterThanEqual(uf_employmentTime, lengthOfEmployment);

            //Action 3 - THEN set Employment Status in the incoming Case document to be Valid

            ActionCollection actionList3 = new ActionCollection();

            actionList3.Add(uf_employmentStatus);

            /*  Name: Employment Status Rule
             *
             *      Description:
             *      IF Time of Employment > 18 months
             *      THEN set Employment Status in the incoming Case document to be Valid
             *
             */

            Microsoft.RuleEngine.Rule r3 = new Microsoft.RuleEngine.Rule("Employment Status Rule", greaterThanEqual1, actionList3);

            // Negation of EmploymentStatus Rule (the ELSE part)

            LogicalNot ln3 = new LogicalNot(greaterThanEqual1);

            Constant empStatus_invalid = new Constant("Employment Status is Invalid");
            XMLDocumentFieldBinding xmlCase_employmentStatusInvalid = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_employmentStatus, xmlCase, empStatus_invalid);
            UserFunction            uf_employmentStatusInvalid      = new UserFunction(xmlCase_employmentStatusInvalid);

            ActionCollection actionList3_1 = new ActionCollection();

            actionList3_1.Add(uf_employmentStatusInvalid);

            Microsoft.RuleEngine.Rule r3_1 = new Microsoft.RuleEngine.Rule("Negation of Employment Status Rule", ln3, actionList3_1);

            // Creating the XML Document Field Bindings required in the Residence Status rule

            XPathPair xp_timeinResidence = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='PlaceOfResidence']/*[local-name()='TimeInMonths']", "PlaceOfResidence/TimeInMonths");
            XMLDocumentFieldBinding xmlCase_timeinResidence = new XMLDocumentFieldBinding(Type.GetType("System.Int32"), xp_timeinResidence, xmlCase);

            UserFunction uf_timeinResidence = new UserFunction(xmlCase_timeinResidence);
            Constant     lengthOfResidence  = new Constant(3);

            Constant residencyStatus_valid = new Constant("Residency Status is valid");

            XPathPair xp_residencyStatus = new XPathPair("/*[local-name()='Root' and namespace-uri()='http://LoansProcessor.Case']/*[local-name()='ResidencyStatus']", "ResidencyStatus");
            XMLDocumentFieldBinding xmlCase_residencyStatus = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_residencyStatus, xmlCase, residencyStatus_valid);
            UserFunction            uf_residencyStatus      = new UserFunction(xmlCase_residencyStatus);

            // Condition 4: IF Time of residence >= 3 years

            GreaterThanEqual greaterThanEqual2 = new GreaterThanEqual(uf_timeinResidence, lengthOfResidence);

            //Action 3 - THEN set Resdiency Status in the incoming Case document to be Valid

            ActionCollection actionList4 = new ActionCollection();

            actionList4.Add(uf_residencyStatus);

            /*  Name: Residency Status Rule
             *
             *      Description:
             *      IF Time of Residency > 3 years
             *      THEN set Residency Status in the incoming Case document to be Valid
             *
             */

            Microsoft.RuleEngine.Rule r4 = new Microsoft.RuleEngine.Rule("Residency Status Rule", greaterThanEqual2, actionList4);

            // Negation of Residency Status Rule

            LogicalNot ln4 = new LogicalNot(greaterThanEqual2);

            Constant residencyStatus_Invalid = new Constant("Residency Status is Invalid");
            XMLDocumentFieldBinding xmlCase_residencyStatusInvalid = new XMLDocumentFieldBinding(Type.GetType("System.String"), xp_residencyStatus, xmlCase, residencyStatus_Invalid);
            UserFunction            uf_residencyStatusInvalid      = new UserFunction(xmlCase_residencyStatusInvalid);

            ActionCollection actionList4_1 = new ActionCollection();

            actionList4_1.Add(uf_residencyStatusInvalid);

            Microsoft.RuleEngine.Rule r4_1 = new Microsoft.RuleEngine.Rule("Negation of Residency Status Rule", ln4, actionList4_1);

            // Creation of the rule-set (policy) and saving it into the file rulestore

            // Creating configuration information (date, version, description, creator, policy name, and fact retriever used to retrieve the required datasets at runtime)

            DateTime    time  = new DateTime(System.DateTime.Today.Year, System.DateTime.Today.Month, System.DateTime.Today.Day);
            VersionInfo vinf1 = new VersionInfo("Rules to process Loan applications", time, "BizRules", 1, 0);
            RuleSet     rs1   = new RuleSet("LoanProcessing", vinf1);
            RuleSetExecutionConfiguration rec1 = new RuleSetExecutionConfiguration();

            Type factRetriever = typeof(myFactRetriever.DbFactRetriever);
            RuleEngineComponentConfiguration recc1 = new RuleEngineComponentConfiguration(factRetriever.Assembly.FullName, factRetriever.FullName);

            rec1.FactRetriever         = recc1;
            rs1.ExecutionConfiguration = rec1;

            // Adding rules to the rule-set

            rs1.Rules.Add(r1);
            rs1.Rules.Add(r1_1);
            rs1.Rules.Add(r2);
            rs1.Rules.Add(r2_1);
            rs1.Rules.Add(r3);
            rs1.Rules.Add(r3_1);
            rs1.Rules.Add(r4);
            rs1.Rules.Add(r4_1);

            // Saving the rule-set (policy) to an XML file in the current directory

            FileRuleStore frs1 = new FileRuleStore("LoanProcessing.xml");

            frs1.Add(rs1);

            // Publish and deploy the ruleset to rulestore
            DeployRuleSet(rs1);
        }
        // Method to create the rule-set or policy
        public void CreateRuleSet()
        {
            //Creating XML document bindings on the Medical claims XSD schema

            //Document Binding that binds to the schema name and specifies the selector
            XMLDocumentBinding xmlClaim = new XMLDocumentBinding("MedicalClaims", "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']");

            //DocumentField Bindings that bind to the fields in the schema that need to be used in rule defintion

            XMLDocumentFieldBinding xmlClaim_Name   = new XMLDocumentFieldBinding(Type.GetType("System.String"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Name']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_ID     = new XMLDocumentFieldBinding(Type.GetType("System.String"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='ID']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_Amount = new XMLDocumentFieldBinding(Type.GetType("System.Double"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Amount']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_Nights = new XMLDocumentFieldBinding(Type.GetType("System.Int32"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Nights']", xmlClaim);
            XMLDocumentFieldBinding xmlClaim_Date   = new XMLDocumentFieldBinding(Type.GetType("System.DateTime"), "/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_Project1.MedicalClaims']/*[local-name()='Date']", xmlClaim);

            //Creating DB bindings on the NorthWind DB -> PolicyValidity table

            // DataRow Binding to bind to the Data Table, and provide the Data Set name (defaulting here to the DB name)

            DataConnectionBinding policyvalidityTable = new DataConnectionBinding("PolicyValidity", "Northwind");

            // Column bindings to bind to the columns in the Data Table that need to be used in rule definition

            DatabaseColumnBinding policyvalidityTable_IDColumn           = new DatabaseColumnBinding(Type.GetType("System.String"), "ID", policyvalidityTable);
            DatabaseColumnBinding policyvalidityTable_PolicyStatusColumn = new DatabaseColumnBinding(Type.GetType("System.String"), "PolicyStatus", policyvalidityTable);

            //Creating .NET class (property and member) bindings

            // Class Bindings to bind to the class defintions whose properties and members will be used in rule definition

            ClassBinding dateClass    = new ClassBinding(typeof(TimeStamp));
            ClassBinding resultsClass = new ClassBinding(new Microsoft.Samples.BizTalk.MedicalClaimsProcessingandTestingPolicies.Claims.ClaimResults().GetType());


            // Member Bindings to bind to the properties and members in the TimeStamp class that need to be used in rule definition

            ClassMemberBinding today = new ClassMemberBinding("Value", dateClass);

            // Member bindings for ClaimResults.Status and ClaimResults.Reason properties

            ClassMemberBinding reason = new ClassMemberBinding("Reason", resultsClass);
            ClassMemberBinding status = new ClassMemberBinding("Status", resultsClass);


            // Member bindings for ClaimResults.Status and ClaimResults.Reason properties with different arguments

            // Creation of constant strings that are required as arguments for rule actions

            Constant           c1  = new Constant(" REJECTED!");
            ArgumentCollection al1 = new ArgumentCollection();

            al1.Add(c1);

            Constant           c2  = new Constant("Amount of claim has exceeded Policy limit");
            ArgumentCollection al2 = new ArgumentCollection();

            al2.Add(c2);

            Constant           c3  = new Constant(" Claim Accepted!");
            ArgumentCollection al3 = new ArgumentCollection();

            al3.Add(c3);

            Constant           c4  = new Constant(" Amount of Nights has exceeded Policy limit");
            ArgumentCollection al4 = new ArgumentCollection();

            al4.Add(c4);

            Constant           c5  = new Constant(" Cannot submit claims for future dates!");
            ArgumentCollection al5 = new ArgumentCollection();

            al5.Add(c5);

            Constant           c6  = new Constant("Policy ID is invalid");
            ArgumentCollection al6 = new ArgumentCollection();

            al6.Add(c6);

            ClassMemberBinding status_Rejected      = new ClassMemberBinding("Status", resultsClass, al1);
            ClassMemberBinding reason_invalidAmount = new ClassMemberBinding("Reason", resultsClass, al2);
            ClassMemberBinding status_Accepted      = new ClassMemberBinding("Status", resultsClass, al3);
            ClassMemberBinding reason_invalidNights = new ClassMemberBinding("Reason", resultsClass, al4);
            ClassMemberBinding reason_invalidDate   = new ClassMemberBinding("Reason", resultsClass, al5);
            ClassMemberBinding reason_invalidID     = new ClassMemberBinding("Reason", resultsClass, al6);


            // MemberBinding for the SendLead method in the ClaimResults class with the name and ID from the incoming XML document as arguments

            Term arg1 = new UserFunction(xmlClaim_Name);
            Term arg2 = new UserFunction(xmlClaim_ID);
            ArgumentCollection args1 = new ArgumentCollection();

            args1.Add(arg1);
            args1.Add(arg2);
            ClassMemberBinding sendLead = new ClassMemberBinding("SendLead", resultsClass, args1);

            // Object reference binding to the ClaimResults object that is to be asserted back in to the initial fact base as part of the rule actions

            ObjectReference resultsObject = new ObjectReference(resultsClass);


            // Wrapping the XML bindings as User Functions

            UserFunction uf_xmlName   = new UserFunction(xmlClaim_Name);
            UserFunction uf_xmlID     = new UserFunction(xmlClaim_ID);
            UserFunction uf_xmlAmount = new UserFunction(xmlClaim_Amount);
            UserFunction uf_xmlNights = new UserFunction(xmlClaim_Nights);
            UserFunction uf_xmlDate   = new UserFunction(xmlClaim_Date);

            // Wrapping the DB bindings as User Functions

            UserFunction uf_IDColumn           = new UserFunction(policyvalidityTable_IDColumn);
            UserFunction uf_PolicyStatusColumn = new UserFunction(policyvalidityTable_PolicyStatusColumn);


            // Wrapping the .NET bindings as User Functions

            UserFunction uf_today         = new UserFunction(today);
            UserFunction uf_reason        = new UserFunction(reason);
            UserFunction uf_status        = new UserFunction(status);
            UserFunction uf_rejected      = new UserFunction(status_Rejected);
            UserFunction uf_invalidAmount = new UserFunction(reason_invalidAmount);
            UserFunction uf_accepted      = new UserFunction(status_Accepted);
            UserFunction uf_invalidNights = new UserFunction(reason_invalidNights);
            UserFunction uf_invalidDate   = new UserFunction(reason_invalidDate);
            UserFunction uf_invalidID     = new UserFunction(reason_invalidID);
            UserFunction uf_sendLead      = new UserFunction(sendLead);


            // Rule 1: Amount Check (check to see if claim amount has exceeded the allowable limit)

            // Condition 1: IF the Amount in the XML document element is > 1000 AND IF the Claims.ClaimResults object has not been modified i.e if STATUS = null

            GreaterThan ge1 = new GreaterThan(uf_xmlAmount, new Constant(1000));
            Equal       eq1 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd1 = new LogicalExpressionCollection();

            conditionAnd1.Add(ge1);
            conditionAnd1.Add(eq1);

            LogicalAnd la1 = new LogicalAnd(conditionAnd1);

            //Action 1 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "Amount of claim has exceeded limit" && Assert this object back into working memory

            ActionCollection actionList1 = new ActionCollection();

            actionList1.Add(uf_rejected);
            actionList1.Add(uf_invalidAmount);
            actionList1.Add(new Assert(resultsObject));

            // Amount Check Rule defintion
            Microsoft.RuleEngine.Rule r1 = new Microsoft.RuleEngine.Rule("Amount Check", la1, actionList1);

            // Rule 2: Nights Spent (check to see if no of nights has exceeded the allowable limit)

            // Condition 2: IF the number of nights in the XML document element is > 10 AND IF the Claims.ClaimResults object has not been modified i.e if STATUS = null

            GreaterThan ge2 = new GreaterThan(uf_xmlNights, new Constant(10));

            Equal eq2 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd2 = new LogicalExpressionCollection();

            conditionAnd2.Add(ge2);
            conditionAnd2.Add(eq2);

            LogicalAnd la2 = new LogicalAnd(conditionAnd2);

            //Action 2 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "No of Nights has exceeded limit" && Assert this object back into working memory

            ActionCollection actionList2 = new ActionCollection();

            actionList2.Add(uf_rejected);
            actionList2.Add(uf_invalidNights);
            actionList2.Add(new Assert(resultsObject));

            //Nights Spent Rule Definition
            Microsoft.RuleEngine.Rule r2 = new Microsoft.RuleEngine.Rule("Nights Spent", la2, actionList2);

            // Rule 3: Date Validity (check to see if the date on the claim is greater than today's date)

            // Condition 3: IF date on the incoming XML claim is greater than Today than reject the claim AND IF the Claims.ClaimResults object has not been modified i.e if RESULT = null

            GreaterThan ge3 = new GreaterThan(uf_xmlDate, uf_today);

            Equal eq3 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd3 = new LogicalExpressionCollection();

            conditionAnd3.Add(ge3);
            conditionAnd3.Add(eq3);

            LogicalAnd la3 = new LogicalAnd(conditionAnd3);

            //Action 3 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "Cannot submit claims in the future!" && Assert this object back into working memory

            ActionCollection actionList3 = new ActionCollection();

            actionList3.Add(uf_rejected);
            actionList3.Add(uf_invalidDate);
            actionList3.Add(new Assert(resultsObject));

            // Date Validity Rule defintion

            Microsoft.RuleEngine.Rule r3 = new Microsoft.RuleEngine.Rule("Date Validity Check", la3, actionList3);

            // Rule 4: Policy Validity (check to see if the policy ID is valid by inspecting the database)

            // Condition 4: IF the Policy is Invalid for the ID in the XML claim (where the validity record is stored in the DB) AND IF the Claims.ClaimResults object has not been modified i.e if RESULT = null

            Equal    ceq1           = new Equal(uf_IDColumn, uf_xmlID);
            Constant invalid_string = new Constant("INVALID");
            Equal    ceq2           = new Equal(uf_PolicyStatusColumn, invalid_string);

            LogicalExpressionCollection andList1 = new LogicalExpressionCollection();

            andList1.Add(ceq1);
            andList1.Add(ceq2);
            LogicalAnd cla1 = new LogicalAnd(andList1);

            Equal eq4 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            LogicalExpressionCollection conditionAnd4 = new LogicalExpressionCollection();

            conditionAnd4.Add(cla1);
            conditionAnd4.Add(eq4);

            LogicalAnd la4 = new LogicalAnd(conditionAnd4);


            //Action 4 - THEN Claims.ClaimResults.Status = "REJECTED" and Claims.ClaimResults.Reason = "Policy Invalid" && Assert this object back into working memory

            ActionCollection actionList4 = new ActionCollection();

            actionList4.Add(uf_rejected);
            actionList4.Add(uf_invalidID);
            actionList4.Add(new Assert(resultsObject));

            // Policy Validity Rule defintion

            Microsoft.RuleEngine.Rule r4 = new Microsoft.RuleEngine.Rule("Policy Validity Check", la4, actionList4);

            // Rule 5: (Send a Lead To Policy Department (by executing the SendLead Method) if the user's policy has expired and is invalid)

            // Condition 5: IF Claim.ClaimResults.Reason = "Policy invalid"

            Constant Reason_String = new Constant("Policy ID is invalid");
            Equal    eq5           = new Equal(uf_reason, Reason_String);

            //Action 5 - THEN Send a Lead to the Policy Department by invoking the function Claim.ClaimResults.SendLead wirh customer ID and Name

            ActionCollection actionList5 = new ActionCollection();

            actionList5.Add(uf_sendLead);

            Microsoft.RuleEngine.Rule r5 = new Microsoft.RuleEngine.Rule("Send Lead", eq5, actionList5);

            // Rule 6:  Set the Claim Status to be Valid if it the Status has not been set to Invalid

            // Condition 6: IF Claim.ClaimResults.Status = null

            Equal eq6 = new Equal(uf_status, new Constant(uf_status.Type, null as string));

            //Action 6 - THEN Send a Set the Claim status to be Valid

            ActionCollection actionList6 = new ActionCollection();

            actionList6.Add(uf_accepted);

            //Claim Accepted Rule definition

            Microsoft.RuleEngine.Rule r6 = new Microsoft.RuleEngine.Rule("Claim Accepted", eq6, actionList6);

            // Since initially the condition is TRUE (the claim has not been rejected or accepted),
            // we need to make this rule a lower priority so that the rejection rules run first.
            // That way, if the claim is rejected, this rule will not execute.
            r6.Priority = -1;

            // Creation of the rule-set (policy) and saving it into the file rulestore

            // Creating configuration information (date, version, description, creator, policy name, and fact retriever used to retrieve the required datasets at runtime)

            DateTime    time  = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day);
            VersionInfo vinf1 = new VersionInfo("Rules to Process medical Insurance Claims", time, "BizRules", 0, 0);
            RuleSet     rs1   = new RuleSet("MedicalInsurancePolicy", vinf1);
            RuleSetExecutionConfiguration    rec1  = new RuleSetExecutionConfiguration();
            RuleEngineComponentConfiguration recc1 = new RuleEngineComponentConfiguration("FactRetrieverForClaimsProcessing", "Microsoft.Samples.BizTalk.MedicalClaimsProcessingandTestingPolicies.FactRetrieverForClaimsProcessing.DbFactRetriever");

            rec1.FactRetriever         = recc1;
            rs1.ExecutionConfiguration = rec1;

            // Adding rules to the rule-set

            rs1.Rules.Add(r1);
            rs1.Rules.Add(r2);
            rs1.Rules.Add(r3);
            rs1.Rules.Add(r4);
            rs1.Rules.Add(r5);
            rs1.Rules.Add(r6);

            // Saving the rule-set (policy) to an XML file in the current directory

            FileRuleStore frs1 = new FileRuleStore("MedicalInsurancePolicy.xml");

            frs1.Add(rs1);
        }
Beispiel #17
0
        private static void ImportPolicies()
        {
            // RuleSetDeploymentDriver has the following important methods
            Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver();

            // SqlRuleStore - gives access t0 the rule engine database
            SqlRuleStore sqlRuleStore = (SqlRuleStore)dd.GetRuleStore();

            // Establish the export file
            FileRuleStore fileRuleStore = new FileRuleStore(policyExportPath);

            CopyPolicies(fileRuleStore, sqlRuleStore, dd);
        }
        /// <summary>
        /// TestStepBase.Execute() implementation
        /// </summary>
        /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
        public override void Execute(Context context)
        {
            var fi = new System.IO.FileInfo(RuleStoreName);

            if (!fi.Exists)
            {
                throw new FileNotFoundException("RuleStoreName", RuleStoreName);
            }

            var ruleStore = new FileRuleStore(fi.FullName);
            var rsInfo = ruleStore.GetRuleSets(RuleSetInfoCollectionName, RuleStore.Filter.Latest);
            if (rsInfo.Count != 1)
            {
                // oops ... error
                throw new ApplicationException(String.Format("RuleStore {0} did not contain RuleSet {1}", RuleStoreName, RuleSetInfoCollectionName));
            }

            var ruleset = ruleStore.GetRuleSet(rsInfo[0]);

            // Create an instance of the DebugTrackingInterceptor
            var dti = new DebugTrackingInterceptor(DebugTracking);

            // Create an instance of the Policy Tester class
            var policyTester = new PolicyTester(ruleset);

            // load the facts into array
            var facts = new object[_factsList.Count]; 
            var i = 0;

            foreach (var currentFact in _factsList)
            {
                switch (currentFact.GetFactType)
                {
                    case "ObjectFact":
                        {
                            var fact = currentFact as ObjectFact;

                            object[] objectArgs = null;
                            if (null != fact.Args)
                            {
                                objectArgs = fact.Args.Split(new char[] { ',' });
                            }

                            System.Reflection.Assembly asm;
                            Type type;
                            if (fact.AssemblyPath.Length > 0)
                            {
                                asm = System.Reflection.Assembly.LoadWithPartialName(fact.AssemblyPath);
                                if (asm == null)
                                {
                                    // fail
                                    throw (new Exception("failed to create type " + fact.Type));
                                }
                                type = asm.GetType(fact.Type, true, false);
                            }
                            else
                            {
                                // must be in path
                                type = Type.GetType(fact.Type);
                            }

                            facts[i] = Activator.CreateInstance(type, objectArgs);
                            break;
                        }
                    case "DocumentFact":
                        {
                            var fact = currentFact as DocumentFact;
                            var xd1 = new XmlDocument();
                            xd1.Load(fact.InstanceDocument);
                            var txd = new TypedXmlDocument(fact.SchemaType, xd1);
                            facts[i] = txd; 
                            break;
                        }
                    case "DataConnectionFact":
                        {
                            var fact = currentFact as DataConnectionFact;
                            var conn = new SqlConnection(fact.ConnectionString);
                            conn.Open();
                            var dc = new DataConnection(fact.Dataset, fact.TableName, conn);
                            facts[i] = dc;
                            break;
                        }
                    case "dataTable":
                    case "dataRow":
                        {
                            var fact = currentFact as DataTableFact;

                            var dAdapt = new SqlDataAdapter();
                            dAdapt.TableMappings.Add("Table", fact.TableName);
                            var conn = new SqlConnection(fact.ConnectionString);
                            conn.Open();
                            var myCommand = new SqlCommand(fact.Command, conn) {CommandType = CommandType.Text};
                            dAdapt.SelectCommand = myCommand;
                            var ds = new DataSet(fact.Dataset);
                            dAdapt.Fill(ds);
                            var tdt = new TypedDataTable(ds.Tables[fact.TableName]);
                            if (fact.Type == "dataRow")
                            {
                                var tdr = new TypedDataRow(ds.Tables[fact.TableName].Rows[0], tdt);
                                facts[i] = tdr;
                            }
                            else
                            {
                                facts[i] = tdt;
                            }
                            break;
                        }
                }
                i++;
            }

            // Execute Policy Tester
            try
            {
                policyTester.Execute(facts, dti);
            }
            catch (Exception e)
            {
                context.LogException(e);
                throw;
            }
            finally
            {
                dti.CloseTraceFile();
            }

            // write out all document instances passed in
            foreach (object fact in facts)
            {
                switch (fact.GetType().Name)
                {
                    case "TypedXmlDocument":
                        {
                            var txd = (TypedXmlDocument)fact;

                            context.LogData("TypedXmlDocument result: ", txd.Document.OuterXml);
                            Stream data = StreamHelper.LoadMemoryStream(txd.Document.OuterXml);

                            // Validate if configured...
                            // HACK: We need to prevent ExecuteValidator for /each/ TypedXmlDocument
                            if (txd.DocumentType == "UBS.CLAS.PoC.Schemas.INSERTS")
                            {
                                foreach (var subStep in SubSteps)
                                {
                                    data = subStep.Execute(data, context);
                                }

                            }

                            break;
                        }
                    case "DataConnection":
                        {
                            var dc = (DataConnection)fact;
                            dc.Update(); // persist any changes
                            break;
                        }
                    case "TypedDataTable":
                        {
                            var tdt = (TypedDataTable)fact;
                            tdt.DataTable.AcceptChanges();
                            break;
                        }
                    case "TypedDataRow":
                        {
                            var tdr = (TypedDataRow)fact;
                            tdr.DataRow.AcceptChanges();
                            break;
                        }
                }
            }
        }
Beispiel #19
0
		/// <summary>
		/// ITestStep.Execute() implementation
		/// </summary>
		/// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param>
		/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
		public void Execute(System.Xml.XmlNode testConfig , Context context)
		{
			// Using Policy Tester
			 
			// Retrieve Rule-Set from Policy file
			string RuleStoreName = context.ReadConfigAsString(testConfig, "RuleStoreName");
			string RuleSetInfoCollectionName =context.ReadConfigAsString(testConfig, "RuleSetInfoCollectionName");
			string DebugTracking = context.ReadConfigAsString(testConfig, "DebugTracking");
			string SampleXML = context.ReadConfigAsString(testConfig, "SampleXML");
			string XSD = context.ReadConfigAsString(testConfig, "XSD");
			string ResultFile = context.ReadConfigAsString(testConfig, "ResultFile");

			RuleStore ruleStore = new FileRuleStore(RuleStoreName);
			RuleSetInfoCollection rsInfo = ruleStore.GetRuleSets(RuleSetInfoCollectionName, RuleStore.Filter.Latest);
			if (rsInfo.Count != 1)
			{
				// oops ... error
				throw new ApplicationException();
			}
			
			RuleSet ruleset = ruleStore.GetRuleSet(rsInfo[0]);
			
			// Create an instance of the DebugTrackingInterceptor
			DebugTrackingInterceptor dti = new DebugTrackingInterceptor(DebugTracking);

			// Create an instance of the Policy Tester class
			PolicyTester policyTester = new PolicyTester(ruleset);

			XmlDocument xd1 = new XmlDocument();
			xd1.Load(SampleXML);
								
			TypedXmlDocument doc1 = new TypedXmlDocument(XSD, xd1);

			// Execute Policy Tester
			try
			{
				policyTester.Execute(doc1, dti);
			}
			catch (Exception e) 
			{
				context.LogException(e);
				throw;
			}
			
			FileInfo f = new FileInfo(ResultFile);
			StreamWriter w = f.CreateText();
			w.Write(doc1.Document.OuterXml);
			w.Close();
		}