/// <summary> /// Tracks the association of a rule set with a rule engine instance. /// </summary> /// <param name="ruleSetInfo">Rule set information.</param> /// <param name="ruleEngineGuid">Rule engine instance identifier.</param> public void TrackRuleSetEngineAssociation(RuleSetInfo ruleSetInfo, Guid ruleEngineGuid) { this.ruleSetName = ruleSetInfo.Name; this.ruleEngineGuid = ruleEngineGuid.ToString(); TraceManager.RulesComponent.TraceInfo(TraceTemplateThreeParam, traceHeaderTrace, this.ruleSetName, DateTime.Now.ToString(CultureInfo.CurrentCulture)); }
public void TrackRuleSetEngineAssociation(RuleSetInfo ruleSetInfo, Guid ruleEngineGuid) { _ruleSetName = string.Format("Ruleset Name: {0}.{1}.{2}", ruleSetInfo.Name, ruleSetInfo.MajorRevision, ruleSetInfo.MinorRevision); _ruleEngineInstanceId = "Rule Engine Instance Identifier: " + ruleEngineGuid; if (_logger.IsDebugEnabled) { LogMessage("RULESET ENGINE ASSOCIATION"); } }
public object UpdateFactsAfterExecution(RuleSetInfo rulesetInfo, Microsoft.RuleEngine.RuleEngine engine, object factsHandleIn) { if (factsHandleIn != null) { // retract the DataConnection object to clean up any rows fetched during policy execution engine.Retract(factsHandleIn); } return(factsHandleIn); }
private static void ProcessPolicies( DeployRulesCommandLine cl, Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd) { RuleStore ruleStore = dd.GetRuleStore(); RuleSetInfoCollection rsInfo = ruleStore.GetRuleSets(cl.ruleSetName, RuleStore.Filter.All); Version version = ParseVersion(cl.ruleSetVersion); RuleSetInfo matchingRuleSetInfo = null; foreach (RuleSetInfo currentRsi in rsInfo) { if (currentRsi.MajorRevision == version.Major && currentRsi.MinorRevision == version.Minor) { matchingRuleSetInfo = currentRsi; break; } } if (matchingRuleSetInfo == null) { Console.WriteLine( "No published ruleset with name '" + cl.ruleSetName + "' and version '" + cl.ruleSetVersion + "'."); } else if (cl.undeploy) { Console.WriteLine("Undeploying rule set '{0}' version {1}.{2}...", cl.ruleSetName, version.Major, version.Minor); if (dd.IsRuleSetDeployed(matchingRuleSetInfo)) { dd.Undeploy(matchingRuleSetInfo); } else { Console.WriteLine(" Rule set is not currently deployed."); } if (cl.unpublish) { Console.WriteLine("Unpublishing rule set '{0}' version {1}.{2}...", cl.ruleSetName, version.Major, version.Minor); ruleStore.Remove(matchingRuleSetInfo); } } else { Console.WriteLine("Deploying rule set '{0}' version {1}.{2}...", cl.ruleSetName, version.Major, version.Minor); dd.Deploy(matchingRuleSetInfo); } }
public static string GetRules(RuleSetInfo ruleSetInfo) { string savedPath = Path.Combine(GenericHelper.GetTempFolder(Environment.MachineName), string.Format("{0}_{1}_{2}.xml", ruleSetInfo.Name, ruleSetInfo.MajorRevision.ToString(), ruleSetInfo.MinorRevision.ToString())); Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver(); dd.ExportRuleSetToFileRuleStore(ruleSetInfo, savedPath); string data = File.ReadAllText(savedPath, Encoding.UTF8); File.Delete(savedPath); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(data); return(xDoc.Beautify()); }
private void toolStripMenuItem2_Click(object sender, EventArgs e) { try { RuleSetInfo ruleSetInfo = this.treeView1.SelectedNode.Tag as RuleSetInfo; //Viewer viewer = new Viewer(GenericHelper.TransformData("BizTalkDeploymentTool.EmbeddedResources.Policy.xslt", BreHelper.GetRules(ruleSetInfo))); Viewer viewer = new Viewer(BreHelper.GetRules(ruleSetInfo)); viewer.ShowDialog(); } catch (Exception exe) { DisplayError(exe); } }
/// <summary> /// подключается к БД и возвращает все rule из БД /// </summary> /// <param name="severName"></param> /// <param name="dbName"></param> /// <returns></returns> public static RuleSetInfo[] GetRuleSetInfo(string severName, string dbName) { RuleStore ruleStore = ((IRuleSetDeploymentDriver)Microsoft.RuleEngine.RemoteUpdateService.RemoteUpdateService.LocateObject(Configuration.DeploymentDriverClass, Configuration.DeploymentDriverDll, new ArrayList() { severName, dbName }.ToArray())).GetRuleStore(); var ruleSetInfoCollection = ruleStore.GetRuleSets(RuleStore.Filter.All); var ruleSet = new RuleSetInfo[ruleSetInfoCollection.Count]; ruleSetInfoCollection.CopyTo(ruleSet, 0); return(ruleSet); }
public static int UnDeployPolicy(string policyName, int majorVersion, int minorVersion, out string message) { int result = 0; try { Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver rdd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver(); RuleSetInfo rsi = new RuleSetInfo(policyName, majorVersion, minorVersion); rdd.Undeploy(rsi); message = "Successfully Un-Deployed"; } catch (Exception exe) { message = exe.Message; return(-1); } return(result); }
public object UpdateFacts(RuleSetInfo ruleSetInfo, RuleEngine engine, object factsHandleIn) { object factsHandleOut; if (factsHandleIn == null) { SqlConnection SQLConn = new SqlConnection("Initial Catalog=Northwind;Data Source=WIN-LUNNMMJQUVE;Integrated Security=SSPI;"); DataConnection RulesConn = new DataConnection("Northwind", "Customers", SQLConn); engine.Assert(RulesConn); factsHandleOut = RulesConn; } else { factsHandleOut = factsHandleIn; } return(factsHandleOut); }
public static int DeletePolicy(string name, int majorVersion, int minorVersion, out string message) { int result = 0; try { RuleSetInfo rInfo = new RuleSetInfo(name, majorVersion, minorVersion); Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver rdd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver(); SqlRuleStore ruleStore = (SqlRuleStore)rdd.GetRuleStore(); ruleStore.Remove(rInfo); message = "Successfully Deleted"; } catch (Exception exe) { message = exe.Message; return(-1); } return(result); }
public object UpdateFacts(RuleSetInfo rulesetInfo, Microsoft.RuleEngine.RuleEngine engine, object factsHandleIn) { object factsHandleOut; // The following logic asserts the required DB rows only once and always uses the the same values (cached) during the first retrieval in subsequent execution cycles if (factsHandleIn == null) { SqlConnection con1 = new SqlConnection("Initial Catalog=Northwind;Data Source=(local);Integrated Security=SSPI;"); DataConnection dc1 = new DataConnection("Northwind", "CustInfo", con1); engine.Assert(dc1); factsHandleOut = dc1; } else { factsHandleOut = factsHandleIn; } return(factsHandleOut); }
public object UpdateFacts(RuleSetInfo rulesetInfo, Microsoft.RuleEngine.RuleEngine engine, object factsHandleIn) { object factsHandleOut; if (factsHandleIn == null) { // create the database connection since it doesn't exist SqlConnection con1 = new SqlConnection("Initial Catalog=Northwind;Data Source=(local);Integrated Security=SSPI;"); DataConnection dc1 = new DataConnection("Northwind", "PolicyValidity", con1); factsHandleOut = dc1; } else { // reuse the database connection previously created factsHandleOut = factsHandleIn; } engine.Assert(factsHandleOut); return(factsHandleOut); }
/// <summary> /// /// </summary> /// <param name="ruleSet"></param> /// <param name="outputFolder"></param> /// <returns></returns> public string ExportRuleSetToFile(RuleArtifact ruleSet, string outputFolder) { TraceManager.SmartTrace.TraceIn(); string fileName = null; try { RuleSetDeploymentDriver rsdd = new RuleSetDeploymentDriver(this.server, this.database); RuleStore store = rsdd.GetRuleStore(); RuleSetInfo rsi = new RuleSetInfo(ruleSet.Name, ruleSet.MajorVersion, ruleSet.MinorVersion); VocabularyInfoCollection referencedVocabs = store.GetReferencedVocabularies(rsi); RuleSet rs = store.GetRuleSet(rsi); fileName = Path.Combine(outputFolder, ruleSet.XmlFileName); rsdd.ExportRuleSetToFileRuleStore(rsi, fileName); fileName = Path.Combine(outputFolder, ruleSet.HtmlFileName); StreamWriter sw = new StreamWriter(fileName); RuleSetWriter writer = new RuleSetWriter(sw); writer.VocabularyDefinitions = vdefs; writer.WriteRuleSet(rs, referencedVocabs, sw); sw.Flush(); sw.Close(); } catch (Exception ex) { TraceManager.SmartTrace.TraceError(ex); TraceManager.SmartTrace.TraceError("FileName will be set to NULL"); } TraceManager.SmartTrace.TraceOut(); return(fileName); }
public object UpdateFacts(RuleSetInfo rulesetInfo, Microsoft.RuleEngine.RuleEngine engine, object factsHandleIn) { object factsHandleOut; // The following logic asserts the required DB rows only once and always uses the the same values (cached) during the first retrieval in subsequent execution cycles if (factsHandleIn == null) { string strCmd1 = "Persist Security Info=False;Integrated Security=SSPI;database=northwind;server=jinli2000"; SqlConnection con1 = new SqlConnection(strCmd1); // Using data connection binding // DataConnection dc1 = new DataConnection("Northwind", "CustInfo", con1); // Using data table binding SqlDataAdapter dAdapt1 = new SqlDataAdapter(); dAdapt1.TableMappings.Add("Table", "CustInfo"); con1.Open(); SqlCommand myCommand = new SqlCommand("SELECT * FROM CustInfo", con1); myCommand.CommandType = CommandType.Text; dAdapt1.SelectCommand = myCommand; DataSet ds = new DataSet("Northwind"); dAdapt1.Fill(ds); TypedDataTable tdt1 = new TypedDataTable(ds.Tables["CustInfo"]); engine.Assert(tdt1); factsHandleOut = tdt1; } else { factsHandleOut = factsHandleIn; } return(factsHandleOut); }
public RuleSet GetRuleSet(RuleSetInfo ruleSetInfo) { if (ruleSetInfo != null) { SqlConnection sqlConn = new SqlConnection(connectionString); sqlConn.Open(); string commandString; // If both the major and minor are 0, it is assumed that a specific version is not being requested. bool specificVersionRequested = !(ruleSetInfo.MajorVersion == 0 && ruleSetInfo.MinorVersion == 0); if (specificVersionRequested) { commandString = String.Format(CultureInfo.InvariantCulture, "SELECT TOP 1 * FROM RuleSet WHERE Name=@name AND MajorVersion={0} AND MinorVersion={1} ORDER BY MajorVersion DESC, MinorVersion DESC", ruleSetInfo.MajorVersion, ruleSetInfo.MinorVersion); } else { commandString = "SELECT TOP 1 * FROM RuleSet WHERE Name=@name ORDER BY MajorVersion DESC , MinorVersion DESC"; } SqlCommand command = new SqlCommand(commandString, sqlConn); command.Parameters.Add("@name", System.Data.SqlDbType.NVarChar, 128); command.Parameters["@name"].Value = ruleSetInfo.Name; SqlDataReader reader = command.ExecuteReader(); RuleSetData data = null; if (reader.HasRows) { reader.Read(); try { data = new RuleSetData(); data.Name = reader.GetString(0); data.OriginalName = data.Name; // will be used later to see if one of these key values changed data.MajorVersion = reader.GetInt32(1); data.OriginalMajorVersion = data.MajorVersion; data.MinorVersion = reader.GetInt32(2); data.OriginalMinorVersion = data.MinorVersion; data.RuleSetDefinition = reader.GetString(3); data.Status = reader.GetInt16(4); data.AssemblyPath = reader.GetString(5); data.ActivityName = reader.GetString(6); data.ModifiedDate = reader.GetDateTime(7); data.Dirty = false; } catch (InvalidCastException) { MessageBox.Show("Error parsing table row", "RuleSet Open Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } sqlConn.Close(); if (data != null) { return(data.RuleSet); } else if (specificVersionRequested) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Specified RuleSet version does not exist: '{0}'", ruleSetInfo.ToString())); //could use a custom exception type here } else { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "No RuleSets exist with this name: '{0}'", ruleSetInfo.Name)); } } else { return(null); } }
public RuleRecord(RuleSetInfo ruleSetInfo) { _ruleSetInfo = ruleSetInfo; }
void SaveTopic() { //var bce = CatalogExplorerFactory.CatalogExplorer(); //bce.ConnectionString = CatalogExplorerFactory.CatalogExplorer().ConnectionString; try { root = CreateDeveloperConceptualElement(); var srs = new SqlRuleStore(CatalogExplorerFactory.CatalogExplorer().ConnectionString.Replace("BizTalkMgmtDb", rulesDb)); XElement intro; //find our policy in the crowd Policy p = null; foreach (Policy policy in CatalogExplorerFactory.CatalogExplorer().Applications[appName].Policies) { if (!policy.Name.Equals(ruleName)) { continue; } p = policy; break; } if (p == null) { intro = new XElement(xmlns + "introduction", new XElement(xmlns + "para", new XText("Policy was not found!"))); root.Add(intro); if (doc.Root != null) { doc.Root.Add(root); } ReadyToSave = true; return; } var rs = srs.GetRuleSet(new RuleSetInfo(p.Name, p.MajorRevision, p.MinorRevision)); root = CreateDeveloperXmlReference(); intro = new XElement(xmlns + "introduction", new XElement(xmlns + "para", new XText(string.Format("This section outlines the properties for the {0} rule set.", p.Name)))); var exeConfInfo = new XElement(xmlns + "section", new XElement(xmlns + "title", new XText("Execution Configuration Properties")), new XElement(xmlns + "content", new XElement(xmlns + "table", new XElement(xmlns + "tableHeader", new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Property")), new XElement(xmlns + "entry", new XText("Value")))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Fact Retriever Class Name")), new XElement(xmlns + "entry", new XText(null == rs.ExecutionConfiguration.FactRetriever ? "N/A" : rs.ExecutionConfiguration.FactRetriever.ClassName ?? "N/A"))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Fact Retriever Assembly Name")), new XElement(xmlns + "entry", new XText(null == rs.ExecutionConfiguration.FactRetriever ? "N/A" : rs.ExecutionConfiguration.FactRetriever.AssemblyName ?? "N/A"))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Max Execution Loop Depth")), new XElement(xmlns + "entry", new XText(rs.ExecutionConfiguration.MaxExecutionLoopDepth.ToString()))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Maximum Working Memory Size")), new XElement(xmlns + "entry", new XText(rs.ExecutionConfiguration.MaxWorkingMemorySize.ToString()))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Translation Duration (milliseconds)")), new XElement(xmlns + "entry", new XText(rs.ExecutionConfiguration.TranslationDuration.ToString()))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Translator Class")), new XElement(xmlns + "entry", new XText(null == rs.ExecutionConfiguration.Translator ? "N/A" : rs.ExecutionConfiguration.Translator.ClassName ?? "N/A"))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Translator Assembly")), new XElement(xmlns + "entry", new XText(null == rs.ExecutionConfiguration.Translator ? "N/A" : rs.ExecutionConfiguration.Translator.AssemblyName ?? "N/A"))) ))); var rulesList = new List <XElement>(); IEnumerator iter = rs.Rules.GetEnumerator(); while (iter.MoveNext()) { var de = (DictionaryEntry)iter.Current; var r = de.Value as Rule; if (null == r) { continue; } var rsi = new RuleSetInfo(p.Name, p.MajorRevision, p.MinorRevision); var rdse = new RuleDisplayStringExtractor(srs, rsi); var s = new XElement(xmlns + "section", new XElement(xmlns + "title", new XText(string.Format("Rule: {0}", r.Name))), new XElement(xmlns + "content", new XElement(xmlns + "para", new XElement(xmlns + "legacyBold", new XText("Rule display:"))), new XElement(xmlns + "code", new XAttribute("language", "other"), new XText(rdse.ExtractRuleDisplayString(r))), new XElement(xmlns + "para", new XElement(xmlns + "legacyBold", new XText("Rule properties:"))), new XElement(xmlns + "table", new XElement(xmlns + "tableHeader", new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Property")), new XElement(xmlns + "entry", new XText("Value")))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Active")), new XElement(xmlns + "entry", new XText(r.Active.ToString()))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Priority")), new XElement(xmlns + "entry", new XText(r.Priority.ToString()))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Vocabulary Definition Id")), new XElement(xmlns + "entry", new XText(r.VocabularyLink == null ? "N/A" : r.VocabularyLink.DefinitionId ?? "N/A"))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Vocabulary Id")), new XElement(xmlns + "entry", new XText(r.VocabularyLink == null ? "N/A" : r.VocabularyLink.VocabularyId ?? "N/A"))) ))); rulesList.Add(s); } //parent section var section = new XElement(xmlns + "section", new XElement(xmlns + "title", new XText("Business RuleSet Properties")), new XElement(xmlns + "content", new XElement(xmlns + "para", new XText(rs.CurrentVersion.Description ?? "The current version of this rule set has no comments associated with it.")), new XElement(xmlns + "table", new XElement(xmlns + "tableHeader", new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Property")), new XElement(xmlns + "entry", new XText("Value")))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Current Version")), new XElement(xmlns + "entry", new XText(rs.CurrentVersion.MajorRevision + "." + rs.CurrentVersion.MinorRevision))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Last Modified By")), new XElement(xmlns + "entry", new XText(rs.CurrentVersion.ModifiedBy))), new XElement(xmlns + "row", new XElement(xmlns + "entry", new XText("Modification Timestamp")), new XElement(xmlns + "entry", new XText(rs.CurrentVersion.ModifiedTime.ToString())))), new XElement(xmlns + "sections", rulesList.ToArray(), exeConfInfo) )); root.Add(intro, section); if (doc.Root != null) { doc.Root.Add(root); } } catch (Exception ex) { HandleException("BusinessRuleTopic.DoWork", ex); } }
public static IRuleSetTrackingInterceptor Create(RuleSetInfo ruleSetInfo) { var logger = LogManager.GetLogger(ruleSetInfo.Name); return(logger.IsDebugEnabled ? new RuleSetTrackingLogger(logger) : null); }
public PolicyViewer(RuleSetInfo ruleSet) { InitializeComponent(); this.BtsRuleSetInfo = ruleSet; }
public BreRuleSetInfo(RuleSetInfo ruleSetInfo) { this._ruleSetInfo = ruleSetInfo; }
private Policy(RuleSetInfo ruleSetInfo) { _ruleSetInfo = ruleSetInfo; }
/// <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> /// Allows to execute a <see cref="Microsoft.RuleEngine.Policy"/> form code on a given set of facts. /// </summary> /// <param name="ruleSetInfo"> /// The <see cref="RuleSetInfo"/> identifying the <see cref="Microsoft.RuleEngine.Policy"/> to execute. /// </param> /// <param name="facts"> /// A collection of facts to execute the <see cref="Microsoft.RuleEngine.Policy"/> against. /// </param> public static void Execute(RuleSetInfo ruleSetInfo, params object[] facts) { _factory(ruleSetInfo).Execute(facts); }
public RuleSet GetRuleSet(RuleSetInfo ruleSetInfo) { if (ruleSetInfo != null) { SqlConnection sqlConn = new SqlConnection(connectionString); sqlConn.Open(); string commandString; // If both the major and minor are 0, it is assumed that a specific version is not being requested. bool specificVersionRequested = !(ruleSetInfo.MajorVersion == 0 && ruleSetInfo.MinorVersion == 0); if (specificVersionRequested) { commandString = String.Format(CultureInfo.InvariantCulture, "SELECT TOP 1 * FROM RuleSet WHERE Name=@name AND MajorVersion={0} AND MinorVersion={1} ORDER BY MajorVersion DESC, MinorVersion DESC", ruleSetInfo.MajorVersion, ruleSetInfo.MinorVersion); } else { commandString = "SELECT TOP 1 * FROM RuleSet WHERE Name=@name ORDER BY MajorVersion DESC , MinorVersion DESC"; } SqlCommand command = new SqlCommand(commandString, sqlConn); command.Parameters.Add("@name", System.Data.SqlDbType.NVarChar, 128); command.Parameters["@name"].Value = ruleSetInfo.Name; SqlDataReader reader = command.ExecuteReader(); RuleSetData data = null; if (reader.HasRows) { reader.Read(); try { data = new RuleSetData(); data.Name = reader.GetString(0); data.OriginalName = data.Name; // will be used later to see if one of these key values changed data.MajorVersion = reader.GetInt32(1); data.OriginalMajorVersion = data.MajorVersion; data.MinorVersion = reader.GetInt32(2); data.OriginalMinorVersion = data.MinorVersion; data.RuleSetDefinition = reader.GetString(3); data.Status = reader.GetInt16(4); data.AssemblyPath = reader.GetString(5); data.ActivityName = reader.GetString(6); data.ModifiedDate = reader.GetDateTime(7); data.Dirty = false; } catch (InvalidCastException) { MessageBox.Show("Error parsing table row", "RuleSet Open Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } sqlConn.Close(); if (data != null) return data.RuleSet; else if (specificVersionRequested) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Specified RuleSet version does not exist: '{0}'", ruleSetInfo.ToString())); //could use a custom exception type here else throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "No RuleSets exist with this name: '{0}'", ruleSetInfo.Name)); } else { return null; } }
public void TrackRuleSetEngineAssociation(RuleSetInfo ruleSetInfo, Guid ruleEngineGuid) { Trace.CorrelationManager.ActivityId = ruleEngineGuid; source.TraceEvent(TraceEventType.Start, 0, String.Format("Executing ruleset {0} {1}.{2}", ruleSetInfo.Name, ruleSetInfo.MajorRevision, ruleSetInfo.MinorRevision)); if (ruleSetInfo == null) { throw new RuleEngineArgumentNullException(string.Format(CultureInfo.CurrentCulture, "nullArgument", new object[] { "strClassName" }), base.GetType().FullName, "ruleSetInfo"); } this.m_ruleSetName = ruleSetInfo.Name; this.m_ruleEngineGuid = ruleEngineGuid.ToString(); // Create a builder to write xml to StringBuilder builder = new StringBuilder(200); using (XmlWriter xWriter = XmlWriter.Create(builder, new XmlWriterSettings { OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment })) { AppendTraceHeader(xWriter); xWriter.WriteElementString(m_traceHeaderTrace, this.m_ruleSetName); CloseTrace(xWriter); } Log(builder); }
/// <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)); }