public void GreaterThanRule_MultipleValuesWhenGreater_ResultsTrueForAll()
        {
            // ARRANGE
            int threshold = 5;
            int actual1 = 7;
            int actual2 = 10;

            // ACT
            var integerRule = new IntegerGreaterThanRule(threshold);

            var integerRuleEngine = new RuleEngine<int>();
            integerRuleEngine.Add(integerRule);

            // Set the first actual and get the result
            integerRuleEngine.ActualValue = actual1;
            var result1 = integerRuleEngine.MatchAll();

            // Set the second actual and get the result
            integerRuleEngine.ActualValue = actual2;
            var result2 = integerRuleEngine.MatchAll();

            // ASSERT
            Assert.IsTrue(result1);
            Assert.IsTrue(result2);
        }
Example #2
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.Perform<Actor>("singleplayer game started")
                .Do((actor) =>
                {
                    SendMessage(actor, "Hurrying through the rainswept November night, you're glad to see the bright lights of the Opera House. It's surprising that there aren't more people about but, hey, what do you expect in a cheap demo game...?");
                    return PerformResult.Continue;
                });

            GlobalRules.Perform<PossibleMatch, Actor>("before command")
                .First
                .Do((match, actor) =>
                    {
                        Console.WriteLine();
                        return PerformResult.Continue;
                    });

            GlobalRules.Perform<Actor>("after every command")
                .Last
                .Do((actor) =>
                {
                    Console.WriteLine();
                    return PerformResult.Continue;
                });
        }
Example #3
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclareCheckRuleBook<MudObject, MudObject>("can pull?", "[Actor, Item] : Can the actor pull the item?", "actor", "item");
            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("pull", "[Actor, Item] : Handle the actor pulling the item.", "actor", "item");

            GlobalRules.Check<MudObject, MudObject>("can pull?")
                .Do((actor, item) => MudObject.CheckIsVisibleTo(actor, item))
                .Name("Item must be visible to pull rule.");

            GlobalRules.Check<MudObject, MudObject>("can pull?")
                .Last
                .Do((a, t) =>
                    {
                        MudObject.SendMessage(a, "@does nothing");
                        return CheckResult.Disallow;
                    })
                .Name("Default disallow pulling rule.");

            GlobalRules.Perform<MudObject, MudObject>("pull")
                .Do((actor, target) =>
                {
                    MudObject.SendMessage(actor, "@nothing happens");
                    return PerformResult.Continue;
                })
                .Name("Default handle pulling rule.");

            GlobalRules.Check<MudObject, Actor>("can pull?")
                .First
                .Do((actor, thing) =>
                {
                    MudObject.SendMessage(actor, "@unappreciated", thing);
                    return CheckResult.Disallow;
                })
                .Name("Can't pull people rule.");
        }
Example #4
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("say what", "Say what?");
            Core.StandardMessage("emote what", "You exist. Actually this is an error message, but that's what you just told me to say.");
            Core.StandardMessage("speak", "^<the0> : \"<s1>\"");
            Core.StandardMessage("emote", "^<the0> <s1>");

            GlobalRules.DeclarePerformRuleBook<MudObject, String>("speak", "[Actor, Text] : Handle the actor speaking the text.", "actor", "text");

            GlobalRules.Perform<MudObject, String>("speak")
                .Do((actor, text) =>
                {
                    MudObject.SendLocaleMessage(actor, "@speak", actor, text);
                    return PerformResult.Continue;
                })
                .Name("Default motormouth rule.");

            GlobalRules.DeclarePerformRuleBook<MudObject, String>("emote", "[Actor, Text] : Handle the actor emoting the text.", "actor", "text");

            GlobalRules.Perform<MudObject, String>("emote")
                .Do((actor, text) =>
                {
                    MudObject.SendLocaleMessage(actor, "@emote", actor, text);
                    return PerformResult.Continue;
                })
                .Name("Default exhibitionist rule.");
        }
Example #5
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("you close", "You close <the0>.");
            Core.StandardMessage("they close", "^<the0> closes <the1>.");

            GlobalRules.DeclareCheckRuleBook<MudObject, MudObject>("can close?", "[Actor, Item] : Determine if the item can be closed.", "actor", "item");

            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("close", "[Actor, Item] : Handle the item being closed.", "actor", "item");

            GlobalRules.Check<MudObject, MudObject>("can close?")
                .When((actor, item) => !item.GetBooleanProperty("openable?"))
                .Do((a, b) =>
                {
                    MudObject.SendMessage(a, "@not openable");
                    return CheckResult.Disallow;
                })
                .Name("Default can't close unopenable things rule.");

            GlobalRules.Check<MudObject, MudObject>("can close?")
                .Do((actor, item) => CheckResult.Allow)
                .Name("Default close things rule.");

            GlobalRules.Perform<MudObject, MudObject>("close").Do((actor, target) =>
            {
                MudObject.SendMessage(actor, "@you close", target);
                MudObject.SendExternalMessage(actor, "@they close", actor, target);
                return PerformResult.Continue;
            }).Name("Default close reporting rule.");

            GlobalRules.Check<MudObject, MudObject>("can close?").First.Do((actor, item) => MudObject.CheckIsVisibleTo(actor, item)).Name("Item must be visible rule.");
        }
Example #6
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("not openable", "I don't think the concept of 'open' applies to that.");
            Core.StandardMessage("you open", "You open <the0>.");
            Core.StandardMessage("they open", "^<the0> opens <the1>.");

            GlobalRules.DeclareCheckRuleBook<MudObject, MudObject>("can open?", "[Actor, Item] : Can the actor open the item?", "actor", "item");

            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("opened", "[Actor, Item] : Handle the actor opening the item.", "actor", "item");

            GlobalRules.Check<MudObject, MudObject>("can open?")
                .When((actor, item) => !item.GetBooleanProperty("openable?"))
                .Do((a, b) =>
                {
                    MudObject.SendMessage(a, "@not openable");
                    return CheckResult.Disallow;
                })
                .Name("Can't open the unopenable rule.");

            GlobalRules.Check<MudObject, MudObject>("can open?")
                .Do((a, b) => CheckResult.Allow)
                .Name("Default go ahead and open it rule.");

            GlobalRules.Perform<MudObject, MudObject>("opened").Do((actor, target) =>
            {
                MudObject.SendMessage(actor, "@you open", target);
                MudObject.SendExternalMessage(actor, "@they open", actor, target);
                return PerformResult.Continue;
            }).Name("Default report opening rule.");

            GlobalRules.Check<MudObject, MudObject>("can open?").First.Do((actor, item) => MudObject.CheckIsVisibleTo(actor, item)).Name("Item must be visible rule.");
        }
Example #7
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.Perform<Actor>("inventory")
                .Do(a =>
                {
                    var wornObjects = (a as Actor).GetContents(RelativeLocations.Worn);
                    if (wornObjects.Count == 0) MudObject.SendMessage(a, "@nude");
                    else
                    {
                        MudObject.SendMessage(a, "@clothing wearing");
                        foreach (var item in wornObjects)
                            MudObject.SendMessage(a, "  <a0>", item);
                    }
                    return PerformResult.Continue;
                })
                .Name("List worn items in inventory rule.");

            GlobalRules.Check<Actor, MudObject>("can wear?")
                .Do((actor, item) =>
                {
                    var layer = item.GetPropertyOrDefault<ClothingLayer>("clothing layer", ClothingLayer.Assecories);
                    var part = item.GetPropertyOrDefault<ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak);
                    foreach (var wornItem in actor.EnumerateObjects(RelativeLocations.Worn))
                        if (wornItem.GetPropertyOrDefault<ClothingLayer>("clothing layer", ClothingLayer.Assecories) == layer && wornItem.GetPropertyOrDefault<ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak) == part)
                        {
                            MudObject.SendMessage(actor, "@clothing remove first", wornItem);
                            return CheckResult.Disallow;
                        }
                    return CheckResult.Continue;
                })
                .Name("Check clothing layering before wearing rule.");

            GlobalRules.Check<Actor, MudObject>("can remove?")
                .Do((actor, item) =>
                {
                    var layer = item.GetPropertyOrDefault<ClothingLayer>("clothing layer", ClothingLayer.Assecories);
                    var part = item.GetPropertyOrDefault<ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak);
                    foreach (var wornItem in actor.EnumerateObjects(RelativeLocations.Worn))
                        if (wornItem.GetPropertyOrDefault<ClothingLayer>("clothing layer", ClothingLayer.Assecories) < layer && wornItem.GetPropertyOrDefault<ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak) == part)
                        {
                            MudObject.SendMessage(actor, "@clothing remove first", wornItem);
                            return CheckResult.Disallow;
                        }
                    return CheckResult.Allow;
                })
                .Name("Can't remove items under other items rule.");

            GlobalRules.Perform<MudObject, Actor>("describe")
                .First
                .Do((viewer, actor) =>
                {
                    var wornItems = new List<MudObject>(actor.EnumerateObjects(RelativeLocations.Worn));
                    if (wornItems.Count == 0)
                        MudObject.SendMessage(viewer, "@clothing they are naked", actor);
                    else
                        MudObject.SendMessage(viewer, "@clothing they are wearing", actor, wornItems);
                    return PerformResult.Continue;
                })
                .Name("List worn items when describing an actor rule.");
        }
