public void ExecutePolicy(string PolicyName, object facts, int Major, int Minor) { Policy brokerPolicy = null; if (Major > 0 || Minor > 0) { brokerPolicy = new Policy(PolicyName, Major, Minor); } else { brokerPolicy = new Policy(PolicyName); } if (this.debug) { string fileName = string.Format("PolicyBrokerDebug_{0}_{1}.xml", PolicyName, Guid.NewGuid()); string folderPath = Path.GetDirectoryName(this.debugPath); string outputPath = Path.Combine(folderPath, fileName); EventLogger.Write("Writing output to " + outputPath); DebugTrackingInterceptor debugTracking = new DebugTrackingInterceptor(outputPath); brokerPolicy.Execute(facts, debugTracking); } else { brokerPolicy.Execute(facts); } brokerPolicy.Dispose(); }
/// <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(); }
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); }
} // 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(); }
/// <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; } } } }
/// <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; } } } }
private void FireRule(XmlDocument xd, string fileName) { string destDirectory = outboundTxtBx.Text.Trim(); string traceDirectory = traceTxtBx.Text.Trim(); TypedXmlDocument doc1 = new TypedXmlDocument("TrackSource.BizTalk.Schemas.InboundToRules", xd); string [] policies = new string[14] { "Data Preparation", "Pre-Processing Group 1", "Pre-Processing Group 2", "Pre-Processing Group 3", "Pre-Processing Group 4", "Pre-Processing Group 5", "Pre-Processing Group 6", "Lender Specific", "Insurance Servicing", "Post Processing Group 1", "Post Processing Group 2", "Black Hole", "Fidelity Hold", "Procedure Set" }; ProcessingTxtBx.Text = ProcessingTxtBx.Text + "Processing Started " + DateTime.Now + "\r\n"; string traceFileName = fileName + "_RuleTrace"; traceFileName = traceDirectory + traceFileName + ".txt"; if (File.Exists(traceFileName)) { File.Delete(traceFileName); } DebugTrackingInterceptor dti = new DebugTrackingInterceptor(traceFileName); try { for (int i = 0; i < policies.Length; i++) { string PolicyName = policies[i].Trim(); lblProcessing.Text = PolicyName; ProcessingTxtBx.Text = ProcessingTxtBx.Text + "Processing ... " + policies[i] + " " + DateTime.Now + "\r\n"; Application.DoEvents(); Microsoft.RuleEngine.Policy tstPolicy = new Microsoft.RuleEngine.Policy(PolicyName); ArrayList shortTermFacts = new ArrayList(); shortTermFacts = GetFacts(PolicyName); shortTermFacts.Add(doc1); tstPolicy.Execute(shortTermFacts.ToArray(), dti); tstPolicy = null; } } catch (Exception ex) { ProcessingTxtBx.Text = ProcessingTxtBx.Text + "Exception Caught Check _Excepion Text File"; string exceptionFileName = fileName + "_Exception"; exceptionFileName = traceDirectory + exceptionFileName + ".txt"; if (File.Exists(exceptionFileName)) { File.Delete(exceptionFileName); } StreamWriter sw2 = new StreamWriter(exceptionFileName); ProcessingTxtBx.Text = ProcessingTxtBx.Text + ex.Message; sw2.Write(ex.Message.ToString()); sw2.Close(); } finally { ProcessingTxtBx.Text = ProcessingTxtBx.Text + "Processing Done " + DateTime.Now + "\r\n"; lblProcessing.Text = "Writing output File"; string processedDoc = fileName + "_Outbound"; processedDoc = destDirectory + processedDoc + ".xml"; if (File.Exists(processedDoc)) { File.Delete(processedDoc); } StreamWriter sw = new StreamWriter(processedDoc); dti.CloseTraceFile(); sw.Write(doc1.Document.InnerXml.ToString()); sw.Close(); xd = null; doc1 = null; lblProcessing.Text = "Processing Completed for " + fileName; } //return xd; }
/// <summary> /// Execute the policy in question, utilizing the DebutTrackingInspector if a TrackingFolder has been specified, and applying specific policy versions /// if they have been specified /// </summary> private void ExecutePolicy(string policyName, object[] facts, string policyVersion) { DebugTrackingInterceptor dti = null; Microsoft.RuleEngine.Policy policy = null; if (string.IsNullOrEmpty(policyVersion)) { policy = new Policy(policyName); } else { int majorVersion; int minorVersion; string[] versionArray = policyVersion.Split('.'); if (versionArray.Length != 2) { throw new Exception(string.Format("Version number {0} for policy {1} did not correctly resolve to a proper major and minor version number.", policyVersion, policyName)); } if (!int.TryParse(versionArray[0], out majorVersion)) { throw new Exception(string.Format("Major version number {0} for policy {1} is invalid.", versionArray[0], policyName)); } if (!int.TryParse(versionArray[1], out minorVersion)) { throw new Exception(string.Format("Minor version number {0} for policy {1} is invalid.", versionArray[1], policyName)); } policy = new Policy(policyName, majorVersion, minorVersion); } try { TraceManager.PipelineComponent.TraceInfo("{0} - Executing Policy {1} {2}.{3}", callToken, policy.PolicyName, policy.MajorRevision.ToString(), policy.MinorRevision.ToString()); if (string.IsNullOrEmpty(trackingFolder)) { policy.Execute(facts); } else { if (trackingFolder.Substring(trackingFolder.Length - 1) != @"\") { trackingFolder = trackingFolder + @"\"; } if (!Directory.Exists(trackingFolder)) { throw new Exception(String.Format("Tracking folder {0} does not resolve to a valid folder location", trackingFolder)); } dti = new DebugTrackingInterceptor(trackingFolder + String.Format("{0}_{1}.{2}_{3}.txt", policy.PolicyName, policy.MajorRevision.ToString(), policy.MinorRevision.ToString(), callToken)); policy.Execute(facts, dti); } } catch (PolicyExecutionException ex) { TraceManager.PipelineComponent.TraceError(ex, true, Guid.Parse(callToken)); string exceptionMessage = string.Format("Exception encountered while executing BRE policy {0}. Top level exception message - {1}", policyName, ex.InnerException.Message); if (ex.InnerException.InnerException != null) { exceptionMessage = exceptionMessage + Environment.NewLine; exceptionMessage = exceptionMessage + string.Format("Innermost exception was - {0}", ex.GetBaseException()); } throw new Exception(exceptionMessage); } catch (Exception e) { TraceManager.PipelineComponent.TraceError(e, true, Guid.Parse(callToken)); throw; } finally { if (dti != null) { dti.CloseTraceFile(); } if (policy != null) { policy.Dispose(); } } }
/// <summary> /// Evaluate the policy /// </summary> /// <param name="policyName"> /// The name of the policy. /// </param> /// <param name="version"> /// The policy version. /// </param> /// <param name="providerName"> /// The provider name /// </param> /// <param name="serviceName"> /// The service name /// </param> /// <param name="bindingAccessPoint"> /// The binding access point. /// </param> /// <param name="bindingUrlType"> /// The binding URL type. /// </param> /// <param name="messageType"> /// The message type. /// </param> /// <param name="operationName"> /// The operation name /// </param> /// <param name="messageRole"> /// The role of the message. /// </param> /// <param name="parameters"> /// A dictionary of parameters. /// </param> /// <param name="messageDirection"> /// The direction of the message flow. /// </param> /// <returns> /// An interchange object containing the information resolved. /// </returns> internal static Facts.Interchange Eval( string policyName, Version version, string providerName, string serviceName, string bindingAccessPoint, string bindingUrlType, string messageType, string operationName, string messageRole, Facts.Dictionaries.Parameters parameters, Facts.Interchange.MessageDirectionTypes messageDirection) { var trace = Convert.ToBoolean(ConfigurationManager.AppSettings[Properties.Resources.AppSettingsEsbBreTrace]); var tempFileName = string.Empty; if (trace) { var traceFileFolder = ConfigurationManager.AppSettings[Properties.Resources.AppSettingsEsbBreTraceFileLocation]; if (!string.IsNullOrWhiteSpace(traceFileFolder)) { while (traceFileFolder.EndsWith(@"\")) { traceFileFolder = traceFileFolder.Substring(0, traceFileFolder.Length - 1); } } if (string.IsNullOrWhiteSpace(traceFileFolder)) { traceFileFolder = @"."; } tempFileName = string.Format( @"{0}\DirectivePolicyTrace_{1}_{2}.txt", traceFileFolder, DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid()); } // Create the array of short-term facts var interchange = new Facts.Interchange { ProviderName = providerName, ServiceName = serviceName, BindingAccessPoint = bindingAccessPoint, BindingUrlType = bindingUrlType, MessageType = messageType, OperationName = operationName, MessageRole = messageRole, Parameters = parameters, MessageDirection = messageDirection }; // Creates a fact array with an optional UDDI fact. Safely create a UDDI Inquiry Service // object using a dynamic reference. UDDI use is optional, and the UDDI library may not // be installed. Func <object[]> createFactsWithOptionalUddi = () => { try { return(new[] { interchange, Activator.CreateInstance(Properties.Resources.UddiAssembly, Properties.Resources.UddiInquiryService).Unwrap() }); } catch { return(new object[] { interchange }); } }; // Determine if static support is being used by rule engine and only assert InquiryServices if not. var shortTermFacts = IsStaticSupport() ? new object[] { interchange } : createFactsWithOptionalUddi(); if (Convert.ToBoolean(ConfigurationManager.AppSettings[Properties.Resources.AppSettingsEsbBrePolicyTester])) { PolicyTester policyTester = null; int min; int maj; if (version == null) { maj = 1; min = 0; } else { maj = version.Major; min = version.Minor; } try { // Use PolicyTester var srs = new SqlRuleStore(GetRuleStoreConnectionString()); var rsi = new RuleSetInfo(policyName, maj, min); var ruleSet = srs.GetRuleSet(rsi); if (ruleSet == null) { throw new EsbResolutionServiceException(string.Format(Properties.Resources.ExceptionRsNotInStore, policyName, maj, min)); } policyTester = new PolicyTester(ruleSet); if (trace) { // Create the debug tacking object var dti = new DebugTrackingInterceptor(tempFileName); // Execute the policy with trace policyTester.Execute(shortTermFacts, dti); // This is deliberately using Trace, rather than Debug Trace.Write("[BusinessRuleEnginePolicyEvaluator] Eval Trace: " + dti.GetTraceOutput()); } else { // Execute the policy policyTester.Execute(shortTermFacts); } } catch (Exception ex) { EventLog.WriteEntry("ESBResolutionService", GetFullMessage(ex)); throw; } finally { if (policyTester != null) { policyTester.Dispose(); } } } else { var policy = version == null ? new Policy(policyName) : new Policy(policyName, version.Major, version.Minor); try { if (trace) { // Create the debug tacking object var dti = new DebugTrackingInterceptor(tempFileName); // Execute the policy with trace policy.Execute(shortTermFacts, dti); // This is deliberately using Trace, rather than Debug Trace.Write("[BusinessRuleEnginePolicyEvaluator] Eval Trace: " + dti.GetTraceOutput()); } else { // Execute the policy policy.Execute(shortTermFacts); } } catch (Exception ex) { EventLog.WriteEntry("ESBResolutionService", GetFullMessage(ex)); throw; } finally { policy.Dispose(); } } Debug.Write("[BusinessRuleEnginePolicyEvaluator] Eval - Returned # directives: " + interchange.Directives.Count); // Perform any directive-level validations interchange.ValidateDirectives(); // If any directives are invalid, raise an exception. var validityStrings = from directive in interchange.Directives where !directive.Value.IsValid select directive.Value.ValidErrors; var validityStringList = validityStrings as IList <string> ?? validityStrings.ToList(); if (validityStringList.Any()) { throw new EsbResolutionServiceException(validityStringList.Aggregate((s1, s2) => s1 + s2).Trim()); } return(interchange); }
/// <summary> /// Return the BAM policy for a given business activity. /// </summary> /// <param name="policyName">Policy name</param> /// <param name="version">Policy version</param> /// <param name="activityName">Activity Name</param> /// <param name="stepName">Step name</param> /// <returns>A BamActivityStep object containing the resolved interceptor configuration information</returns> internal static Facts.BamActivityStep GetBamActivityPolicy(string policyName, Version version, string activityName, string stepName) { var trace = Convert.ToBoolean(ConfigurationManager.AppSettings[Properties.Resources.AppSettingsEsbBreTrace]); var tempFileName = string.Empty; if (trace) { var traceFileFolder = ConfigurationManager.AppSettings[Properties.Resources.AppSettingsEsbBreTraceFileLocation]; if (!string.IsNullOrWhiteSpace(traceFileFolder)) { while (traceFileFolder.EndsWith(@"\")) { traceFileFolder = traceFileFolder.Substring(0, traceFileFolder.Length - 1); } } if (string.IsNullOrWhiteSpace(traceFileFolder)) { traceFileFolder = @"."; } tempFileName = string.Format( @"{0}\BAMPolicyTrace_{1}_{2}.txt", traceFileFolder, DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid()); } // Create the array of short-term facts var bamActivityStep = new Facts.BamActivityStep(activityName, stepName); var shortTermFacts = new object[] { bamActivityStep }; if (Convert.ToBoolean(ConfigurationManager.AppSettings[Properties.Resources.AppSettingsEsbBrePolicyTester])) { PolicyTester policyTester = null; int min; int maj; if (version == null) { maj = 1; min = 0; } else { maj = version.Major; min = version.Minor; } try { // Use PolicyTester var srs = new SqlRuleStore(GetRuleStoreConnectionString()); var rsi = new RuleSetInfo(policyName, maj, min); var ruleSet = srs.GetRuleSet(rsi); if (ruleSet == null) { throw new EsbResolutionServiceException( string.Format(Properties.Resources.ExceptionRsNotInStore, policyName, maj, min)); } policyTester = new PolicyTester(ruleSet); if (trace) { // Create the debug tracking object var dti = new DebugTrackingInterceptor(tempFileName); // Execute the policy with trace policyTester.Execute(shortTermFacts, dti); // This is deliberately using Trace, rather than Debug Trace.Write("[BusinessRuleEnginePolicyEvaluator] GetBamActivityPolicy Trace: " + dti.GetTraceOutput()); } else { // Execute the policy policyTester.Execute(shortTermFacts); } } catch (Exception ex) { EventLog.WriteEntry("ESBResolutionService", GetFullMessage(ex)); throw; } finally { if (policyTester != null) { policyTester.Dispose(); } } } else { var policy = version == null ? new Policy(policyName) : new Policy(policyName, version.Major, version.Minor); try { if (trace) { // Create the debug tacking object var dti = new DebugTrackingInterceptor(tempFileName); // Execute the policy with trace policy.Execute(shortTermFacts, dti); // This is deliberately using Trace, rather than Debug Trace.Write("[BusinessRuleEnginePolicyEvaluator] GetBamActivityPolicy Trace: " + dti.GetTraceOutput()); } else { // Execute the policy policy.Execute(shortTermFacts); } } catch (Exception ex) { EventLog.WriteEntry("ESBResolutionService", GetFullMessage(ex)); throw; } finally { policy.Dispose(); } } if (!bamActivityStep.IsValid) { throw new EsbResolutionServiceException(bamActivityStep.ValidErrors.Trim()); } Debug.Write("[BusinessRuleEnginePolicyEvaluator] GetBamActivityPolicy - Returned a BAM policy."); return(bamActivityStep); }
/// <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(); }
/// <summary> /// Validate an XML document using a BRE policy. /// </summary> /// <param name="xmlDocument"> /// The XML message document to be validated. /// </param> /// <param name="documentType"> /// The document type of the XML document, as used in the validation rules. /// </param> /// <returns> /// A <see cref="Validations"/> object containing the results of all validations. /// </returns> public Validations ValidateDocument(XmlNode xmlDocument, string documentType) { var validations = new Validations(); if (this.directive == null) { return(validations); } if (string.IsNullOrWhiteSpace(this.directive.ValidationPolicyName)) { return(validations); } var trace = Convert.ToBoolean(ConfigurationManager.AppSettings[Resources.AppSettingsEsbBreTrace]); var tempFileName = string.Empty; if (trace) { var traceFileFolder = ConfigurationManager.AppSettings[Resources.AppSettingsEsbBreTraceFileLocation]; if (!string.IsNullOrWhiteSpace(traceFileFolder)) { while (traceFileFolder.EndsWith(@"\")) { traceFileFolder = traceFileFolder.Substring(0, traceFileFolder.Length - 1); } } if (string.IsNullOrWhiteSpace(traceFileFolder)) { traceFileFolder = @"."; } tempFileName = string.Format( @"{0}\ValidationPolicyTrace_{1}_{2}.txt", traceFileFolder, DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid()); } var breValidations = new Libraries.Facts.Validations(); // Determine if static support is being used by rule engine and create the array of short-term facts var shortTermFacts = IsStaticSupport() ? new object[] { new TypedXmlDocument(documentType, xmlDocument), breValidations } : new object[] { new TypedXmlDocument(documentType, xmlDocument), breValidations, new XmlHelper() }; // Assert the XML messsage and a validation object. var policyName = this.directive.ValidationPolicyName; Version version; Version.TryParse(this.directive.ValidationPolicyVersion, out version); if (Convert.ToBoolean(ConfigurationManager.AppSettings[Resources.AppSettingsEsbBrePolicyTester])) { PolicyTester policyTester = null; int min; int maj; if (version == null) { maj = 1; min = 0; } else { maj = version.Major; min = version.Minor; } try { // Use PolicyTester var srs = new SqlRuleStore(GetRuleStoreConnectionString()); var rsi = new RuleSetInfo(policyName, maj, min); var ruleSet = srs.GetRuleSet(rsi); if (ruleSet == null) { throw new RuleSetNotFoundException( string.Format(Resources.ExceptionRsNotInStore, policyName, maj, min)); } policyTester = new PolicyTester(ruleSet); if (trace) { // Create the debug tracking object var dti = new DebugTrackingInterceptor(tempFileName); // Execute the policy with trace policyTester.Execute(shortTermFacts, dti); Trace.Write( "[Esb.BizTalk.Orchestration.Directive] ValidateMessage Trace: " + dti.GetTraceOutput()); } else { // Execute the policy policyTester.Execute(shortTermFacts); } } finally { if (policyTester != null) { policyTester.Dispose(); } } } else { var policy = version == null ? new Policy(policyName) : new Policy(policyName, version.Major, version.Minor); try { if (trace) { // Create the debug tacking object var dti = new DebugTrackingInterceptor(tempFileName); // Execute the policy with trace policy.Execute(shortTermFacts, dti); Trace.Write( "[Esb.BizTalk.Orchestration.Directive] ValidateMessage Trace: " + dti.GetTraceOutput()); } else { // Execute the policy policy.Execute(shortTermFacts); } } finally { policy.Dispose(); } } // Throw an exception if dictated by the policy if (this.directive.ErrorOnInvalid && breValidations.ErrorCount > 0) { throw new ValidationException(string.Format("\r\nValidation Errors:\r\n{0}", breValidations.ToString(Libraries.Facts.ValidationLevel.Error))); } return(validations.InitialiseFromBreValidations(breValidations)); }