/// <summary> /// Remove a imported toolkit from a Rule Application. /// </summary> public void RemoveToolkit(RuleApplicationDef source, RuleApplicationDef dest) { string key = MakeKey(source); Remove(dest, key); RemoveSourceRuleapp(source, dest); }
public void ToolkitIntegrationTests() { Helper h = new Helper(); RuleApplicationDef source = RuleApplicationDef.Load(_sourcePath); RuleApplicationDef dest = RuleApplicationDef.Load(_destPath); h.ImportToolkit(source, dest); Assert.IsTrue(source.Entities.Count == dest.Entities.Count); Assert.IsTrue(source.EndPoints.Count == dest.EndPoints.Count); Assert.IsTrue(source.UdfLibraries.Count == dest.UdfLibraries.Count); Assert.IsTrue(source.Categories.Count == dest.Categories.Count); Assert.IsTrue(source.DataElements.Count == dest.DataElements.Count); Assert.IsTrue(source.RuleSets.Count == dest.RuleSets.Count); string path = AppDomain.CurrentDomain.BaseDirectory + "\\Ruleapps\\dest_" + Guid.NewGuid() + ".ruleappx"; dest.SaveToFile(path); h.RemoveToolkit(source, dest); Assert.IsTrue(dest.Entities.Count == 0); //all imported entities are gone Assert.IsTrue(dest.RuleSets.Count == 0); //all imported RuleSets are gone Assert.IsTrue(dest.EndPoints.Count == 0); //all endpoints are gone Assert.IsTrue(dest.Categories.Count == 0); //all categories are gone Assert.IsTrue(dest.DataElements.Count == 0); //all data elements are gone Assert.IsTrue(dest.UdfLibraries.Count == 0); //All udfs are gone Assert.IsTrue(dest.Attributes.Default.Count == 0); //the base 64 encoded source ruleapp is removed }
/// <summary> /// Deep search of a ruleapp for a specific def. This code may not be suitable for proper looping and stamping /// of defs because the AsEnumerable misses some artifacts. This will remain standalone for specific artifacts /// until it's decided that the ProcessChildren and this code can be refactored safely. This code has the /// advantage of not requireing the member variable to hash duplicate hits and remove them from the /// collection. /// </summary> public RuleRepositoryDefBase FindDefDeep(RuleApplicationDef ruleapp, string guid) { RuleRepositoryDefBase found = null; if ((ruleapp != null) && (String.IsNullOrEmpty(guid) == false)) { foreach (RuleRepositoryDefBase def in ruleapp.AsEnumerable()) { if (def.Guid.ToString().Equals(guid)) { //Console.WriteLine("Found...."); found = def; break; } } //If we did not get a hit, let's look at category if (found == null) { foreach (RuleRepositoryDefBase def in ruleapp.Categories) { if (def.Guid.ToString().Equals(guid)) { //Console.WriteLine("Found...."); found = def; break; } } } } return(found); }
public static string GetRuleExecutionFlowXml(RuleSetDef ruleSetDef) { string xml = null; StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); //TODO: this hack is described on the variable definition _workingRuleAppDef = ruleSetDef.GetRuleApp(); using (xw) { xw.WriteStartElement(ruleSetDef.Name); foreach (RuleRepositoryDefBase def in ruleSetDef.Rules) { //xw.WriteRaw("<Collection3>"); AppendToExecutionFlowXml(def as RuleElementDef, xw); //xw.WriteRaw("</Collection3>"); } xw.WriteEndElement(); xml = sw.ToString(); } _workingRuleAppDef = null; return(xml); }
internal void GetAll(RuleApplicationDef source, ObservableCollection <Artifact> list) { _importHash = ""; //reset if (source != null) { string key = MakeKey(source); /* * foreach (RuleRepositoryDefBase def in source.AsEnumerable()) * { * ProcessDef(def, list, key); * } * foreach (RuleRepositoryDefBase def in source.Categories) * { * ProcessDef(def,list,key); * } */ RuleRepositoryDefCollection[] colls = source.GetAllChildCollections(); foreach (RuleRepositoryDefCollection coll in colls) { foreach (RuleRepositoryDefBase def in coll) { ProcessChildren(def, list, key); } } } }
public void DuplicateEntityNameTest() { Helper h = new Helper(); RuleApplicationDef source = RuleApplicationDef.Load(_sourcePath); RuleApplicationDef dest = RuleApplicationDef.Load(_destPath); EntityDef entity = new EntityDef(); EntityDef entity2 = new EntityDef(); entity.Name = "HelloWorld"; entity2.Name = "HelloWorld"; source.Entities.Add(entity); dest.Entities.Add(entity2); try { h.ImportToolkit(source, dest); Assert.Fail("Expected InvalidImportException."); } catch (Exception ex) { if (ex.GetType().ToString().Contains("InvalidImportException")) { Assert.Pass("Got the expected exception"); } else { Assert.Fail("Did not get the expected exception. Instead got: " + ex.GetType().ToString()); } } }
internal void ValidateImport(RuleApplicationDef dest) { if (dest.Validate().Count != 0) { throw new InvalidImportException("The import you just attempted is not valid."); } }
static void Main(string[] args) { var log = new LoggerConfiguration().WriteTo.Console().CreateLogger(); Log.Logger = log; var ruleAppDef = new RuleApplicationDef(); var entity1Def = ruleAppDef.Entities.Add(new EntityDef("entity1")); var fieldDef = new FieldDef(); fieldDef.IsCalculated = true; fieldDef.Calc.FormulaText = "1 + 1"; entity1Def.Fields.Add(fieldDef); using (var session = new RuleSession(ruleAppDef)) { var entity1 = session.CreateEntity(entity1Def.Name); session.ApplyRules(); Console.WriteLine(entity1.Fields[fieldDef.Name].Value.ToString()); } Console.ReadLine(); }
private static void Main() { // Create rule application definition in memory var ruleApp = new RuleApplicationDef(); var entity = ruleApp.Entities.Add(new EntityDef("Entity")); entity.Fields.Add(new FieldDef("Field1")); entity.Fields.Add(new FieldDef("Field2")); entity.Fields.Add(new FieldDef("Total", "Field1 + Field2")); // Create the rule session from the in-memory rule application using (var session = new RuleSession(new InMemoryRuleApplicationReference(ruleApp))) { // Create entity var invoiceEntity = session.CreateEntity("Entity"); // Set values invoiceEntity.Fields["Field1"].Value = 2; invoiceEntity.Fields["Field2"].Value = 3; // Apply rules session.ApplyRules(); // Get the value of the Total calculation var total = invoiceEntity.Fields["Total"].Value; Console.WriteLine("Total is: " + total); Console.ReadLine(); } }
private string GetRuleAppEntityStructure(RuleApplicationDef def) { var entities = new List <entityBasicInfo>(); foreach (EntityDef entity in def.Entities) { var ent = new entityBasicInfo() { name = entity.Name, fields = new List <fieldBasicInfo>() }; foreach (FieldDef field in entity.Fields) { ent.fields.Add(new fieldBasicInfo() { name = field.Name, isTemporary = field.StateLocation == StateLocation.TemporaryState, isCollection = field.IsCollection, dataType = field.DataType.ToString(), entityName = field.DataTypeEntityName }); } entities.Add(ent); } var json = JsonConvert.SerializeObject(entities); return(json); }
public static string GetJavaScriptRules(RuleApplicationDef ruleAppDef) { var subscriptionKey = Properties.Settings.Default.InRuleDistKey; string returnContent; try { var client = new HttpClient(); client.BaseAddress = new Uri("https://api.distribution.inrule.com"); var uri = new Uri("https://api.distribution.inrule.com/package?logOption=None&subscription-key=" + subscriptionKey); using (var mpfdc = new MultipartFormDataContent()) { var byteArray = System.Text.Encoding.UTF8.GetBytes(ruleAppDef.GetXml()); var stream = new MemoryStream(byteArray); var content = new StreamContent(stream); mpfdc.Add(content, "ruleApplication", ruleAppDef.Name + ".ruleapp"); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data")); var result = client.PostAsync(uri, mpfdc).Result; dynamic resource = result.Content.ReadAsAsync <JObject>().Result; var resultDownload = client.GetAsync((string)resource.PackagedApplicationDownloadUrl + "?subscription-key=" + subscriptionKey).Result; returnContent = resultDownload.Content.ReadAsStringAsync().Result; } } catch (Exception e) { returnContent = e.Message; } return(returnContent); }
public void GivenMetricsWithoutServiceName_MetricsAreStored() { var ra = new RuleApplicationDef("TestRuleApplication"); var e1Def = ra.AddEntity("e1"); var f1Def = e1Def.AddField("f1", DataType.Integer, "1"); f1Def.IsMetric = true; using (var session = new RuleSession(ra)) { session.Settings.MetricLogger = new MetricLogger(DatabaseConnectionString); session.CreateEntity(e1Def.Name); session.ApplyRules(); } using (var connection = new SqlConnection(DatabaseConnectionString)) using (var command = new SqlCommand()) { var sql = $"SELECT {f1Def.Name}_{f1Def.DataType} FROM {ra.Name}.{e1Def.Name}"; command.CommandText = sql; command.Connection = connection; connection.Open(); var metricValue = command.ExecuteScalar(); Assert.That(metricValue, Is.EqualTo(1)); } }
public void Adhoc_PerformanceTest_Harness() { var ruleAppDef = RuleApplicationDef.Load("InvoiceForKpis.ruleappx"); var entityState = new string[100]; for (var i = 1; i < 101; i++) { entityState[i - 1] = File.ReadAllText($"InvoiceJsonFiles\\Invoice{i}.json"); } var stopWatch = new Stopwatch(); stopWatch.Start(); for (var i = 1; i < 101; i++) { using (var session = new RuleSession(ruleAppDef)) { session.Settings.MetricLogger = new MetricLogger(DatabaseConnectionString); session.Settings.MetricServiceName = "Integration Tests"; var invoice = session.CreateEntity("Invoice"); invoice.ParseJson(entityState[i - 1]); session.ApplyRules(); } } stopWatch.Stop(); Console.WriteLine("Execution Time:" + stopWatch.ElapsedMilliseconds); }
private static void Main() { // // Create the rule application // var ruleAppDef = new RuleApplicationDef(); // Add Entity var entityDef = new EntityDef("Rectangle"); ruleAppDef.Entities.Add(entityDef); // Add Fields entityDef.Fields.Add(new FieldDef("Width", DataType.Number)); entityDef.Fields.Add(new FieldDef("Length", DataType.Number)); entityDef.Fields.Add(new FieldDef("Area", "Width * Length", DataType.Number)); // // Run rules // using (var ruleSession = new RuleSession(ruleAppDef)) { // create default entity state var entity = ruleSession.CreateEntity("Rectangle"); entity.Fields["Width"].Value = 20; entity.Fields["Length"].Value = 10; ruleSession.ApplyRules(); Console.WriteLine("The area is: " + entity.Fields["Area"].Value); Console.ReadLine(); } }
public void GreaterThan1000Metrics_WritesSqlViaBulkCopy() { var ra = new RuleApplicationDef(nameof(GreaterThan1000Metrics_WritesSqlViaBulkCopy)); var e1Def = ra.AddEntity("e1"); var e2Def = ra.AddEntity("e2"); var ec1Def = e1Def.AddEntityCollection("ec1", e2Def.Name); var f2Def = e2Def.AddField("f2", DataType.Integer); var f3Def = e2Def.AddCalcField("f3", DataType.String, $"Concat(\"Test\", {f2Def.Name})"); f2Def.IsMetric = true; f3Def.IsMetric = true; e1Def.AddAutoSeqRuleSet("rs1") .AddSimpleRule("ifThen1", $"Count({ec1Def.Name}) < {MetricLogger.BulkCopyMetricsThreshold}") .AddAddCollectionMemberAction("add1", ec1Def.Name, new NameExpressionPairDef(f2Def.Name, $"Count({ec1Def.Name})")); using (var session = new RuleSession(ra)) { session.Settings.MetricLogger = new MetricLogger(DatabaseConnectionString); session.Settings.MetricServiceName = "Integration Tests"; var e1 = session.CreateEntity(e1Def.Name); var ec1 = e1.Collections[ec1Def.Name]; session.ApplyRules(); Assert.That(ec1.Count, Is.EqualTo(MetricLogger.BulkCopyMetricsThreshold)); Assert.That(ec1[0].Fields[f2Def.Name].Value.ToInt32(), Is.EqualTo(1)); Assert.That(ec1[999].Fields[f2Def.Name].Value.ToInt32(), Is.EqualTo(1000)); } using (var connection = new SqlConnection(DatabaseConnectionString)) using (var command = new SqlCommand()) { var sql = $"SELECT {f2Def.Name}_{f2Def.DataType}, {f3Def.Name}_{f3Def.DataType} FROM {ra.Name}.{e2Def.Name}"; command.CommandText = sql; command.Connection = connection; connection.Open(); using (var reader = command.ExecuteReader()) { reader.Read(); Assert.That(reader.GetInt32(0), Is.EqualTo(1)); var rowCount = 1; var lastRowIntValue = -1; string lastRowStringValue = null; while (reader.Read()) { lastRowIntValue = reader.GetInt32(0); lastRowStringValue = reader.GetString(1); rowCount++; } Assert.That(rowCount, Is.EqualTo(MetricLogger.BulkCopyMetricsThreshold)); Assert.That(lastRowIntValue, Is.EqualTo(1000)); Assert.That(lastRowStringValue, Is.EqualTo("Test1000")); } } }
public static EntityDef AddEntity(this RuleApplicationDef ruleApplicationDef, string entityName) { var entityDef = new EntityDef(); entityDef.Name = entityName; ruleApplicationDef.Entities.Add(entityDef); return(entityDef); }
internal ObservableCollection <Artifact> GetToolkitContents(string key, RuleApplicationDef dest) { ObservableCollection <Artifact> list = new ObservableCollection <Artifact>(); //unpack the source ruleappdef RuleApplicationDef source = this.GetSourceRuleapp("Toolkit:" + key, dest); GetAll(source, list); return(list); }
public void CountArtifactsByType(RuleApplicationDef source, ObservableCollection <ArtifactCount> summary) { ObservableCollection <Artifact> list = new ObservableCollection <Artifact>(); GetAll(source, list); //Get a flat list of everything in the ruleapp foreach (Artifact item in list) { AddArtifactToCount(item.DefBase, summary); } }
/// <summary> /// Import a Rule Application as a toolkit off the filesystem. /// </summary> public void ImportToolkit(RuleApplicationDef source, RuleApplicationDef dest) { if (ToolkitExists(source, dest)) { throw new DuplicateToolkitException("Toolkit already exists in the destination rule application."); } Import(source, dest, true); ValidateImport(dest); StoreSourceRuleapp(source, dest); }
private static Table GetTable(RuleApplicationDef ruleAppDef, string name) { var sqlConnection = new SqlConnection(ServerConnectionString); var server = new Server(new ServerConnection(sqlConnection)); var database = server.Databases[IntegrationTestDatabaseName]; var table = database.Tables[name, ruleAppDef.Name]; return(table); }
public static EntityDef GetRootEntityDef(RuleApplicationDef ruleApplicationDef) { foreach (EntityDef entityDef in ruleApplicationDef.Entities) { if (!entityDef.GetIsReferencedByOtherEntities(false)) { return(entityDef); } } return(null); }
// Helpers private string GetDiagramHtml() { RuleApplicationDef ruleApp = RuleApplicationService.RuleApplicationDef; var jsonData = GetRuleAppEntityStructure(ruleApp); string htmlContent = DiagramEntitySchema.Properties.Resources.SchemaDiagram; htmlContent = htmlContent.Replace("{ENTITYSTRUCTURE}", jsonData); return(htmlContent); }
public void IsToolkitMatchTest() { Helper h = new Helper(); RuleApplicationDef source = RuleApplicationDef.Load(_sourcePath); EntityDef ent = new EntityDef(); string key = h.MakeKey(source); h.StampAttribute(ent, key); Assert.IsTrue(h.IsToolkitMatch(ent, key)); //the purpose is to test the helper method look for a stamped attribute Assert.IsFalse(h.IsToolkitMatch(new EntityDef(), key)); //no stamp should be false }
public void TestDeepFindDef() { Helper h = new Helper(); RuleApplicationDef source = RuleApplicationDef.Load(_sourcePath); RuleApplicationDef dest = RuleApplicationDef.Load(_destPath); h.ImportToolkit(source, dest); RuleRepositoryDefBase found = h.FindDefDeep(dest, "ece7c19a-f8c1-4212-9cc2-90f6dcf837cf"); Assert.NotNull(found); }
public void ImportRuleApp(string sourceRuleappPath, string destRuleappPath) { try { ImportRuleApp(RuleApplicationDef.Load(sourceRuleappPath), RuleApplicationDef.Load(destRuleappPath), destRuleappPath); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace + ex.InnerException); } }
public void RemoveToolkit(string sourceRuleappPath, string destinationRuleappPath) { try { RemoveToolkit(RuleApplicationDef.Load(sourceRuleappPath), RuleApplicationDef.Load(destinationRuleappPath), destinationRuleappPath); } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace + ex.InnerException); } }
public void TestCountSummary() { Helper h = new Helper(); RuleApplicationDef source = RuleApplicationDef.Load(_sourcePath); ObservableCollection <ArtifactCount> result = new ObservableCollection <ArtifactCount>(); h.CountArtifactsByType(source, result); foreach (ArtifactCount item in result) { Console.WriteLine(item.ArtifcatType + " - " + item.Count); } }
internal void StoreSourceRuleapp(RuleApplicationDef source, RuleApplicationDef dest) { //Save temporarily to the filesystem string tmp = GetTmpPath(); source.SaveToFile(tmp); string file = EncodeFile(tmp); //Store in target attribute with stamp string key = MakeKey(source); StoreFileInAttribute(file, key, dest); }
static void ExplicitCache() { Console.WriteLine(); Console.WriteLine("--------------------------------------------------------"); Console.WriteLine("--- ExplicitCache()"); Console.WriteLine("--------------------------------------------------------"); // Ensure RuleApplication cache is empty RuleSession.RuleApplicationCache.Clear(); Console.WriteLine("1) Cached RuleApplications: " + RuleSession.RuleApplicationCache.Count); // Expecting 0 // Create in-memory RuleApplications RuleApplicationDef ruleAppDef1 = new RuleApplicationDef("MyApp1"); ruleAppDef1.Entities.Add(new EntityDef("Entity1")); RuleApplicationDef ruleAppDef2 = new RuleApplicationDef("MyApp2"); ruleAppDef2.Entities.Add(new EntityDef("Entity2")); // Explicit Cache Usage #1: Explicitly cache MyApp1 via RuleApplicationCache RuleApplicationReference ruleAppReference1 = RuleSession.RuleApplicationCache.Add(ruleAppDef1); Console.WriteLine("2) Cached RuleApplications: " + RuleSession.RuleApplicationCache.Count); // Expecting 1 // Explicit Cache Usage #2: Explicitly cache MyApp2 via RuleApplicationReference.Compile() RuleApplicationReference ruleAppReference2 = new InMemoryRuleApplicationReference(ruleAppDef2); ruleAppReference2.Compile(); Console.WriteLine("3) Cached RuleApplications: " + RuleSession.RuleApplicationCache.Count); // Expecting 2 // Consumption Usage #1: Create RuleSession with source RuleApplicationDef using (RuleSession session = new RuleSession(ruleAppDef1)) { session.CreateEntity("Entity1"); } using (RuleSession session = new RuleSession(ruleAppDef2)) { session.CreateEntity("Entity2"); } Console.WriteLine("4) Cached RuleApplications: " + RuleSession.RuleApplicationCache.Count); // Still only expecting 2 // Consumption Usage #2: Create RuleSession with RuleApplicationReference using (RuleSession session = new RuleSession(ruleAppReference1)) { session.CreateEntity("Entity1"); } using (RuleSession session = new RuleSession(ruleAppReference2)) { session.CreateEntity("Entity2"); } Console.WriteLine("5) Cached RuleApplications: " + RuleSession.RuleApplicationCache.Count); // Still only expecting 2 }
public static Stack <RuleRepositoryDefBase> GetAllFields(this RuleApplicationDef ruleAppDef) { var ret = new Stack <RuleRepositoryDefBase>(); foreach (var entityDef in ruleAppDef.Entities.OfType <EntityDef>()) { foreach (var fieldDef in entityDef.Fields.OfType <FieldDef>()) { ret.Push(fieldDef); } } return(ret); }