Example #8
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("dont see that", "I don't see that here.");

            GlobalRules.DeclareCheckRuleBook<MudObject, MudObject>("can examine?", "[Actor, Item] : Can the viewer examine the item?", "actor", "item");

            GlobalRules.Check<MudObject, MudObject>("can examine?")
                .First
                .Do((viewer, item) => MudObject.CheckIsVisibleTo(viewer, item))
                .Name("Can't examine what isn't here rule.");

            GlobalRules.Check<MudObject, MudObject>("can examine?")
                .Last
                .Do((viewer, item) => CheckResult.Allow)
                .Name("Default can examine everything rule.");

            GlobalRules.DeclarePerformRuleBook<MudObject>("examine", "[Actor] -> Take a close look at the actor's surroundings.");

            GlobalRules.Perform<MudObject>("examine")
                .Do((actor) =>
                {
                    MudObject.SendMessage(actor, "A detailed account of all objects present.");
                    if (actor.Location != null && actor.Location is Container)
                        foreach (var item in (actor.Location as Container).EnumerateObjects().Where(i => !System.Object.ReferenceEquals(i, actor)))
                        {
                            MudObject.SendMessage(actor, "<a0>", item);
                        }
                    return PerformResult.Continue;
                });
        }
        public void StateTransitionRule_WhenValid_ReturnsTrue()
        {
            // ARRANGE
            GameStateTransition nullToIntro = new GameStateTransition(GameState.NullState, GameState.Intro);
            GameStateTransition introToMainMenu = new GameStateTransition(GameState.Intro, GameState.MainMenu);
            GameStateTransition mainMenuToNewGame = new GameStateTransition(GameState.MainMenu, GameState.NewGame);
            GameStateTransition actualTransition = new GameStateTransition(GameState.Intro, GameState.MainMenu);

            // ACT
            var transitionNullToIntro = new StateTransitionRule(nullToIntro);
            var transitionIntroToMainMenu = new StateTransitionRule(introToMainMenu);
            var transitionMainMenuToNewGame = new StateTransitionRule(mainMenuToNewGame);

            // Create the rule engine and add the rules
            var stateTransitionRuleEngine = new RuleEngine<GameStateTransition>();
            stateTransitionRuleEngine.ActualValue = actualTransition;

            stateTransitionRuleEngine.Add(transitionNullToIntro);
            stateTransitionRuleEngine.Add(transitionIntroToMainMenu);
            stateTransitionRuleEngine.Add(transitionMainMenuToNewGame);

            // Get the result
            var result = stateTransitionRuleEngine.MatchAny();

            // ASSERT
            Assert.IsTrue(result);
        }
        /// <summary>Save the test results to TestResults table</summary>
        /// <param name="result">TestResult</param>
        public void Accept(RuleEngine.TestResult result)
        {
            if (result == null)
            {
                return;
            }

            TestResult testResult = new TestResult();
            testResult.ValidationJobID = this.jobId;
            testResult.RuleName = result.RuleName;
            testResult.Description = result.Description;

            // TODO: need ErrorMessage property on CheckResult
            testResult.ErrorMessage = result.ErrorDetail != null ? result.ErrorDetail : string.Empty;
            testResult.HelpUri = result.HelpLink;

            testResult.SpecificationUri = "version:" + result.Version + ";";

            // TODO: need spec back in HTML form.
            if (result.SpecificationSection != null && result.V4SpecificationSection != null)
            {
                testResult.SpecificationUri += "V4SpecificationSection:" + result.V4SpecificationSection + "&SpecificationSection:" + result.SpecificationSection;
            }
            else if (result.SpecificationSection != null && result.V4SpecificationSection == null)
            {
                testResult.SpecificationUri += result.SpecificationSection;
            }
            else
            {
                testResult.SpecificationUri += result.V4SpecificationSection;
            }

            if (result.V4Specification != null)
            {
                testResult.SpecificationUri += ";V4Specification:" + result.V4Specification;
            }

            testResult.Classification = result.Classification;
            testResult.ODataLevel = result.Category;
            testResult.LineNumberInError = result.LineNumberInError.ToString(CultureInfo.CurrentCulture);

            this.resultsToSave.Add(testResult);

            if (result.Details != null)
            {
                foreach (ExtensionRuleResultDetail detail in result.Details)
                {
                    this.details.Add(detail.Clone());
                }
            }

            // save results to DB in batches of 5
            if (this.resultsToSave.Count >= ResultBatchSize)
            {
                using (var ctx = SuiteEntitiesUtility.GetODataValidationSuiteEntities())
                {
                    this.ProcessResultsBatchByJobCompleted(ctx, false);
                }
            }
        }
        public void BasicOperatorTest()
        {
            // rule DTO
            var car = new CarDTO
            {
                Make = "Ford",
                Year=2010,
                Model="Expedition",
                AskingPrice=10000.0000m,
                SellingPrice=9000.0000m
            };

            // build up some rules
            var carRule1 = new Rule("Year", "2010", "GreaterThanOrEqual");
            var carRule2 = new Rule("AskingPrice", "10000.0000", "LessThanOrEqual");
            var carRule3= new Rule("Make", "Ford", "Equals");
            var carRule4 = new Rule("Model", "Ex", "StartsWith");  //gets the excursion, explorer, expedition -gass guzzlers

            var re = new RuleEngine();

            // Compile the rules as a seperate step
            Func<CarDTO, bool> carRule1Compiled = re.Compile<CarDTO>(carRule1);
            Func<CarDTO, bool> carRule2Compiled = re.Compile<CarDTO>(carRule2);
            Func<CarDTO, bool> carRule3Compiled = re.Compile<CarDTO>(carRule3);
            Func<CarDTO, bool> carRule4Compiled = re.Compile<CarDTO>(carRule4);

            Assert.AreEqual(true,carRule1Compiled(car));
            Assert.AreEqual(true,carRule2Compiled(car));
            Assert.AreEqual(true,carRule3Compiled(car));
            Assert.AreEqual(true,carRule4Compiled(car));
        }
Example #12
0
        public void Consume(int m)
        {
            var engine = new RuleEngine<Account>();
            engine.AddRuleSet(new ConsumeRule())
                  .Start(this);

            Money -= m*Discount/100;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GameSceneManager"/> class.
        /// </summary>
        /// <param name="ruleEngine">The rule engine.</param>
        public GameSceneManager(RuleEngine<GameSceneTransition> ruleEngine)
        {
            // Guard against a null RuleEngine
            if (ruleEngine == null) { throw new ArgumentNullException("ruleEngine"); }

            // Set the rule engine reference
            RuleEngine = ruleEngine;
        }
Example #14
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclarePerformRuleBook<PossibleMatch, Actor>("before command", "[Match, Actor] : Considered before every command's procedural rules are run.", "match", "actor");

            GlobalRules.DeclarePerformRuleBook<PossibleMatch, Actor>("after command", "[Match, Actor] : Considered after every command's procedural rules are run, unless the before command rules stopped the command.", "match", "actor");

            GlobalRules.DeclarePerformRuleBook<Actor>("after every command", "[Actor] : Considered after every command, even if earlier rules stopped the command.", "actor");
        }
Example #15
0
        /// <summary>
        /// Start the mud engine.
        /// </summary>
        /// <param name="Flags">Flags control engine functions</param>
        /// <param name="Database"></param>
        /// <param name="Assemblies">Modules to integrate</param>
        /// <returns></returns>
        public static bool Start(StartupFlags Flags, WorldDataService Database, params ModuleAssembly[] Assemblies)
        {
            ShuttingDown = false;
            Core.Flags = Flags;

            try
            {
                // Setup the rule engine and some basic rules.
                GlobalRules = new RuleEngine(NewRuleQueueingMode.QueueNewRules);
                GlobalRules.DeclarePerformRuleBook("at startup", "[] : Considered when the engine is started.");
                GlobalRules.DeclarePerformRuleBook<MudObject>("singleplayer game started", "Considered when a single player game is begun");

                // Integrate modules. The Core assembly is always integrated.
                IntegratedModules.Add(new ModuleAssembly(Assembly.GetExecutingAssembly(), new ModuleInfo { Author = "Blecki", Description = "RMUD Core", BaseNameSpace = "RMUD" }, "Core.dll"));
                IntegratedModules.AddRange(Assemblies);

                if ((Flags & StartupFlags.SearchDirectory) == StartupFlags.SearchDirectory)
                {
                    foreach (var file in System.IO.Directory.EnumerateFiles(System.IO.Directory.GetCurrentDirectory()).Where(p => System.IO.Path.GetExtension(p) == ".dll"))
                    {
                        var assembly = System.Reflection.Assembly.LoadFrom(file);

                        var infoType = assembly.GetTypes().FirstOrDefault(t => t.IsSubclassOf(typeof(ModuleInfo)));
                        if (infoType != null)
                        {
                            IntegratedModules.Add(new ModuleAssembly(assembly, file));
                            if ((Flags & StartupFlags.Silent) == 0)
                                Console.WriteLine("Discovered module: " + file);
                        }
                    }
                }

                foreach (var startupAssembly in IntegratedModules)
                    IntegrateModule(startupAssembly);

                PersistentValueSerializer.AddGlobalSerializer(new BitArraySerializer());

                InitializeCommandProcessor();

                GlobalRules.FinalizeNewRules();

                Core.Database = Database;
                Database.Initialize();

                GlobalRules.ConsiderPerformRule("at startup");

                if ((Flags & StartupFlags.SingleThreaded) == 0)
                    StartThreadedCommandProcesor();
            }
            catch (Exception e)
            {
                LogError("Failed to start mud engine.");
                LogError(e.Message);
                LogError(e.StackTrace);
                throw;
            }
            return true;
        }
Example #16
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.Perform<PossibleMatch, Actor>("after acting")
                .Do((match, actor) =>
                {
                    if (actor.GetProperty<MudObject>("active-quest") != null)
                    {
                        var quest = actor.GetProperty<MudObject>("active-quest");

                        if (GlobalRules.ConsiderValueRule<bool>("quest complete?", actor, quest))
                        {
                            actor.RemoveProperty("active-quest");
                            GlobalRules.ConsiderPerformRule("quest completed", actor, quest);
                        }
                        else if (GlobalRules.ConsiderValueRule<bool>("quest failed?", actor, quest))
                        {
                            actor.RemoveProperty("active-quest");
                            GlobalRules.ConsiderPerformRule("quest failed", actor, quest);
                        }
                    }

                    return PerformResult.Continue;
                })
                .Name("Check quest status after acting rule.");

            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("quest reset", "[quest, thing] : The quest is being reset. Quests can call this on objects they interact with.", "quest", "item");

            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("quest accepted", "[actor, quest] : Handle accepting a quest.", "actor", "quest");
            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("quest completed", "[actor, quest] : Handle when a quest is completed.", "actor", "quest");
            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("quest failed", "[actor, quest] : Handle when a quest is failed.", "actor", "quest");
            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject>("quest abandoned", "[actor, quest] : Handle when a quest is abandoned.", "actor", "quest");

            GlobalRules.Perform<MudObject, MudObject>("quest abandoned")
                .Last
                .Do((actor, quest) =>
                {
                    return GlobalRules.ConsiderPerformRule("quest failed", actor, quest);
                })
                .Name("Abandoning a quest is failure rule.");

            GlobalRules.DeclareValueRuleBook<MudObject, MudObject, bool>("quest available?", "[actor, quest -> bool] : Is the quest available to this actor?", "actor", "quest");

            GlobalRules.Value<MudObject, MudObject, bool>("quest available?")
                .Do((Actor, quest) => false)
                .Name("Quests unavailable by default rule.");

            GlobalRules.DeclareValueRuleBook<MudObject, MudObject, bool>("quest complete?", "[actor, quest -> bool] : Has this actor completed this quest?", "actor", "quest");

            GlobalRules.Value<MudObject, MudObject, bool>("quest complete?")
                .Do((actor, quest) => false)
                .Name("Quests incomplete by default rule.");

            GlobalRules.DeclareValueRuleBook<MudObject, MudObject, bool>("quest failed?", "[actor, quest -> bool] : Has this actor failed this quest?", "actor", "quest");

            GlobalRules.Value<MudObject, MudObject, bool>("quest failed?")
                .Do((actor, quest) => false)
                .Name("Quests can't fail by default rule.");
        }
