public void Then_Null_Argument_Instances_Are_Not_Allowed() { var systemUnderTest = new ArgumentCollection(); Invoking(() => systemUnderTest.Add(null)).Should().ThrowExactly <ArgumentNullException>() .Which.ParamName.Should().Be("item"); }
private static ArgumentCollection TranslateArguments(IEnumerable <Expression> argumentExpressions) { var arguments = new ArgumentCollection(); argumentExpressions.Each(arg => arguments.Add(TranslateTerm(arg))); return(arguments); }
private static ArgumentCollection TranslateMessageContextPropertyArgument(IEnumerable <Expression> argumentExpressions) { var expressions = argumentExpressions as Expression[] ?? argumentExpressions.ToArray(); var arguments = new ArgumentCollection(); TranslateMessageContextPropertyTerm((MemberExpression)expressions.First()).Each(arg => arguments.Add(arg)); expressions.Skip(1).Each(arg => arguments.Add(TranslateTerm(arg))); return(arguments); }
public void CanLocateConstructorWithImplementedInterfaceArgument() { var arguments = new ArgumentCollection(); arguments.Add("square", new Square()); var constructor = _selector.Select(typeof(ConstructorSelectorTestModel), arguments); Assert.IsNotNull(constructor); Assert.That(constructor.GetParameters()[0].ParameterType == typeof(ISquare)); }
public void CanLocateConstructorWithExactArgumentTypes() { var arguments = new ArgumentCollection(); arguments.Add("width", 5); var constructor = _selector.Select(typeof(Square), arguments); Assert.IsNotNull(constructor); Assert.That(constructor.GetParameters().Length == 1); }
public void CanLocateConstructorWithBaseClassArgument() { var arguments = new ArgumentCollection(); arguments.Add("shape", new Circle()); var constructor = _selector.Select(typeof(ConstructorSelectorTestModel), arguments); Assert.IsNotNull(constructor); Assert.That(constructor.GetParameters()[0].ParameterType == typeof(Shape)); }
internal static ArgumentCollection BuildArgInfoCol(ParameterInfo[] info) { var ret = new ArgumentCollection(); foreach (var arg in info) { ret.Add(BuildArgInfo(arg)); } return(ret); }
public void CreateArgumentsCollectionWithOneArgumentAddedTest() { string key = "key"; int value = 10; Argument argument = new Argument(key, value); ArgumentCollection argumentCollection = new ArgumentCollection(); argumentCollection.Add(argument); Assert.IsTrue(argumentCollection.Any()); Assert.IsTrue(argumentCollection.HasArgument(argument.Key)); Assert.AreEqual(argument.Value, argumentCollection[argument.Key]); }
public ArgumentCollection Map(ArgumentCollection arguments) { ArgumentCollection argumentCollection = ArgumentCollection.New(); if (arguments.HasArgument(ProcessWatcherResultArgs.ProcessName)) { argumentCollection.Add(KillProcessByNameActionExecutionArgs.ProcessName, arguments[ProcessWatcherResultArgs.ProcessName]); } return(argumentCollection); }
static RuleSet CreateRuleset(string rulesetName) { // create a simple rule // IF MySampleBusinessObject.MyValue != XMLdocument.ID // THEN MySampleBusinessObject.MySampleMethod1(5) //Creating the XML bindings on the SampleSchema XSD //Document Binding that binds to the schema name and specifies the selector XPathPair xp_root = new XPathPair("/*[local-name()='Root']", "Root"); XMLDocumentBinding xdb = new XMLDocumentBinding("SampleSchema", xp_root); //DocumentField Bindings that bind to the fields in the schema that need to be used in rule defintion XPathPair xp_ID = new XPathPair("/*[local-name()='Root']/*[local-name()='ID']", "ID"); XMLDocumentFieldBinding xfb1 = new XMLDocumentFieldBinding(Type.GetType("System.Int32"), xp_ID, xdb); //Creating .NET class (property and member) bindings // Class Bindings to bind to the class defintions whose properties and memebers will be used in rule defintion ClassBinding cb = new ClassBinding(typeof(Microsoft.Samples.BizTalk.BusinessRulesHelloWorld2.HelloWorld2Library.HelloWorld2LibraryObject)); // Member Bindings to bind to the properties and members in the MySampleBusinessObject class that need to be used in rule definition ClassMemberBinding myValue = new ClassMemberBinding("MyValue", cb); ArgumentCollection argList = new ArgumentCollection(); argList.Add(new Constant(5)); ClassMemberBinding method1 = new ClassMemberBinding("MySampleMethod", cb, argList); // create IF part LogicalExpression condition = new NotEqual(new UserFunction(myValue), new UserFunction(xfb1)); // create then part ActionCollection actions = new ActionCollection(); actions.Add(new UserFunction(method1)); // create the rule Rule rule1 = new Rule("rule1", 0, condition, actions); //create the verion information and ruleset description DateTime time = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day); VersionInfo vinf1 = new VersionInfo("Sample RuleSet to demonstrate the use of the Policy object", time, "BizRules", 1, 0); // create the ruleset RuleSet rs1 = new RuleSet(rulesetName, vinf1); rs1.Rules.Add(rule1); return(rs1); }
public void Then_An_Argument_Cannot_Be_Duplicated() { var argument = ArgumentBuilder.Build("a", 1); var duplicate = ArgumentBuilder.Build(argument.Name, "will fail"); var systemUnderTest = new ArgumentCollection { argument }; Invoking(() => systemUnderTest.Add(duplicate)).Should().ThrowExactly <InvalidOperationException>() .WithMessage($"There can be only one argument named '{argument.Name}'."); }
private void GenerateReadAction(ControllerSourceUnit srcUnit, HandlerInfo handler, CqrsControllerBuilder builder) { if (handler.RequestType.GetProperties().Any(x => x.Name == "Id" || x.Name == $"{handler.Service.Name}Id")) { // this seems to be a query for one record if (!handler.IsResponseCollection) { } else { // this is query for many records } } else { // this seems to be a query for many records. if (!handler.IsResponseCollection) { } else { ArgumentCollection arguments = new ArgumentCollection(); var queryArg = arguments.Add(handler.RequestType.Name.EndsWithSingleSuffix("Request", "Query"), "request", "FromQuery"); // this is query for many records var responseType = handler.ResponseType.Name.EndsWithSingleSuffix("Response", "Result"); builder.AppendAction(handler, "Get", responseType, HttpVerb.Get, handler.IsResponseCollection, $"api/{handler.Service.Name}", arguments.ToArray()); srcUnit.Responses.Append(GenerateResponseType(responseType, handler.ResponseType)); srcUnit.ResultToResponseMappers.Append(GenerateResultToResponseMapper(responseType, handler.ResponseType)); srcUnit.Requests.Append(GenerateRequestType(queryArg.Type, handler.RequestType)); srcUnit.RequestToCommandMappers.Append(GenerateRequestToCommandMapper(queryArg.Type, handler.RequestType)); builder.AddUsing(handler.ResponseType.Namespace + ".WebApi"); builder.AddUsing(handler.RequestType.Namespace + ".WebApi"); builder.AddUsing(handler.ResponseType.Namespace); builder.AddUsing(handler.RequestType.Namespace); } } }
public void Then_All_Arguments_Are_In_The_Collection() { var expectedArguments = new[] { ArgumentBuilder.Build("foo", "bloop"), ArgumentBuilder.Build("bar", 13), ArgumentBuilder.Build("baz", 84.19), ArgumentBuilder.Build("foobar"), ArgumentBuilder.Build("jorb", false) }; var systemUnderTest = new ArgumentCollection(); foreach (var arg in expectedArguments) { systemUnderTest.Add(arg); } systemUnderTest.Should().BeEquivalentTo(expectedArguments.ToList()); }
/// <summary> /// Gets the define options. /// </summary> /// <returns>An <see cref="ArgumentCollection"/> instance containing the define arguments.</returns> public ArgumentCollection GetDefineArguments() { ArgumentCollection defineArguments = new ArgumentCollection(); foreach (CrossCompileDefine define in this.Defines) { if (string.IsNullOrEmpty(define.DefineValue)) { defineArguments.Add(new CrossCompileOption(this.DefineSwitch + define.DefineName)); } else { defineArguments.Add( new CrossCompileOption(this.DefineSwitch + define.DefineName + "=" + define.DefineValue)); } } return defineArguments; }
private string WriteTerm(Term term) { string displayString = ""; ArgumentCollection args = null; if (term is Constant) { if (((Constant)term).Value != null) { if (((Constant)term).Value.ToString() == string.Empty) { displayString = "<empty string>"; } else { displayString = ((Constant)term).Value.ToString(); } } else { displayString = "<null>"; } } else if (term is UserFunction || term is ObjectReference) { Binding termBinding = null; if (term is UserFunction) { termBinding = ((UserFunction)term).Binding; } else { termBinding = ((ObjectReference)term).Binding; } if (termBinding is XMLDocumentBinding) { XMLDocumentBinding binding = termBinding as XMLDocumentBinding; displayString = binding.DocumentType; } else if (termBinding is DatabaseBinding) { DatabaseBinding binding = termBinding as DatabaseBinding; displayString = binding.DatasetName; } else if (termBinding is ClassBinding) { ClassBinding binding = termBinding as ClassBinding; displayString = binding.TypeName; } else if (termBinding is XMLDocumentFieldBinding) { XMLDocumentFieldBinding binding = termBinding as XMLDocumentFieldBinding; displayString = binding.DocumentBinding.DocumentType + ":" + binding.DocumentBinding.Selector.Alias + "/" + binding.Field.Alias; if (binding.Argument != null) { if (binding.MemberName.ToLower() == "setstring") { displayString += " = {0}"; } args = new ArgumentCollection(); args.Add(binding.Argument); } } else if (termBinding is DatabaseColumnBinding) { DatabaseColumnBinding binding = termBinding as DatabaseColumnBinding; displayString = binding.DatabaseBinding.DatasetName + "." + binding.DatabaseBinding.TableName + "." + binding.ColumnName; if (binding.Argument != null) { args = new ArgumentCollection(); args.Add(binding.Argument); } } else if (termBinding is DataRowBinding) { DataRowBinding binding = termBinding as DataRowBinding; displayString = binding.DisplayName; } else if (termBinding is ClassMemberBinding) { ClassMemberBinding binding = termBinding as ClassMemberBinding; displayString = binding.ClassBinding.ImplementingType.FullName + "." + binding.MemberName; args = binding.Arguments; } } else if (term is ArithmeticFunction) { ArithmeticFunction f = term as ArithmeticFunction; args = new ArgumentCollection(); args.Add(f.LeftArgument); args.Add(f.RightArgument); } else if (term is Assert) { args = new ArgumentCollection(); args.Add(((Assert)term).Facts); } else if (term is Retract) { args = new ArgumentCollection(); args.Add(((Retract)term).Facts); } else if (term is Update) { args = new ArgumentCollection(); args.Add(((Update)term).Facts); } else if (term is Halt) { args = new ArgumentCollection(); args.Add(((Halt)term).ClearAgenda); } ArrayList argsToDisplay = new ArrayList(); if (args != null) { foreach (Term t in args) { argsToDisplay.Add(WriteTerm(t)); } } string format = ""; if (term.VocabularyLink != null) { VocabularyDefinition vd = vdefs[term.VocabularyLink.DefinitionId] as VocabularyDefinition; format = vd.GetFormatString().Format; // Added to fix halt documentation CD 20140328 if (format == "halt choices") { format = "{0}"; if (displayString == "True") { argsToDisplay.Add("clear all rules firings"); } else { argsToDisplay.Add("do not clear"); } } } else { format = displayString; } displayString = TryStringFormat(format, argsToDisplay.ToArray()); return("<span class='TableData'>" + displayString + "</span>"); }
private static void GenerateWriteAction(ControllerSourceUnit srcUnit, HandlerInfo handler, CqrsControllerBuilder builder) { if (handler.RequestType.GetProperties().Any(x => x.Name == "Id" || x.Name == $"{handler.Service.Name}Id")) { var prop = handler.RequestType.GetProperties() .First(x => x.Name == "Id" || x.Name == $"{handler.Service.Name}Id"); ArgumentCollection arguments = new ArgumentCollection(); var propTypeInfo = (FullTypeNameInfo)prop.PropertyType; var idArg = arguments.Add(propTypeInfo.ToString(), prop.Name.StartLower()); var cmdArg = arguments.Add(handler.RequestType.Name.EndsWithSingleSuffix("Request", "Command"), "request", "FromBody"); // this is update action // lets check if this put or post. // Put assumes that we have command starting with name "Update" or "Modify" if (handler.RequestType.Name.StartsWithPrefixes("Update", "Modify", "Edit")) { // this is pure PUT // Id is taken from command.id // ResultResponse Put(int id, updaterequest request); var responseType = handler.ResponseType.Name.EndsWithSingleSuffix("Response", "Result"); builder.AppendAction(handler, "Put", responseType, HttpVerb.Put, false, $"api/{handler.Service.Name}/{{{idArg.Name}}}", arguments.ToArray()); srcUnit.Responses.Append(GenerateResponseType(responseType, handler.ResponseType)); srcUnit.ResultToResponseMappers.Append(GenerateResultToResponseMapper(responseType, handler.ResponseType)); srcUnit.Requests.Append(GenerateRequestType(cmdArg.Type, handler.RequestType, prop.PropertyType, prop.Name)); srcUnit.RequestToCommandMappers.Append(GenerateRequestToCommandMapper(cmdArg.Type, handler.RequestType, prop.PropertyType, prop.Name)); builder.AddUsing(handler.ResponseType.Namespace + ".WebApi"); builder.AddUsing(handler.RequestType.Namespace + ".WebApi"); builder.AddUsing(handler.ResponseType.Namespace); builder.AddUsing(handler.RequestType.Namespace); } else { // This is custom method var responseType = handler.ResponseType.Name.EndsWithSingleSuffix("Response", "Result"); string name = handler.RequestType.Name.RemoveSuffixWords("Command").RemoveWords(handler.Service.Name); builder.AppendAction(handler, name, responseType, HttpVerb.Post, handler.IsResponseCollection, $"api/{handler.Service.Name}/{{{idArg.Name}}}/{name}", arguments.ToArray()); srcUnit.Responses.Append(GenerateResponseType(responseType, handler.ResponseType)); srcUnit.ResultToResponseMappers.Append(GenerateResultToResponseMapper(responseType, handler.ResponseType)); srcUnit.Requests.Append(GenerateRequestType(cmdArg.Type, handler.RequestType, prop.PropertyType, prop.Name)); srcUnit.RequestToCommandMappers.Append(GenerateRequestToCommandMapper(cmdArg.Type, handler.RequestType, prop.PropertyType, prop.Name)); builder.AddUsing(handler.ResponseType.Namespace + ".WebApi"); builder.AddUsing(handler.RequestType.Namespace + ".WebApi"); builder.AddUsing(handler.ResponseType.Namespace); builder.AddUsing(handler.RequestType.Namespace); } } else { ArgumentCollection arguments = new ArgumentCollection(); var cmdArg = arguments.Add(handler.RequestType.Name.EndsWithSingleSuffix("Request", "Command"), "request", "FromBody"); // this might be create method if (handler.RequestType.Name.StartsWithPrefixes("Create", "Insert", "Add")) { var responseType = handler.ResponseType.Name.EndsWithSingleSuffix("Response", "Result"); builder.AppendAction(handler, "Post", responseType, HttpVerb.Post, handler.IsResponseCollection, $"api/{handler.Service.Name}", arguments.ToArray()); srcUnit.Responses.Append(GenerateResponseType(responseType, handler.ResponseType)); srcUnit.ResultToResponseMappers.Append(GenerateResultToResponseMapper(responseType, handler.ResponseType)); srcUnit.Requests.Append(GenerateRequestType(cmdArg.Type, handler.RequestType)); srcUnit.RequestToCommandMappers.Append(GenerateRequestToCommandMapper(cmdArg.Type, handler.RequestType)); builder.AddUsing(handler.ResponseType.Namespace + ".WebApi"); builder.AddUsing(handler.RequestType.Namespace + ".WebApi"); builder.AddUsing(handler.ResponseType.Namespace); builder.AddUsing(handler.RequestType.Namespace); } else { // This is unkown method. var responseType = handler.ResponseType.Name.EndsWithSingleSuffix("Response", "Result"); string name = handler.RequestType.Name.RemoveSuffixWords("Command").RemoveWords(handler.Service.Name); builder.AppendAction(handler, name, responseType, HttpVerb.Post, handler.IsResponseCollection, $"api/{handler.Service.Name}/{name}", arguments.ToArray()); srcUnit.Responses.Append(GenerateResponseType(responseType, handler.ResponseType)); srcUnit.ResultToResponseMappers.Append(GenerateResultToResponseMapper(responseType, handler.ResponseType)); srcUnit.Requests.Append(GenerateRequestType(cmdArg.Type, handler.RequestType)); srcUnit.RequestToCommandMappers.Append(GenerateRequestToCommandMapper(cmdArg.Type, handler.RequestType)); builder.AddUsing(handler.ResponseType.Namespace + ".WebApi"); builder.AddUsing(handler.RequestType.Namespace + ".WebApi"); builder.AddUsing(handler.ResponseType.Namespace); builder.AddUsing(handler.RequestType.Namespace); } } }
public ActionResult Execute(ArgumentCollection arguments) { ArgumentCollection resultArgumentCollection = ArgumentCollection.New(); try { #region process path var processPath = arguments.GetValue <string>(StartProcessActionExecutionArgs.ProcessPath); if (string.IsNullOrWhiteSpace(processPath)) { processPath = ProcessPath; } if (string.IsNullOrWhiteSpace(processPath)) { throw new MissingArgumentException(StartProcessActionArgs.ProcessPath); } processPath = Environment.ExpandEnvironmentVariables(processPath); if (Path.IsPathRooted(processPath) && !File.Exists(processPath)) { throw new Exception($"The file set as process path doesn't exist, {processPath}"); } #endregion #region process working directory var processWorkingDirectory = arguments.GetValue <string>(StartProcessActionExecutionArgs.ProcessWorkingDirectory); if (string.IsNullOrWhiteSpace(processWorkingDirectory)) { processWorkingDirectory = ProcessWorkingDirectory; } if (Path.IsPathRooted(processPath) && string.IsNullOrWhiteSpace(processWorkingDirectory)) { processWorkingDirectory = Path.GetDirectoryName(processPath); } //if (string.IsNullOrWhiteSpace(processWorkingDirectory)) // throw new MissingArgumentException(StartProcessActionArgs.ProcessWorkingDirectory); #endregion #region process arguments var processArguments = arguments.GetValue <string>(StartProcessActionExecutionArgs.ProcessArguments); if (string.IsNullOrWhiteSpace(processArguments)) { processArguments = ProcessArguments; } #endregion System.Diagnostics.Process process = new System.Diagnostics.Process { StartInfo = { FileName = processPath, Arguments = processArguments, CreateNoWindow = true, } }; if (!string.IsNullOrWhiteSpace(processWorkingDirectory)) { process.StartInfo.WorkingDirectory = processWorkingDirectory; } resultArgumentCollection = ArgumentCollection.New() .WithArgument(StartProcessActionResultArgs.ProcessPath, processPath) .WithArgument(StartProcessActionResultArgs.ProcessArguments, processArguments) .WithArgument(StartProcessActionResultArgs.ProcessWorkingDirectory, processWorkingDirectory); if (!process.Start()) { resultArgumentCollection.Add(StartProcessActionResultArgs.ProcessStarted, false); return(ActionResult.Failed().WithAdditionInformation(resultArgumentCollection)); } if (WaitForExit) { var waitResult = process.WaitForExit(WaitForExitTimeout); resultArgumentCollection.Add(StartProcessActionResultArgs.ProcessStarted, true); resultArgumentCollection.Add(StartProcessActionResultArgs.ProcessExited, waitResult); return(ActionResult.Succeeded().WithAdditionInformation(resultArgumentCollection)); } resultArgumentCollection.Add(StartProcessActionResultArgs.ProcessStarted, true); return(ActionResult.Succeeded().WithAdditionInformation(resultArgumentCollection)); } catch (Exception exception) { LoggingService.Error(exception); return(ActionResult.Failed().WithAdditionInformation(resultArgumentCollection)); } }
// 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); }
public static ArgumentCollection WithArgument(this ArgumentCollection argumentCollection, string key, object value) { argumentCollection.Add(key, value); return(argumentCollection); }
/// <summary> /// Generates a template xml to base custom scripts off of. /// </summary> /// <param name="savePath">The location the template will be saved.</param> public void GenerateXmlTemplate(string savePath) { ServiceManager.Services.LogService.WriteHeader("Generating Xml Template..."); #region Script 1 Script script = new Script(); script.Name = "Script 1"; script.Description = "Does nothing"; Executable executable = new Executable(); executable.Path = "C:/Temp/nothing.ps1"; ArgumentCollection argCollection = new ArgumentCollection(); argCollection.Add(new Argument() { Key = "-i", Value = "C:/Temp/something.bin" }); argCollection.Add(new Argument() { Key = "-x", Value = "" }); ExitCodeCollection exitCollection = new ExitCodeCollection(); exitCollection.Add(new ExitCode() { Value = 0, Message = "Files deleted", IsSuccess = true }); exitCollection.Add(new ExitCode() { Value = 1, Message = "Files failed to delete" }); exitCollection.Add(new ExitCode() { Value = 2, Message = "Couldn't find any files" }); // Add all elements into the single script file. script.Arguments = argCollection; script.ExitCodes = exitCollection; script.Executable = executable; #endregion #region Script 2 Script script2 = new Script(); script2.Name = "Script 2"; script2.Description = "Does nothing"; Executable executable2 = new Executable(); executable2.Path = "C:/Temp/Downloads/Extracted/SomethingThatWasInAZip.exe"; ArgumentCollection argCollection2 = new ArgumentCollection(); argCollection2.Add(new Argument() { Key = "-install" }); argCollection2.Add(new Argument() { Key = "-silent" }); ExitCodeCollection exitCollection2 = new ExitCodeCollection(); exitCollection2.Add(new ExitCode() { Value = 0, Message = "Script 2 has installed", IsSuccess = true }); exitCollection2.Add(new ExitCode() { Value = 1, Message = "Failed to install." }); exitCollection2.Add(new ExitCode() { Value = 2, Message = "Installed but limited." }); // Add all elements into the single script file. script2.Arguments = argCollection; script2.ExitCodes = exitCollection; script2.Executable = executable; // Add the single script above into a collection of scripts. ScriptCollection scriptCollection = new ScriptCollection(); scriptCollection.Add(script); scriptCollection.Add(script2); #endregion ServiceManager.Services.LogService.WriteLine("Generating Download Collection..."); DownloadCollection downloadCollection = new DownloadCollection(); downloadCollection.TimeOut = 60; downloadCollection.RefreshRate = 10; downloadCollection.Add(new Download() { Name = "Nothing Powershell Script", Description = "This script does nothing", DownloadUrl = "www.blank.com/nothing.ps1", DestinationPath = "C:/Temp/Downloads/nothing.ps1" }); downloadCollection.Add(new Download() { Name = "Test Zip File", Description = "This zip has nothing", DownloadUrl = "www.blank.com/nothing.zip", DestinationPath = "C:/Temp/Downloads", ExtractionPath = "C:/Temp/Downloads/Extracted" }); // Add the 2 main elements, the scripts to run and the downloads to download. Setup setup = new Setup(); setup.Scripts = scriptCollection; setup.Downloads = downloadCollection; ServiceManager.Services.LogService.WriteLine("Saving file to: \"{0}\"", savePath); setup.Serialize(savePath); }