Example #17
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclareValueRuleBook<MudObject, MudObject, String, String>("printed name", "[Viewer, Object, Article -> String] : Find the name that should be displayed for an object.", "actor", "item", "article");

            GlobalRules.Value<MudObject, MudObject, String, String>("printed name")
               .Last
               .Do((viewer, thing, article) => (String.IsNullOrEmpty(article) ? (thing.Short) : (article + " " + thing.Short)))
               .Name("Default name of a thing.");
        }
Example #18
0
        public void Charge(int m)
        {
            Money += m;
            TotalMoney += m;

            var engine = new RuleEngine<Account>();
            engine.AddRuleSet(new MemberTypeRule())
                  .Start(this);
        }
Example #19
0
        public BoardController()
        {
            SaveHandler = new SaveHandler();

            gameFromFile();
            ruleEngine = new RuleEngine(State.Board);
            logicEngine = new LogicEngine(State.Board);
            SaveHandler.OnManualSaveChange += gameFromFile;
        }
Example #20
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclarePerformRuleBook("heartbeat", "[] : Considered every tick.");

            GlobalRules.Perform("heartbeat").Do(() =>
                {
                    MudObject.TimeOfDay += Core.SettingsObject.ClockAdvanceRate;
                    return PerformResult.Continue;
                }).Name("Advance clock on heartbeat rule");
        }
Example #21
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("cant look relloc", "You can't look <s0> that.");
            Core.StandardMessage("is closed error", "^<the0> is closed.");
            Core.StandardMessage("relloc it is", "^<s0> <the1> is..");
            Core.StandardMessage("nothing relloc it", "There is nothing <s0> <the1>.");

            GlobalRules.DeclareCheckRuleBook<MudObject, MudObject, RelativeLocations>("can look relloc?", "[Actor, Item, Relative Location] : Can the actor look in/on/under/behind the item?", "actor", "item", "relloc");

            GlobalRules.Check<MudObject, MudObject, RelativeLocations>("can look relloc?")
                .Do((actor, item, relloc) => MudObject.CheckIsVisibleTo(actor, item))
                .Name("Container must be visible rule.");

            GlobalRules.Check<MudObject, MudObject, RelativeLocations>("can look relloc?")
                .When((actor, item, relloc) => !(item is Container) || (((item as Container).LocationsSupported & relloc) != relloc))
                .Do((actor, item, relloc) =>
                {
                    MudObject.SendMessage(actor, "@cant look relloc", Relloc.GetRelativeLocationName(relloc));
                    return CheckResult.Disallow;
                })
                .Name("Container must support relloc rule.");

            GlobalRules.Check<MudObject, MudObject, RelativeLocations>("can look relloc?")
                .When((actor, item, relloc) => (relloc == RelativeLocations.In) && !item.GetBooleanProperty("open?"))
                .Do((actor, item, relloc) =>
                {
                        MudObject.SendMessage(actor, "@is closed error", item);
                        return CheckResult.Disallow;
                })
                .Name("Container must be open to look in rule.");

            GlobalRules.Check<MudObject, MudObject, RelativeLocations>("can look relloc?")
                .Do((actor, item, relloc) => CheckResult.Allow)
                .Name("Default allow looking relloc rule.");

            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject, RelativeLocations>("look relloc", "[Actor, Item, Relative Location] : Handle the actor looking on/under/in/behind the item.", "actor", "item", "relloc");

            GlobalRules.Perform<MudObject, MudObject, RelativeLocations>("look relloc")
                .Do((actor, item, relloc) =>
                {
                    var contents = new List<MudObject>((item as Container).EnumerateObjects(relloc));

                    if (contents.Count > 0)
                    {
                        MudObject.SendMessage(actor, "@relloc it is", Relloc.GetRelativeLocationName(relloc), item);
                        foreach (var thing in contents)
                            MudObject.SendMessage(actor, "  <a0>", thing);
                    }
                    else
                        MudObject.SendMessage(actor, "@nothing relloc it", Relloc.GetRelativeLocationName(relloc), item);

                    return PerformResult.Continue;
                })
                .Name("List contents in relative location rule.");
        }
Example #22
0
 public static void AtStartup(RuleEngine GlobalRules)
 {
     GlobalRules.Perform<Actor>("player joined")
         .Last
         .Do((actor) =>
         {
             Core.EnqueuActorCommand(actor, "look");
             return PerformResult.Continue;
         })
         .Name("New players look rule.");
 }
Example #23
0
		public void Setup()
		{
			ruleSet = new List<Rule>
			{
				new ACellDeadWhenHasOneNeighbor(),
				new ACellDeadWhenHasMoreThanThreeNeighbors(),
				new ACellLiveWhenHasThreeNeighbors(),
				new ACellMantainsItsStateWhenHasTwoNeighborsRule()
			};
			ruleEngine = new RuleEngine(ruleSet);
		}
Example #24
0
        public void should_throw_for_unrecognized_comparison_operators()
        {
            var ruleEngine = new RuleEngine();

            Assert.Throws<UnrecognizedComparisonOperatorException>(() =>
            {
                ruleEngine.CheckCondition("Age > 10 OR TotalProjects notexistsoperator 5", new Person
                {
                    Age = 5
                });
            });
        }
Example #25
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclareCheckRuleBook<MudObject, MudObject, MudObject>("can tape to?", "[Actor, Subject, Object] : Can the subject be taped to the object?");

            GlobalRules.Check<MudObject, MudObject, MudObject>("can tape to?")
                .Do((actor, subject, @object) => MudObject.CheckIsVisibleTo(actor, @object))
                .Name("Object must be visible to tape something to it rule.");

            GlobalRules.Check<MudObject, MudObject, MudObject>("can tape to?")
                .Do((actor, subject, @object) => MudObject.CheckIsHolding(actor, subject))
                .Name("Subject must be held to tape it to something rule.");

            GlobalRules.Check<MudObject, MudObject, MudObject>("can tape to?")
                .When((actor, subject, @object) => !MudObject.ObjectContainsObject(actor, MudObject.GetObject("DuctTape")))
                .Do((actor, subject, @object) =>
                {
                    MudObject.SendMessage(actor, "You don't have any tape.");
                    return CheckResult.Disallow;
                })
                .Name("Need tape to tape rule.");

            GlobalRules.Check<MudObject, MudObject, MudObject>("can tape to?")
                .When((actor, subject, @object) => subject.GetPropertyOrDefault<Weight>("weight", Weight.Normal) != Weight.Light)
                .Do((actor, subject, @object) =>
                {
                    MudObject.SendMessage(actor, "^<the0> is too heavy to tape to things.", subject);
                    return CheckResult.Disallow;
                })
                .Name("Can only tape light things rule.");

            GlobalRules.Check<MudObject, MudObject, MudObject>("can tape to?")
               .When((actor, subject, @object) => !(@object is Container) || ((@object as Container).Supported & RelativeLocations.On) != RelativeLocations.On)
               .Do((actor, subject, @object) =>
               {
                   MudObject.SendMessage(actor, "I can't tape things to <the0>.", @object);
                   return CheckResult.Disallow;
               })
               .Name("Can only tape things to containers that support 'on' rule");

            GlobalRules.Check<MudObject, MudObject, MudObject>("can tape to?")
                .Do((a, b, c) => CheckResult.Allow)
                .Name("Default allow taping things to things rule.");

            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject, MudObject>("taped to", "[Actor, Subject, Object] : Handle the actor taping the subject to the object.");

            GlobalRules.Perform<MudObject, MudObject, MudObject>("taped to").Do((actor, subject, @object) =>
            {
                MudObject.SendMessage(actor, "Okay, I taped <the0> onto <the1>.", subject, @object);
                MudObject.Move(subject, @object, RelativeLocations.On);
                return PerformResult.Continue;
            });
        }
        public void ExecuteRules_ZeroAmount_HasRuleViolation()
        {
            var ruleEngine = new RuleEngine<SelfPayment>(new SelfPaymentRuleCollection());
            var selfPayment = new SelfPayment(
                new Mock<Patient>().Object,
                new Mock<Staff>().Object,
                new Money(new Currency("en-US"), 0),
                new PaymentMethod(),
                DateTime.Now);
            var results = ruleEngine.ExecuteAllRules(selfPayment);

            Assert.IsTrue(results.HasRuleViolation);
        }
        public PromotionPricingStage(
            IPromotionService promotionService,
            IPromotionPolicyProvider policyFactory,
            RuleEngine ruleEngine)
        {
            Require.NotNull(promotionService, "promotionService");
            Require.NotNull(policyFactory, "policyFactory");
            Require.NotNull(ruleEngine, "ruleEngine");

            _promotionService = promotionService;
            _policyFactory = policyFactory;
            _ruleEngine = ruleEngine;
        }
Example #28
0
 public void ShouldForwardChainRules()
 {
     var ruleBase = new RuleBase<Target>();
     var ruleSet = new RuleSet<Target>();
     var rule = new Rule<Target>("rule 1", "description of rule 1", t => t.Number == 0, t => t.Number = 1);
     var rule2 = new Rule<Target>("rule 2", "", t => t.Number == 1, t => t.Number = 2);
     ruleSet.AddRule(rule);
     ruleSet.AddRule(rule2);
     ruleBase.AddRuleSet(ruleSet);
     var target = new Target();
     var ruleEngine = new RuleEngine<Target>(ruleBase);
     ruleEngine.Execute(target);
     Assert.Equal(2, target.Number);
 }
Example #29
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("you unlock", "You unlock <the0>.");
            Core.StandardMessage("they unlock", "^<the0> unlocks <the1> with <a2>.");

            GlobalRules.DeclarePerformRuleBook<MudObject, MudObject, MudObject>("unlocked", "[Actor, Item, Key] : Handle the actor unlocking the item with the key.", "actor", "item", "key");

            GlobalRules.Perform<MudObject, MudObject, MudObject>("unlocked").Do((actor, target, key) =>
            {
                MudObject.SendMessage(actor, "@you unlock", target);
                MudObject.SendExternalMessage(actor, "@they unlock", actor, target, key);
                return PerformResult.Continue;
            });
        }
Example #30
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclarePerformRuleBook<Actor>("player joined", "[Player] : Considered when a player enters the game.", "actor");

            GlobalRules.DeclarePerformRuleBook<Actor>("player left", "[Player] : Considered when a player leaves the game.", "actor");

            GlobalRules.Perform<Actor>("player joined")
                .First
                .Do((actor) =>
                {
                    MudObject.Move(actor, MudObject.GetObject(Core.SettingsObject.NewPlayerStartRoom));
                    return PerformResult.Continue;
                })
                .Name("Move to start room rule.");
        }
Example #31
0
 public MortalCell(CellState state, int x, int y, RuleEngine rules, int maxAge) : base(state, x, y, rules)
 {
     MaxAge = maxAge;
 }
Example #32
0
        private async Task InitLongRunning()
        {
            var spk = new UWPLocalSpeaker(media, Windows.Media.SpeechSynthesis.VoiceGender.Female);

            string localIp = GetLocalIp();

            if (localIp == null)
            {
                localIp = "127.0.0.1";
            }
            if (localIp == "")
            {
                localIp = "127.0.0.1";
            }
            spk.Speak($"мой адрес не дом и не улица, мой адрес {localIp} и точка");
            CoreWindow.GetForCurrentThread().KeyDown += KeyPressed;
            Log.Trace("BEFORE receive actual kb");

            try {
                HttpResponseMessage httpResponseMessage = await httpClient.GetAsync("https://github.com/");

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    byte[] git_kb = await httpClient.GetByteArrayAsync(Config.GitKBUrl);

                    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                    StorageFile   sampleFile    =
                        await storageFolder.CreateFileAsync(Config.GitKBFileName, CreationCollisionOption.ReplaceExisting);

                    await Windows.Storage.FileIO.WriteBytesAsync(sampleFile, git_kb);

                    RE = BracketedRuleEngine.LoadBracketedKb(sampleFile);
                    Log.Trace("Using actual git's config version");
                }
                else
                {
                    //try {
                    //    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                    //    StorageFile sampleFile = await storageFolder.GetFileAsync(Config.GitKBFileName);
                    //    RE = BracketedRuleEngine.LoadBracketedKb(sampleFile);
                    //    Log.Trace("Using local git's config version");
                    //    offline = true;
                    //}
                    //catch (Exception) {
                    RE = BracketedRuleEngine.LoadBracketedKb(Config.KBFileName);
                    Log.Trace("Using local nongit config version");
                    offline = true;
                    //}
                }
            }
            catch (Exception)
            {
                //try
                //{
                //    StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                //    StorageFile sampleFile = await storageFolder.GetFileAsync(Config.GitKBFileName);
                //    RE = BracketedRuleEngine.LoadBracketedKb(sampleFile);
                //    Log.Trace("Using local git's config version");
                //    offline = true;
                //}
                //catch (Exception)
                //{
                RE = BracketedRuleEngine.LoadBracketedKb(Config.KBFileName);
                Log.Trace("Using local nongit config version");
                offline = true;
                //}
            }
            Log.Trace("AFTER receive actual kb");


            RE.SetSpeaker(spk);
            RE.Initialize();
            RE.SetExecutor(ExExecutor);
            FaceWaitTimer.Tick   += StartDialog;
            DropoutTimer.Tick    += FaceDropout;
            PreDropoutTimer.Tick += PreDropout;
            InferenceTimer.Tick  += InferenceStep;
            InitGpio();
            if (gpio != null)
            {
                ArduinoInputTimer.Tick += ArduinoInput;
                ArduinoInputTimer.Start();
            }
            yesNoCancelGPIO.Execute(RE.State);
            media.MediaEnded += EndSpeech;

            // Create face detection
            var def = new FaceDetectionEffectDefinition();

            def.SynchronousDetectionEnabled = false;
            def.DetectionMode                     = FaceDetectionMode.HighPerformance;
            FaceDetector                          = (FaceDetectionEffect)(await MC.AddVideoEffectAsync(def, MediaStreamType.VideoPreview));
            FaceDetector.FaceDetected            += FaceDetectedEvent;
            FaceDetector.DesiredDetectionInterval = TimeSpan.FromMilliseconds(100);
            LogLib.Log.Trace("Ready to start face recognition");
            await MC.StartPreviewAsync();

            LogLib.Log.Trace("Face Recognition Started");
            var props = MC.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);

            VideoProps           = props as VideoEncodingProperties;
            FaceDetector.Enabled = true;

            InferenceTimer.Start();
        }
Example #33
0
File: Rules.cs Project: SinaC/RMUD
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.Perform <Actor>("inventory")
            .Do(a =>
            {
                var wornObjects = (a as Actor).GetContents(RelativeLocations.Worn);
                if (wornObjects.Count == 0)
                {
                    MudObject.SendMessage(a, "@nude");
                }
                else
                {
                    MudObject.SendMessage(a, "@clothing wearing");
                    foreach (var item in wornObjects)
                    {
                        MudObject.SendMessage(a, "  <a0>", item);
                    }
                }
                return(PerformResult.Continue);
            })
            .Name("List worn items in inventory rule.");

            GlobalRules.Check <Actor, MudObject>("can wear?")
            .Do((actor, item) =>
            {
                var layer = item.GetPropertyOrDefault <ClothingLayer>("clothing layer", ClothingLayer.Assecories);
                var part  = item.GetPropertyOrDefault <ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak);
                foreach (var wornItem in actor.EnumerateObjects(RelativeLocations.Worn))
                {
                    if (wornItem.GetPropertyOrDefault <ClothingLayer>("clothing layer", ClothingLayer.Assecories) == layer && wornItem.GetPropertyOrDefault <ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak) == part)
                    {
                        MudObject.SendMessage(actor, "@clothing remove first", wornItem);
                        return(CheckResult.Disallow);
                    }
                }
                return(CheckResult.Continue);
            })
            .Name("Check clothing layering before wearing rule.");

            GlobalRules.Check <Actor, MudObject>("can remove?")
            .Do((actor, item) =>
            {
                var layer = item.GetPropertyOrDefault <ClothingLayer>("clothing layer", ClothingLayer.Assecories);
                var part  = item.GetPropertyOrDefault <ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak);
                foreach (var wornItem in actor.EnumerateObjects(RelativeLocations.Worn))
                {
                    if (wornItem.GetPropertyOrDefault <ClothingLayer>("clothing layer", ClothingLayer.Assecories) < layer && wornItem.GetPropertyOrDefault <ClothingBodyPart>("clothing part", ClothingBodyPart.Cloak) == part)
                    {
                        MudObject.SendMessage(actor, "@clothing remove first", wornItem);
                        return(CheckResult.Disallow);
                    }
                }
                return(CheckResult.Allow);
            })
            .Name("Can't remove items under other items rule.");


            GlobalRules.Perform <MudObject, Actor>("describe")
            .First
            .Do((viewer, actor) =>
            {
                var wornItems = new List <MudObject>(actor.EnumerateObjects(RelativeLocations.Worn));
                if (wornItems.Count == 0)
                {
                    MudObject.SendMessage(viewer, "@clothing they are naked", actor);
                }
                else
                {
                    MudObject.SendMessage(viewer, "@clothing they are wearing", actor, wornItems);
                }
                return(PerformResult.Continue);
            })
            .Name("List worn items when describing an actor rule.");
        }
 /// <summary>
 /// Creates a new instance with the given input knowledge and the node where the transfer is applied to.
 /// </summary>
 /// <param name="inputKnowledge">The input knowledge at the current node.</param>
 /// <param name="node">The node where the transfer is applied to.</param>
 /// <param name="interprocedural"><code>True</code> if this is an interprocedural analysis.</param>
 internal NodeTransfer(ISet <VariableDescriptor> inputKnowledge, FlowNode node, bool interprocedural)
 {
     _inputKnowledge = inputKnowledge;
     _flowNode       = node;
     _ruleEngine     = new RuleEngine(inputKnowledge, interprocedural);
 }
Example #35
0
 static void Main(string[] args)
 {
     _ = ShowWindow(GetConsoleWindow(), SW_HIDE);
     RuleEngine.New(Config.Factory())(new Uri(args[0])).Run(args[0]);
 }
Example #36
0
 public BaseRule()
 {
     RulesEngine = new RuleEngine <T>();
 }
Example #37
0
        private void Main(ProgramOptions options)
        {
            // Validate rules folder
            if (string.IsNullOrWhiteSpace(options.RulesFolder) || options.RulesFolder.IndexOfAny(new char[] { '"', '\'', '\\', '/', ':' }) >= 0)
            {
                Display.WriteText("Specified rule folder name does not seems to be valid: \n\n" + options.RulesFolder +
                                  "\n\nEnsure the value is a single folder name (not a full path) without special characters: \", ', \\, / and :.");
                return;
            }

            // Initialize data file provider
            IDataFileProvider fileProvider;

            try
            {
                // Use data folder path from options which will default the parent direcotry unless another path is specified
                // Pass custom plugins.txt file path if provided via options
                fileProvider = new DefaultDataFileProvider(options.DataFolder, options.PluginListFile);
            }
            catch (Exception ex)
            {
                // Program will exit on error
                // Appropriate hint is displayed
                Display.WriteText("Data folder path does not seems to be valid: " + ex.Message + "\n\n" + options.DataFolder +
                                  "\n\nUse option -d or --data to specify correct path to the data folder or use option -h or --help for more help.");
                return;
            }

            // Mod Ogranizer
            if (!string.IsNullOrEmpty(options.ModOrganizerProfile))
            {
                try
                {
                    // After verifying data folder with DefaultDataFolderProvider
                    // replace it with MO data file provider
                    fileProvider = new ModOrganizerDataFileProvider(options.DataFolder, options.ModOrganizerProfile, options.ModOrganizerModsPath);
                }
                catch (Exception ex)
                {
                    // Program will exit on error
                    // Appropriate hint is displayed
                    Display.WriteText("Incorrect Mod Organizer configuration: " + ex.Message +
                                      "\n\nUse option -h or --help for more help.");
                    return;
                }
            }

            // Determine output plugin file name, use filename from options if provided
            string targetPluginFileName = options.OutputFilename ?? string.Format("Patcher-{0}.esp", options.RulesFolder);

            // File log will be created in the data folder, named as the output plugin plus .log extension
            string logFileName = Path.Combine(Program.ProgramFolder, Program.ProgramLogsFolder, targetPluginFileName + ".log");

            using (var logger = new StreamLogger(fileProvider.GetDataFile(FileMode.Create, logFileName).Open()))
            {
                Log.AddLogger(logger);

                // Put some handy info at the beginning of the log file
                Log.Info(Program.GetProgramVersionInfo());
                Log.Fine("Options: " + options);

                try
                {
                    // Create suitable data context according to the data folder content
                    using (DataContext context = DataContext.CreateContext(fileProvider))
                    {
                        Log.Fine("Initialized data context: " + context.GetType().FullName);

                        // Context tweaks
                        context.AsyncFormIndexing = true;
                        context.AsyncFormLoading  = options.MaxLoadingThreads > 0;
                        context.AsyncFormLoadingWorkerThreshold = 100;
                        context.AsyncFromLoadingMaxWorkers      = Math.Max(1, options.MaxLoadingThreads);

                        if (!options.Append)
                        {
                            // Inform context to ignore output plugin in case it is active
                            context.IgnorePlugins.Add(targetPluginFileName);
                        }

                        // Index all forms except hidden (such as cells and worlds)
                        context.Load();

                        if (options.Append && context.Plugins.Exists(targetPluginFileName) && context.Plugins.Count > 0)
                        {
                            // Make sure output plugin is loaded last when appending
                            var plugin = context.Plugins[(byte)(context.Plugins.Count - 1)];
                            if (!plugin.FileName.Equals(targetPluginFileName))
                            {
                                throw new ApplicationException("Output plugin must be loaded last when appending changes.");
                            }
                        }

                        using (RuleEngine engine = new RuleEngine(context))
                        {
                            engine.RulesFolder = options.RulesFolder;

                            // Apply debug scope to rule engine
                            if (!string.IsNullOrEmpty(options.DebugScope))
                            {
                                if (options.DebugScope == "*")
                                {
                                    engine.DebugAll = true;
                                }
                                else
                                {
                                    var parts = options.DebugScope.Split('/', '\\');
                                    if (parts.Length > 0)
                                    {
                                        engine.DebugPluginFileName = parts[0];
                                    }
                                    if (parts.Length > 1)
                                    {
                                        engine.DebugRuleFileName = parts[1];
                                    }
                                }
                            }

                            foreach (var param in options.Parameters)
                            {
                                var split = param.Split('=');
                                if (split.Length != 2 || !split[0].Contains(':'))
                                {
                                    Log.Warning("Ignored malformatted parameter: '{0}' Expected format is 'plugin:param=value'", param);
                                }
                                engine.Params.Add(split[0], split[1]);
                            }

                            // Load rules
                            engine.Load();

#if DEBUG
                            // Load supported forms in debug mode
                            context.LoadForms(f => context.IsSupportedFormKind(f.FormKind));
#else
                            // Load all indexed forms in release mode
                            context.LoadForms();
#endif

                            if (options.Append && context.Plugins.Exists(targetPluginFileName))
                            {
                                // Use existing plugin as the target plugin
                                engine.ActivePlugin = context.Plugins[targetPluginFileName];
                            }
                            else
                            {
                                // Create and set up target plugin
                                engine.ActivePlugin             = context.CreatePlugin(targetPluginFileName);
                                engine.ActivePlugin.Author      = options.Author ?? Program.GetProgramVersionInfo();
                                engine.ActivePlugin.Description = options.Description ?? string.Format("Generated by {0}", Program.GetProgramVersionInfo());
                            }

                            // See if target plugin exists
                            var targetPluginFile = fileProvider.GetDataFile(FileMode.Open, targetPluginFileName);
                            if (targetPluginFile.Exists())
                            {
                                Log.Info("Target plugin {0} already exists and will be overwriten, however previously used FormIDs will be preserved if possible.", targetPluginFileName);

                                try
                                {
                                    var inspector = new PluginInspector(context, targetPluginFile);
                                    foreach (var record in inspector.NewRecords)
                                    {
                                        engine.ActivePlugin.ReserveFormId(record.FormId, record.EditorId);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.Warning("Previously used Form IDs cannot be preserved because target plugin {0} could not be read: {1}", targetPluginFileName, ex.ToString());
                                }
                            }

                            engine.Run();

                            if (!options.KeepDirtyEdits)
                            {
                                engine.ActivePlugin.PurgeDirtyEdits();
                            }

                            // Prepare list of master to be removed by force
                            IEnumerable <string> removeMasters = options.RemovedMasters != null?options.RemovedMasters.Split(',') : null;

                            // Save target plugin
                            engine.ActivePlugin.Save(removeMasters);
                        }
                    }
                }
                catch (UserAbortException ex)
                {
                    Log.Error("Program aborted: " + ex.Message);
                }
#if !DEBUG
                catch (Exception ex)
                {
                    Log.Error("Program error: " + ex.Message);
                    Log.Error(ex.ToString());
                }
#endif
            }

            return;
        }
Example #38
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclareValueRuleBook <MudObject, bool>("silly?", "[Thing -> bool] : Determine if an object is silly.", "item");
            GlobalRules.Value <MudObject, bool>("silly?").Last.Do((thing) => false).Name("Things are serious by default rule.");

            GlobalRules.DeclareCheckRuleBook <MudObject, MudObject>("can silly?", "[Actor, Target] : Can the actor make the target silly?", "actor", "item");

            GlobalRules.Check <MudObject, MudObject>("can silly?").First
            .When((actor, target) => !(target is Actor))
            .Do((actor, target) =>
            {
                MudObject.SendMessage(actor, "That just sounds silly.");
                return(CheckResult.Disallow);
            })
            .Name("Can only silly actors rule.");

            GlobalRules.Check <MudObject, MudObject>("can silly?")
            .Do((actor, target) => MudObject.CheckIsVisibleTo(actor, target))
            .Name("Silly target must be visible.");

            GlobalRules.Check <MudObject, MudObject>("can silly?")
            .When((actor, target) => GlobalRules.ConsiderValueRule <bool>("silly?", target))
            .Do((actor, target) =>
            {
                MudObject.SendMessage(actor, "^<the0> is already silly.", target);
                return(CheckResult.Disallow);
            })
            .Name("Can't silly if already silly rule.");

            GlobalRules.Check <MudObject, MudObject>("can silly?")
            .Last
            .Do((actor, target) => CheckResult.Allow)
            .Name("Let the silliness ensue rule.");

            GlobalRules.DeclarePerformRuleBook <MudObject, MudObject>("silly", "[Actor, Target] : Apply silly status to the target.", "actor", "item");

            GlobalRules.Perform <MudObject, MudObject>("silly")
            .Do((actor, target) =>
            {
                MudObject.SendExternalMessage(actor, "^<the0> applies extra silly to <the1>.", actor, target);
                MudObject.SendMessage(actor, "You apply extra silly to <the0>.", target);

                var ruleID  = Guid.NewGuid();
                var counter = 100;

                target.Nouns.Add("silly");

                target.Value <MudObject, bool>("silly?").Do((thing) => true).ID(ruleID.ToString())
                .Name("Silly things are silly rule.");

                target.Value <MudObject, MudObject, String, String>("printed name")
                .Do((viewer, thing, article) =>
                {
                    return("silly " + thing.Short);
                })
                .Name("Silly things have silly names rule.")
                .ID(ruleID.ToString());

                GlobalRules.Perform("heartbeat")
                .Do(() =>
                {
                    counter -= 1;
                    if (counter <= 0)
                    {
                        MudObject.SendExternalMessage(target, "^<the0> is serious now.", target);
                        target.Nouns.Remove("silly");
                        target.Rules.DeleteAll(ruleID.ToString());
                        GlobalRules.DeleteRule("heartbeat", ruleID.ToString());
                    }
                    return(PerformResult.Continue);
                })
                .ID(ruleID.ToString())
                .Name("Countdown to seriousness rule.");

                return(PerformResult.Continue);
            })
            .Name("Apply sillyness rule.");

            GlobalRules.DeclareCheckRuleBook <MudObject>("can dance?", "[Actor] : Can the actor dance?", "actor");

            GlobalRules.Check <MudObject>("can dance?")
            .When(actor => !GlobalRules.ConsiderValueRule <bool>("silly?", actor))
            .Do(actor =>
            {
                MudObject.SendMessage(actor, "You don't feel silly enough for that.");
                return(CheckResult.Disallow);
            })
            .Name("Your friends don't dance rule.");

            GlobalRules.Check <MudObject>("can dance?")
            .Last
            .Do(actor => CheckResult.Allow)
            .Name("You can dance if you want to rule.");

            GlobalRules.DeclarePerformRuleBook <MudObject>("dance", "[Actor] : Perform a silly dance.", "actor");

            GlobalRules.Perform <MudObject>("dance")
            .Do(actor =>
            {
                MudObject.SendExternalMessage(actor, "^<the0> does a very silly dance.", actor);
                MudObject.SendMessage(actor, "You do a very silly dance.");
                return(PerformResult.Continue);
            })
            .Name("They aren't no friends of mine rule.");
        }
        public HttpResponseMessage Validate(List <DecisionRuleRequest> contracts)
        {
            var responses = new RuleEngine().ExecuteRuleParllel(contracts);

            return(Request.CreateResponse(responses));
        }
Example #40
0
 public ClipsEngine()
 {
     m_oRuleEngine   = new RuleEngine();
     m_stInferResult = new Result();
     m_stInferResult.Init();
 }
Example #41
0
        static void Main(string[] args)
        {
            // Rule creation for Person class and Club class
            var rule = RuleEngine.CreateRule <Person, Club>()
                       // if person's age is greater than 18
                       .If <Person>(p => p.Age).GreaterThan(18)
                       // and if club is open
                       .AndIf <Club>(c => c.IsOpen).IsTrue()
                       // then person can go to club
                       .Then <Person, Club>(p => p.GoToClub);

            //printing out the rule
            Console.WriteLine("--[rules]-------------------------------");
            Console.WriteLine(rule);
            Console.WriteLine("----------------------------------------");
            Console.WriteLine();

            //a list of people
            var people = new List <Person>
            {
                new Person {
                    Name = "Anas", Age = 15
                },
                new Person {
                    Name = "Ahmed", Age = 31
                },
                new Person {
                    Name = "Sameh", Age = 54
                },
                new Person {
                    Name = "Janna", Age = 9
                }
            };

            //the club
            var club = new Club
            {
                Name   = "The Club",
                IsOpen = true
            };

            //checking the rulw for every person in the list and the club
            people.ForEach(person =>
            {
                //printing out the person and the club
                Console.WriteLine($"--[person {people.IndexOf(person) + 1}]----------------------------");
                Console.WriteLine(person);
                Console.WriteLine(club);

                // checking if person and club match the rule
                var match = rule.Match(person, club);

                // printing out the match result
                Console.WriteLine(match);

                // executing the action if the person and club match the rule
                match.Execute();

                Console.WriteLine("----------------------------------------");
                Console.WriteLine();
            });
        }
Example #42
0
        public void InterpretationIndex(RuleEngine env, ProAi.Clips.DataObject obj)
        {
            Interpretation oInterpret = new Interpretation(env.UserFunctionManager.RtnString(1));

            m_stInferResult.lstInInterpretation.Add(oInterpret);
        }
Example #43
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            GlobalRules.DeclarePerformRuleBook <MudObject, String>("stats", "[Actor, Type] : Display engine stats.");

            GlobalRules.DeclarePerformRuleBook <MudObject>("enumerate-stats", "[Actor] : Display stats options.");
        }
Example #44
0
        private void SetValues(string opcServerUrl, string eventId, BaseTagValueWrapper valuesWrapper)
        {
            BaseTagValue[] values = valuesWrapper.Values;
            using (UserContextHolder.Register(new SystemUserContext()))
            {
                Folder configFolder = EntityCache <OPCServerFolderBehaviorData> .GetCache().AllEntities.FirstOrDefault(s => s.Url == opcServerUrl)?.GetEntity() as Folder;

                if (configFolder == null)
                {
                    return;
                }

                Array.ForEach(values, tagValue => { LOG.Debug($"Value Change: {tagValue.Path} - {TagValueUtils.GetObjectValueFromTag(tagValue)}"); });

                // put values in last cache
                foreach (var v in values)
                {
                    string       key = eventId + "|" + v.Path;
                    BaseTagValue priorValue;
                    OPCEngine.mostRecentValues.TryGetValue(key, out priorValue);

                    OPCEngine.mostRecentValues[key] = v;

                    if (priorValue == null)
                    {
                        OPCEngine.priorValues[key] = v;
                    }
                    else
                    {
                        OPCEngine.priorValues[key] = priorValue;
                    }
                }

                OPCEvent opcEvent = opcEventOrm.Fetch(eventId);
                if (opcEvent == null || opcEvent.Disabled)
                {
                    return;
                }

                bool runIt = false;
                // see if this event is interested in this change
                foreach (var v in opcEvent.EventValues)
                {
                    if (values.FirstOrDefault(changedValue => changedValue.Path == v.PathToValue) != null)
                    {
                        runIt = true;
                        break;
                    }
                }

                if (runIt)
                {
                    try
                    {
                        List <DataPair> inputs = new List <DataPair>();

                        foreach (var v in opcEvent.EventValues)
                        {
                            string       key   = eventId + "|" + v.PathToValue;
                            BaseTagValue value = null;

                            OPCEngine.mostRecentValues.TryGetValue(key, out value);

                            inputs.Add(new DataPair(v.Name, value));

                            BaseTagValue priorvalue = null;

                            OPCEngine.priorValues.TryGetValue(key, out priorvalue);

                            inputs.Add(new DataPair("Last " + v.Name, priorvalue));
                        }

                        inputs.Add(new DataPair("LastWorkflowRun", opcEvent.LastRun));

                        // check rule to see if it matches
                        var ruleResult = RuleEngine.RunRule(opcEvent.Rule, inputs.ToArray());

                        if (ruleResult != null && ruleResult is bool)
                        {
                            if (((bool)ruleResult) == true)
                            {
                                new Log("OPC").Error("Value Changed And Rule Returned True - running flow");
                                FlowEngine.Start(FlowEngine.LoadFlowByID(opcEvent.Flow, false, true),
                                                 new FlowStateData(inputs.ToArray()));
                            }
                            else
                            {
                                new Log("OPC").Error("Value Changed But Rule Returned False");
                            }
                        }
                        else
                        {
                            new Log("OPC").Error("Value Changed But Rule Returned False");
                        }
                    }
                    catch (Exception except)
                    {
                        new Log("OPC").Error(except, "Error running flow from event");
                    }
                }
            }
        }
Example #45
0
 public static void AtStartup(RuleEngine GlobalRules)
 {
     ProscriptionList = new ProscriptionList("proscriptions.txt");
 }
 public RuleEngineTests()
 {
     _ruleEngine = new RuleEngine();
 }
Example #47
0
File: Take.cs Project: SinaC/RMUD
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("you take", "You take <the0>.");
            Core.StandardMessage("they take", "^<the0> takes <the1>.");
            Core.StandardMessage("cant take people", "You can't take people.");
            Core.StandardMessage("cant take portals", "You can't take portals.");
            Core.StandardMessage("cant take scenery", "That's a terrible idea.");

            GlobalRules.DeclareCheckRuleBook <MudObject, MudObject>("can take?", "[Actor, Item] : Can the actor take the item?", "actor", "item");
            GlobalRules.DeclarePerformRuleBook <MudObject, MudObject>("take", "[Actor, Item] : Handle the actor taking the item.", "actor", "item");

            GlobalRules.Check <MudObject, MudObject>("can take?")
            .Do((actor, item) => MudObject.CheckIsVisibleTo(actor, item))
            .Name("Item must be visible to take rule.");

            GlobalRules.Check <MudObject, MudObject>("can take?")
            .When((actor, item) => actor is Container && (actor as Container).Contains(item, RelativeLocations.Held))
            .Do((actor, item) =>
            {
                MudObject.SendMessage(actor, "@already have that");
                return(CheckResult.Disallow);
            })
            .Name("Can't take what you're already holding rule.");

            GlobalRules.Check <MudObject, MudObject>("can take?")
            .Last
            .Do((a, t) => CheckResult.Allow)
            .Name("Default allow taking rule.");

            GlobalRules.Perform <MudObject, MudObject>("take")
            .Do((actor, target) =>
            {
                MudObject.SendMessage(actor, "@you take", target);
                MudObject.SendExternalMessage(actor, "@they take", actor, target);
                MudObject.Move(target, actor);
                return(PerformResult.Continue);
            })
            .Name("Default handle taken rule.");

            GlobalRules.Check <MudObject, MudObject>("can take?")
            .First
            .When((actor, thing) => thing is Actor)
            .Do((actor, thing) =>
            {
                MudObject.SendMessage(actor, "@cant take people");
                return(CheckResult.Disallow);
            })
            .Name("Can't take people rule.");

            GlobalRules.Check <MudObject, MudObject>("can take?")
            .First
            .When((actor, thing) => thing.GetPropertyOrDefault <bool>("portal?", false))
            .Do((actor, thing) =>
            {
                MudObject.SendMessage(actor, "@cant take portal");
                return(CheckResult.Disallow);
            });

            GlobalRules.Check <MudObject, MudObject>("can take?")
            .First
            .When((actor, thing) => thing.GetBooleanProperty("scenery?"))
            .Do((actor, thing) =>
            {
                MudObject.SendMessage(actor, "@cant take scenery");
                return(CheckResult.Disallow);
            })
            .Name("Can't take scenery rule.");
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.AntibioticList);
            // Create your application here
            antibioticPrescription = FindViewById <Button>(Resource.Id.antibioticPrescriptionButton);               //Antibiotic Prescription button
            patientInformation     = FindViewById <Button>(Resource.Id.patientInformationButton);                   //Patient Information button
            searchAntibiotic       = FindViewById <Button>(Resource.Id.searchAntibioticButton);                     //Search Antibiotic button
            label   = FindViewById <TextView>(Resource.Id.antibioticListTitleText);
            logout  = FindViewById <Button>(Resource.Id.logout);
            user    = FindViewById <TextView>(Resource.Id.currentUser);
            patient = FindViewById <TextView>(Resource.Id.currentPatient);


            label.SetBackgroundColor(Android.Graphics.Color.DarkGray);
            logout.SetBackgroundColor(Android.Graphics.Color.DarkCyan);
            patientInformation.SetBackgroundColor(Android.Graphics.Color.Transparent);
            antibioticPrescription.SetBackgroundColor(Android.Graphics.Color.DarkRed);
            searchAntibiotic.SetBackgroundColor(Android.Graphics.Color.Transparent);
            user.Text = "Doctor: " + Session.user.username;
            if (Session.selectedPatient == null)
            {
                patient.Text = "Patient: Not Selected";
            }
            else
            {
                patient.Text = "Patient: " + Session.selectedPatient.name;
            }


            //if Patient Information button is clicked, move to PList activity
            patientInformation.Click += delegate
            {
                StartActivity(typeof(PatientList));
            };

            //if Search Antibiotic button is clicked, move to AntibioticSearch activity
            searchAntibiotic.Click += delegate
            {
                StartActivity(typeof(AntibioticSearch));
            };
            logout.Click += delegate
            {
                StartActivity(typeof(MainActivity));
                //clear user below
                // [add later]
            };
            //if Antibiotic Prescription button is clicked, move to AntibioticPrescription activity
            antibioticPrescription.Click += delegate
            {
                StartActivity(typeof(AntibioticPrescription));
            };


            RuleEngine re = new RuleEngine();
            string     a  = re.determineAntibiotic(Session.selectedArea.name);

            char[]   delim          = { ',' };
            ListView antibioticList = FindViewById <ListView>(Resource.Id.antibioticListView);

            string[] ab = a.Split(delim);
            antibitoics = new List <string>();
            foreach (string s in ab)
            {
                antibitoics.Add(s);
            }
            var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItemSingleChoice, antibitoics);

            antibioticList.Adapter    = adapter;
            antibioticList.ItemClick += lista_ItemClicked;
        }
Example #49
0
        public AssemblyBuilder DoProcess(
            Object typeLib,
            string asmFilename,
            TypeLibImporterFlags flags,
            ITypeLibImporterNotifySink notifySink,
            byte[] publicKey,
            StrongNameKeyPair keyPair,
            string asmNamespace,
            Version asmVersion,
            bool isVersion2,
            bool isPreserveSig,
            string ruleSetFileName)
        {
            m_resolver = notifySink;

            TypeLib tlb = new TypeLib((TypeLibTypes.Interop.ITypeLib)typeLib);

            if (asmNamespace == null)
            {
                asmNamespace = tlb.GetDocumentation();

                string fileName = System.IO.Path.GetFileNameWithoutExtension(asmFilename);
                if (fileName != asmNamespace)
                {
                    asmNamespace = fileName;
                }

                //
                // Support for GUID_ManagedName (for namespace)
                //
                string customManagedNamespace = tlb.GetCustData(CustomAttributeGuids.GUID_ManagedName) as string;
                if (customManagedNamespace != null)
                {
                    customManagedNamespace = customManagedNamespace.Trim();
                    if (customManagedNamespace.ToUpper().EndsWith(".DLL"))
                    {
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
                    }
                    else if (customManagedNamespace.ToUpper().EndsWith(".EXE"))
                    {
                        customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
                    }

                    asmNamespace = customManagedNamespace;
                }
            }

            //
            // Check for GUID_ExportedFromComPlus
            //
            object value = tlb.GetCustData(CustomAttributeGuids.GUID_ExportedFromComPlus);

            if (value != null)
            {
                // Make this a critical failure, instead of returning null which will be ignored.
                throw new TlbImpGeneralException(Resource.FormatString("Err_CircularImport", asmNamespace), ErrorCode.Err_CircularImport);
            }

            string strModuleName = asmFilename;

            if (asmFilename.Contains("\\"))
            {
                int nIndex;
                for (nIndex = strModuleName.Length; strModuleName[nIndex - 1] != '\\'; --nIndex)
                {
                    ;
                }
                strModuleName = strModuleName.Substring(nIndex);
            }

            // If the version information was not specified, then retrieve it from the typelib.
            if (asmVersion == null)
            {
                using (TypeLibAttr attr = tlb.GetLibAttr())
                {
                    asmVersion = new Version(attr.wMajorVerNum, attr.wMinorVerNum, 0, 0);
                }
            }

            // Assembly name should not have .DLL
            // while module name must contain the .DLL
            string strAsmName = String.Copy(strModuleName);

            if (strAsmName.EndsWith(".DLL", StringComparison.InvariantCultureIgnoreCase))
            {
                strAsmName = strAsmName.Substring(0, strAsmName.Length - 4);
            }

            AssemblyName assemblyName = new AssemblyName();

            assemblyName.Name = strAsmName;
            assemblyName.SetPublicKey(publicKey);
            assemblyName.Version = asmVersion;
            assemblyName.KeyPair = keyPair;

            m_assemblyBuilder = CreateAssemblyBuilder(assemblyName, tlb, flags);

            m_moduleBuilder = CreateModuleBuilder(m_assemblyBuilder, strModuleName);

            // Add a listener for the reflection load only resolve events.
            AppDomain           currentDomain     = Thread.GetDomain();
            ResolveEventHandler asmResolveHandler = new ResolveEventHandler(ReflectionOnlyResolveAsmEvent);

            currentDomain.ReflectionOnlyAssemblyResolve += asmResolveHandler;

            ConverterSettings settings;

            settings.m_isGenerateClassInterfaces = true;
            settings.m_namespace     = asmNamespace;
            settings.m_flags         = flags;
            settings.m_isVersion2    = isVersion2;
            settings.m_isPreserveSig = isPreserveSig;
            RuleEngine.InitRuleEngine(new TlbImpActionManager(),
                                      new TlbImpCategoryManager(),
                                      new TlbImpConditionManager(),
                                      new TlbImpOperatorManager());
            if (ruleSetFileName != null)
            {
                try
                {
                    RuleFileParser parser = new RuleFileParser(ruleSetFileName);
                    settings.m_ruleSet = parser.Parse();
                }
                catch (Exception ex)
                {
                    Output.WriteWarning(Resource.FormatString("Wrn_LoadRuleFileFailed",
                                                              ruleSetFileName, ex.Message),
                                        WarningCode.Wrn_LoadRuleFileFailed);
                    settings.m_ruleSet = null;
                }
            }
            else
            {
                settings.m_ruleSet = null;
            }

            m_converterInfo = new ConverterInfo(m_moduleBuilder, tlb, m_resolver, settings);

            //
            // Generate class interfaces
            // NOTE:
            // We have to create class interface ahead of time because of the need to convert default interfaces to
            // class interfafces. However, this creates another problem that the event interface is always named first
            // before the other interfaces, because we need to create the type builder for the event interface first
            // so that we can create a class interface that implement it. But in the previous version of TlbImp,
            // it doesn't have to do that because it can directly create a typeref with the class interface name,
            // without actually creating anything like the TypeBuilder. The result is that the name would be different
            // with interop assemblies generated by old tlbimp in this case.
            // Given the nature of reflection API, this cannot be easily workarounded unless we switch to metadata APIs.
            // I believe this is acceptable because this only happens when:
            // 1. People decide to migrate newer .NET framework
            // 2. The event interface name conflicts with a normal interface
            //
            // In this case the problem can be easily fixed with a global refactoring, so I wouldn't worry about that
            //
            if (m_converterInfo.GenerateClassInterfaces)
            {
                CreateClassInterfaces();
            }

            //
            // Generate the remaining types except coclass
            // Because during creating coclass, we require every type, including all the referenced type to be created
            // This is a restriction of reflection API that when you override a method in parent interface, the method info
            // is needed so the type must be already created and loaded
            //
            List <TypeInfo> coclassList = new List <TypeInfo>();
            int             nCount      = tlb.GetTypeInfoCount();

            for (int n = 0; n < nCount; ++n)
            {
                TypeInfo type = null;
                try
                {
                    type = tlb.GetTypeInfo(n);
                    string strType = type.GetDocumentation();

                    TypeInfo typeToProcess;
                    TypeAttr attrToProcess;

                    using (TypeAttr attr = type.GetTypeAttr())
                    {
                        TypeLibTypes.Interop.TYPEKIND kind = attr.typekind;
                        if (kind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS)
                        {
                            ConvCommon.ResolveAlias(type, attr.tdescAlias, out typeToProcess, out attrToProcess);
                            if (attrToProcess.typekind == TypeLibTypes.Interop.TYPEKIND.TKIND_ALIAS)
                            {
                                continue;
                            }
                            else
                            {
                                // We need to duplicate the definition of the user defined type in the name of the alias
                                kind          = attrToProcess.typekind;
                                typeToProcess = type;
                                attrToProcess = attr;
                            }
                        }
                        else
                        {
                            typeToProcess = type;
                            attrToProcess = attr;
                        }

                        switch (kind)
                        {
                        // Process coclass later because of reflection API requirements
                        case TypeLibTypes.Interop.TYPEKIND.TKIND_COCLASS:
                            coclassList.Add(typeToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_ENUM:
                            m_converterInfo.GetEnum(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_DISPATCH:
                        case TypeLibTypes.Interop.TYPEKIND.TKIND_INTERFACE:
                            m_converterInfo.GetInterface(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_MODULE:
                            m_converterInfo.GetModule(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_RECORD:
                            m_converterInfo.GetStruct(typeToProcess, attrToProcess);
                            break;

                        case TypeLibTypes.Interop.TYPEKIND.TKIND_UNION:
                            m_converterInfo.GetUnion(typeToProcess, attrToProcess);
                            break;
                        }

                        m_converterInfo.ReportEvent(
                            MessageCode.Msg_TypeInfoImported,
                            Resource.FormatString("Msg_TypeInfoImported", typeToProcess.GetDocumentation()));
                    }
                }
                catch (ReflectionTypeLoadException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpResolveRefFailWrapperException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TlbImpGeneralException)
                {
                    throw; // Fatal failure. Throw
                }
                catch (TypeLoadException)
                {
                    throw; // TypeLoadException is critical. Throw.
                }
                catch (Exception)
                {
                }
            }

            // Process coclass after processing all the other types
            foreach (TypeInfo type in coclassList)
            {
                using (TypeAttr attr = type.GetTypeAttr())
                {
                    try
                    {
                        m_converterInfo.GetCoClass(type, attr);
                    }
                    catch (ReflectionTypeLoadException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpResolveRefFailWrapperException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TlbImpGeneralException)
                    {
                        throw; // Fatal failure. Throw
                    }
                    catch (TypeLoadException)
                    {
                        throw; // TypeLoadException is critical. Throw.
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            //
            // Build an array of EventItfInfo & generate event provider / event sink helpers
            //

            Event.TCEAdapterGenerator eventAdapterGenerator = new Event.TCEAdapterGenerator();
            List <Event.EventItfInfo> eventItfList          = new List <Event.EventItfInfo>();

            foreach (IConvBase symbol in m_converterInfo.GetAllConvBase)
            {
                IConvInterface convInterface = symbol as IConvInterface;
                if (convInterface != null)
                {
                    if (convInterface.EventInterface != null)
                    {
                        Debug.Assert(convInterface.EventInterface is ConvEventInterfaceLocal);
                        ConvEventInterfaceLocal local = convInterface.EventInterface as ConvEventInterfaceLocal;

                        Type eventInterfaceType = convInterface.EventInterface.ManagedType;

                        // Build EventItfInfo and add to the list
                        Type               sourceInterfaceType = convInterface.ManagedType;
                        string             sourceInterfaceName = sourceInterfaceType.FullName;
                        Event.EventItfInfo eventItfInfo        = new Event.EventItfInfo(
                            eventInterfaceType.FullName,
                            sourceInterfaceName,
                            local.EventProviderName,
                            eventInterfaceType,
                            convInterface.ManagedType);
                        eventItfList.Add(eventItfInfo);
                    }
                }
            }

            eventAdapterGenerator.Process(m_moduleBuilder, eventItfList);

            return(m_assemblyBuilder);
        }
Example #50
0
        protected void DefineType(ConverterInfo info, TypeInfo typeInfo, bool dealWithAlias)
        {
            m_info     = info;
            m_typeInfo = typeInfo;

            if (dealWithAlias)
            {
                m_nonAliasedTypeInfo = ConvCommon.GetAlias(typeInfo);
            }
            else
            {
                m_nonAliasedTypeInfo = typeInfo;
            }

            try
            {
                OnDefineType();

                //
                // Emit SuppressUnmanagedCodeSecurityAttribute for /unsafe switch
                //
                if ((m_info.Settings.m_flags & TypeLibImporterFlags.UnsafeInterfaces) != 0)
                {
                    if (ConvType != ConvType.ClassInterface && ConvType != ConvType.EventInterface)
                    {
                        m_typeBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForSuppressUnmanagedCodeSecurity());
                    }
                }

                // Rule Engine AddAttributeAction
                if (m_info.Settings.m_ruleSet != null)
                {
                    ICategory           category = TypeCategory.GetInstance();
                    TypeInfoMatchTarget target   = null;
                    using (TypeAttr attr = m_typeInfo.GetTypeAttr())
                    {
                        TypeLibTypes.Interop.TYPEKIND kind = attr.typekind;
                        target = new TypeInfoMatchTarget(m_typeInfo.GetContainingTypeLib(), m_typeInfo, kind);
                    }
                    AbstractActionManager actionManager     = RuleEngine.GetActionManager();
                    List <Rule>           addAttributeRules = m_info.Settings.m_ruleSet.GetRule(
                        category, AddAttributeActionDef.GetInstance(), target);
                    foreach (Rule rule in addAttributeRules)
                    {
                        AddAttributeAction addAttributeAction = rule.Action as AddAttributeAction;
                        ConstructorInfo    attributeCtor;
                        byte[]             blob;
                        bool success = true;
                        if (addAttributeAction.GetCustomAttribute(out attributeCtor, out blob))
                        {
                            try
                            {
                                m_typeBuilder.SetCustomAttribute(attributeCtor, blob);
                            }
                            catch (Exception)
                            {
                                success = false;
                            }
                        }
                        else
                        {
                            success = false;
                        }
                        if (!success)
                        {
                            string name = m_typeInfo.GetDocumentation();
                            string msg  = Resource.FormatString("Wrn_AddCustomAttributeFailed",
                                                                addAttributeAction.TypeName, name);
                            m_info.ReportEvent(WarningCode.Wrn_AddCustomAttributeFailed, msg);
                        }
                    }
                }
            }
            catch (ReflectionTypeLoadException)
            {
                throw; // Fatal failure. Throw
            }
            catch (TlbImpResolveRefFailWrapperException)
            {
                throw; // Fatal failure. Throw
            }
            catch (TlbImpGeneralException)
            {
                throw; // Fatal failure. Throw
            }
            catch (Exception)
            {
                string name = String.Empty;
                if (m_typeInfo != null)
                {
                    try
                    {
                        name = m_typeInfo.GetDocumentation();
                    }
                    catch (Exception)
                    {
                    }
                }

                if (name != String.Empty)
                {
                    string msg = Resource.FormatString("Wrn_InvalidTypeInfo", name);
                    m_info.ReportEvent(WarningCode.Wrn_InvalidTypeInfo, msg);
                }
                else
                {
                    string msg = Resource.FormatString("Wrn_InvalidTypeInfo_Unnamed");
                    m_info.ReportEvent(WarningCode.Wrn_InvalidTypeInfo_Unnamed, msg);
                }

                // When failure, try to create the type anyway
                if (m_typeBuilder != null)
                {
                    m_type = m_typeBuilder.CreateType();
                }
            }
        }
Example #51
0
 public ProbabilisticMoralCell(CellState state, int x, int y, RuleEngine rules, int maxAge) : base(state, x, y, rules, maxAge)
 {
 }
Example #52
0
 public static void AtStartup(RuleEngine GlobalRules)
 {
 }
Example #53
0
 public AbsoluteMortalCell(CellState state, int x, int y, RuleEngine rules, int maxAge) : base(state, x, y, rules, maxAge)
 {
 }
Example #54
0
 public void OperateNumberFact(RuleEngine env, ProAi.Clips.DataObject obj)
 {
     OperateFact(env.UserFunctionManager.RtnString(1), env.UserFunctionManager.RtnDouble(2).ToString());
 }
Example #55
0
        public static void AtStartup(RuleEngine GlobalRules)
        {
            Core.StandardMessage("cant put relloc", "You can't put things <s0> that.");
            Core.StandardMessage("you put", "You put <the0> <s1> <the2>.");
            Core.StandardMessage("they put", "^<the0> puts <the1> <s2> <the3>.");

            GlobalRules.DeclareCheckRuleBook <MudObject, MudObject, MudObject, RelativeLocations>("can put?", "[Actor, Item, Container, Location] : Determine if the actor can put the item in or on or under the container.", "actor", "item", "container", "relloc");
            GlobalRules.DeclarePerformRuleBook <MudObject, MudObject, MudObject, RelativeLocations>("put", "[Actor, Item, Container, Location] : Handle an actor putting the item in or on or under the container.", "actor", "item", "container", "relloc");

            GlobalRules.Check <MudObject, MudObject, MudObject, RelativeLocations>("can put?")
            .Last
            .Do((a, b, c, d) => CheckResult.Allow)
            .Name("Allow putting as default rule.");

            GlobalRules.Check <MudObject, MudObject, MudObject, RelativeLocations>("can put?")
            .Do((actor, item, container, relloc) =>
            {
                if (!(container is Container))
                {
                    MudObject.SendMessage(actor, "@cant put relloc", Relloc.GetRelativeLocationName(relloc));
                    return(CheckResult.Disallow);
                }
                return(CheckResult.Continue);
            })
            .Name("Can't put things in things that aren't containers rule.");

            GlobalRules.Check <MudObject, MudObject, MudObject, RelativeLocations>("can put?")
            .Do((actor, item, container, relloc) =>
            {
                if (GlobalRules.ConsiderCheckRule("can drop?", actor, item) != CheckResult.Allow)
                {
                    return(CheckResult.Disallow);
                }
                return(CheckResult.Continue);
            })
            .Name("Putting is dropping rule.");

            GlobalRules.Perform <MudObject, MudObject, MudObject, RelativeLocations>("put")
            .Do((actor, item, container, relloc) =>
            {
                MudObject.SendMessage(actor, "@you put", item, Relloc.GetRelativeLocationName(relloc), container);
                MudObject.SendExternalMessage(actor, "@they put", actor, item, Relloc.GetRelativeLocationName(relloc), container);
                MudObject.Move(item, container, relloc);
                return(PerformResult.Continue);
            })
            .Name("Default putting things in things handler.");

            GlobalRules.Check <MudObject, MudObject, MudObject, RelativeLocations>("can put?")
            .Do((actor, item, container, relloc) =>
            {
                var c = container as Container;
                if (c == null || (c.LocationsSupported & relloc) != relloc)
                {
                    MudObject.SendMessage(actor, "@cant put relloc", Relloc.GetRelativeLocationName(relloc));
                    return(CheckResult.Disallow);
                }
                return(CheckResult.Continue);
            })
            .Name("Check supported locations before putting rule.");

            GlobalRules.Check <MudObject, MudObject, MudObject, RelativeLocations>("can put?")
            .Do((actor, item, container, relloc) =>
            {
                if (relloc == RelativeLocations.In && !container.GetBooleanProperty("open?"))
                {
                    MudObject.SendMessage(actor, "@is closed error", container);
                    return(CheckResult.Disallow);
                }

                return(CheckResult.Continue);
            })
            .Name("Can't put things in closed container rule.");

            GlobalRules.Check <MudObject, MudObject, MudObject, RelativeLocations>("can put?")
            .First
            .Do((actor, item, container, relloc) => MudObject.CheckIsVisibleTo(actor, container))
            .Name("Container must be visible rule.");

            GlobalRules.Check <MudObject, MudObject, MudObject, RelativeLocations>("can put?")
            .First
            .Do((actor, item, container, relloc) => MudObject.CheckIsHolding(actor, item))
            .Name("Must be holding item rule.");
        }
Example #56
0
 public void Recommendation(RuleEngine env, ProAi.Clips.DataObject obj)
 {
     m_stInferResult.Recommendations.Add(env.UserFunctionManager.RtnString(1));
     //m_stInferResult.lstInInterpretation[m_stInferResult.lstInInterpretation.Count - 1].lstRecomm.Add(env.UserFunctionManager.RtnString(1));
 }
Example #57
0
        public void Setup()
        {
            var mockIPgStageBuilder = new Mock <IPgStageBuilder>();
            //IRuleService ruleService,
            var mockICostStageRevisionService = new Mock <ICostStageRevisionService>();

            mockICostStageRevisionService.Setup(a => a.GetPreviousRevision(new Guid(PreviousStageId)))
            .ReturnsAsync(new CostStageRevision()
            {
                Name = "OriginalEstimate"
            });
            var mockIAgencyService  = new Mock <IAgencyService>();
            var mockIProjectService = new Mock <IProjectService>();
            var mockRuleBuilder     = new Mock <IVendorRuleBuilder>();
            var mockRuleService     = new Mock <IPluginRuleService>();
            var pgCostServiceMock   = new Mock <IPgCostService>();
            var efContext           = GetService <EFContext>();
            var currencyService     = new Mock <IPgCurrencyService>();

            _costLineItemServiceMock = new Mock <ICostLineItemService>();
            _costTemplateServiceMock = new Mock <ICostTemplateVersionService>();
            _permissionServiceMock   = new Mock <IPermissionService>();

            var ruleEngine  = new RuleEngine();
            var ruleService = new RuleService(
                new List <Lazy <IVendorRuleBuilder, PluginMetadata> >
            {
                new Lazy <IVendorRuleBuilder, PluginMetadata>(() => mockRuleBuilder.Object, new PluginMetadata {
                    BuType = BuType.Pg
                })
            },
                new List <Lazy <IPluginRuleService, PluginMetadata> >
            {
                new Lazy <IPluginRuleService, PluginMetadata>(() => mockRuleService.Object, new PluginMetadata {
                    BuType = BuType.Pg
                })
            },
                ruleEngine,
                efContext
                );

            _costNumberGeneratorServiceMock.Setup(x => x.Generate(It.IsAny <Guid>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>())).Returns(Task.FromResult(CostNumber));
            _pgLedgerMaterialCodeServiceMock = new Mock <IPgLedgerMaterialCodeService>();
            _pgPaymentServiceMock            = new Mock <IPgPaymentService>();
            _exchangeRateServiceMock         = new Mock <IExchangeRateService>();
            _pgTotalsBuilder = new PgCostSectionTotalsBuilder();

            CostBuilder = new PgCostBuilder(mockIPgStageBuilder.Object,
                                            ruleService,
                                            mockICostStageRevisionService.Object,
                                            mockIAgencyService.Object,
                                            mockIProjectService.Object,
                                            efContext,
                                            _costNumberGeneratorServiceMock.Object,
                                            currencyService.Object,
                                            _pgLedgerMaterialCodeServiceMock.Object,
                                            _costLineItemServiceMock.Object,
                                            _costTemplateServiceMock.Object,
                                            _permissionServiceMock.Object,
                                            pgCostServiceMock.Object,
                                            _pgTotalsBuilder,
                                            _pgPaymentServiceMock.Object,
                                            _exchangeRateServiceMock.Object
                                            );
        }