예제 #1
0
        public void ReturnsFalseForNullQuery()
        {
            using (var db = new Db()
            {
                new DbItem("page1"), new DbItem("page2")
            })
            {
                var page1 = db.GetItem("/sitecore/content/page1");

                var args = new GetLookupSourceItemsArgs()
                {
                    Item = page1
                };

                var context   = new GetLookupsourceItemsRuleContext(args);
                var condition = new QueryContainsTokenCondition <GetLookupsourceItemsRuleContext>()
                {
                    Token = "ItemField"
                };

                var ruleStack = new RuleStack();

                condition.Evaluate(context, ruleStack);

                ruleStack.Should().HaveCount(1);
                ruleStack.Pop().Should().Be(false);
            }
        }
        public void MatchesToken()
        {
            using (var db = new Db()
            {
                new DbItem("page1"), new DbItem("page2")
            })
            {
                var page1 = db.GetItem("/sitecore/content/page1");
                var page2 = db.GetItem("/sitecore/content/page2");

                var args = new GetLookupSourceItemsArgs()
                {
                    Item = page1, Source = "{Home}/page1"
                };

                var context   = new GetLookupsourceItemsRuleContext(args);
                var condition = new QueryContainsTokenCondition <GetLookupsourceItemsRuleContext>()
                {
                    Token = "Home"
                };

                var ruleStack = new RuleStack();

                condition.Evaluate(context, ruleStack);

                ruleStack.Should().HaveCount(1);
                ruleStack.Pop().Should().Be(true);
            }
        }
예제 #3
0
        public Expression <Func <SearchResultItem, bool> > GetPredicatesFromRules(IProviderSearchContext context, string rawRules, Database db)
        {
            Assert.ArgumentNotNull(db, nameof(db));

            var expression = PredicateBuilder.True <SearchResultItem>();

            Sitecore.ContentSearch.Rules.QueryableRuleFactory ruleFactory = new Sitecore.ContentSearch.Rules.QueryableRuleFactory();
            var rules = ruleFactory.ParseRules <Sitecore.ContentSearch.Rules.QueryableRuleContext <SearchResultItem> >(db, rawRules);

            if (!rules.Rules.Any())
            {
                return(null);
            }

            foreach (var rule in rules.Rules)
            {
                if (rule.Condition != null)
                {
                    var ruleContext = new Sitecore.ContentSearch.Rules.QueryableRuleContext <SearchResultItem>(context);
                    var stack       = new RuleStack();
                    rule.Condition.Evaluate(ruleContext, stack);
                    rule.Execute(ruleContext);
                    if (stack.Any())
                    {
                        expression = ruleContext.Where;
                    }
                }
            }

            return(expression);
        }
        public static string GenerateMetaTags()
        {
            StringBuilder sb         = new StringBuilder();
            RuleStack     stack      = new RuleStack();
            var           references = Sitecore.Context.Item.Visualization.GetRenderings(Sitecore.Context.Device, false);

            try
            {
                foreach (RenderingReference reference in references)
                {
                    ConditionalRenderingsRuleContext context = new ConditionalRenderingsRuleContext(references.ToList(), reference);
                    foreach (Rule <ConditionalRenderingsRuleContext> rule in reference.Settings.Rules.Rules)
                    {
                        rule.Condition.Evaluate(context, stack);
                        if ((stack.Count != 0) && (bool)stack.Pop() && rule.UniqueId != ID.Null)
                        {
                            sb.Append(",").Append(rule.Name);
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Warn("Problem aggregating rules for personalization context, metatag may be incorrect", e, e);
            }
            return(sb.Length > 0 ? $@"<meta name=""sitecorePersonalization"" content=""{sb.ToString(1, sb.Length - 1)}"">" : "");
        }
예제 #5
0
        static void ProcessSinglePatient(int id)
        {
            //DbMapper db = new DbMapper();

            LocalDb db = new LocalDb();

            Patient p = new Patient();

            p = db.GetPatientTSD(id);

            Console.WriteLine("Patient : {0}", p.ToString());

            Console.WriteLine("Patient result count: {0}", p.TSDataPoints.Count());



            RuleStack rs = new RuleStack();

            rs.Execute(p);
            Console.WriteLine("Age calc done: {3},Patient Age: {0},  Invalid Age Flag:{1}, Alive: {2}", p.Age, p.Status.FlagInvalidAge, p.Status.Alive, p.Status.FlagCalculatedAge);



            foreach (var n in p.Notifications)
            {
                Console.WriteLine("--> {0}: {1} |", n.TimeStamp, n.Message);
            }
            Console.WriteLine("--------------------------------------------------");
            // rules


            //write back to reporting
            //db.InsertPatientReport(p);
        }
    public void DoesUserAgentContainValueCondition(string userAgent, string containsUserAgentValue, bool expectedResult, Db database)
    {


      SetupDb(database);


      RuleContext ruleContext = new RuleContext();

      PoorMansDeviceDetectorCondition<RuleContext> customUserAgentCondition = new PoorMansDeviceDetectorCondition<RuleContext>()
      {
        OperatorId = Constants.StringOperations.Contains.ItemID.ToString(),
        Value = containsUserAgentValue,
        UserAgent = userAgent
      };

      var ruleStack = new RuleStack();

      // act
      customUserAgentCondition.Evaluate(ruleContext, ruleStack);

      // assert
      ruleStack.Should().HaveCount(1);

      object value = ruleStack.Pop();

      value.Should().Be(expectedResult);

    }
예제 #7
0
        public void MatchesTargetId()
        {
            var sourceRenderingId = ID.NewID;
            var targetRenderingId = ID.NewID;

            using (var db = new Db {
                new DbItem("rendering", targetRenderingId)
            })
            {
                var targetRenderingItem = db.GetItem(targetRenderingId);

                var context = new ReplaceRenderingRuleContext(new RenderingDefinition()
                {
                    ItemID = sourceRenderingId.ToString()
                }, targetRenderingItem, new DeviceDefinition());

                var condition = new TargetRenderingIsAnyOfCondition <ReplaceRenderingRuleContext>
                {
                    CompareRenderingItemIds = targetRenderingId.ToString()
                };

                var ruleStack = new RuleStack();

                condition.Evaluate(context, ruleStack);

                ruleStack.Should().HaveCount(1);
                ruleStack.Pop().Should().Be(true);
            }
        }
예제 #8
0
        public void FailsButDoesNotErrorWhenCompareIdNotSet()
        {
            var sourceRenderingId = ID.NewID;
            var targetRenderingId = ID.NewID;

            using (var db = new Db {
                new DbItem("rendering", targetRenderingId)
            })
            {
                var targetRenderingItem = db.GetItem(targetRenderingId);

                var context = new ReplaceRenderingRuleContext(new RenderingDefinition()
                {
                    ItemID = sourceRenderingId.ToString()
                }, targetRenderingItem, new DeviceDefinition());

                var condition = new TargetRenderingIsAnyOfCondition <ReplaceRenderingRuleContext>();

                var ruleStack = new RuleStack();

                condition.Evaluate(context, ruleStack);

                ruleStack.Should().HaveCount(1);
                ruleStack.Pop().Should().Be(false);
            }
        }
예제 #9
0
        /// <summary>
        /// runs the set of rules and checks for any matches, if it finds a match it will run the rule's associated action
        /// </summary>
        /// <param name="root">Item which holds the field</param>
        /// <param name="field">the rule field name</param>
        /// <param name="ruleContext"></param>
        /// <returns></returns>
        public static void RunRules <T>(this Item root, string field, T ruleContext)
            where T : RuleContext
        {
            foreach (Rule <T> rule in RuleFactory.GetRules <T>(new[] { root }, field).Rules)
            {
                if (rule.Condition != null)
                {
                    var stack = new RuleStack();
                    rule.Condition.Evaluate(ruleContext, stack);

                    if (ruleContext.IsAborted)
                    {
                        continue;
                    }
                    if ((stack.Count != 0) && ((bool)stack.Pop()))
                    {
                        rule.Execute(ruleContext);
                    }
                }
                else
                {
                    rule.Execute(ruleContext);
                }
            }
        }
        /// <summary>
        /// Gets the rules device.
        /// </summary>
        /// <param name="database">The database.</param>
        /// <returns>Resolved device</returns>
        private static DeviceItem GetRulesDevice(Database database)
        {
            DeviceItem[] all = database.Resources.Devices.GetAll();

            foreach (var device in all)
            {
                var ruleContext = new RuleContext();
                var rules       = RuleFactory.GetRules <RuleContext>(
                    device.InnerItem, "Conditions").Rules;
                foreach (Rule <RuleContext> rule in rules)
                {
                    if (rule.Condition != null)
                    {
                        var stack = new RuleStack();
                        rule.Condition.Evaluate(ruleContext, stack);
                        if (ruleContext.IsAborted)
                        {
                            continue;
                        }
                        if ((stack.Count != 0) && ((bool)stack.Pop()))
                        {
                            return(device);
                        }
                    }
                }
            }

            return(null);
        }
예제 #11
0
        private static DeviceItem ExecuteDeviceConditions()
        {
            var devices = Context.Database.Resources.Devices.GetAll();

            foreach (var device in devices)
            {
                var ruleContext = new RuleContext();

                foreach (var rule in RuleFactory.GetRules <RuleContext>(new[] { device.InnerItem }, "Rule").Rules)
                {
                    if (rule.Condition != null)
                    {
                        var stack = new RuleStack();
                        rule.Condition.Evaluate(ruleContext, stack);
                        if (ruleContext.IsAborted)
                        {
                            continue;
                        }
                        if ((stack.Count != 0) && ((bool)stack.Pop()))
                        {
                            return(device);
                        }
                    }
                }
            }

            return(null);
        }
예제 #12
0
        private void CheckForRulesMatch(Database db, string domain, string requestedUrl, string requestedPathAndQuery, HttpRequestArgs args)
        {
            // Loop through the pattern match items to find a match
            foreach (Item possibleRedirectRule in GetRedirects(db, domain, Constants.Templates.RedirectRule, Constants.Templates.VersionedRedirectRule, Sitecore.Configuration.Settings.GetSetting(Constants.Settings.QueryExactMatch)))
            {
                var ruleContext = new RuleContext();
                ruleContext.Parameters.Add("newUrl", requestedUrl);

                foreach (Rule <RuleContext> rule in RuleFactory.GetRules <RuleContext>((IEnumerable <Item>) new Item[1] {
                    possibleRedirectRule
                }, "Redirect Rule").Rules)
                {
                    if (rule.Condition != null)
                    {
                        RuleStack stack = new RuleStack();
                        rule.Condition.Evaluate(ruleContext, stack);
                        if (!ruleContext.IsAborted && (stack.Count != 0 && (bool)stack.Pop()))
                        {
                            foreach (var action in rule.Actions)
                            {
                                action.Apply(ruleContext);
                            }
                        }
                    }
                }

                if (ruleContext.Parameters["newUrl"] != null && ruleContext.Parameters["newUrl"].ToString() != string.Empty && ruleContext.Parameters["newUrl"].ToString() != requestedUrl)
                {
                    var responseStatus = GetResponseStatus(possibleRedirectRule);
                    // The query string will be in the URL already, so don't break it apart.
                    SendResponse(ruleContext.Parameters["newUrl"].ToString(), string.Empty, responseStatus, args);
                }
            }
        }
예제 #13
0
        public void DetectsItemFieldTokenWithoutFieldName()
        {
            using (var db = new Db()
            {
                new DbItem("page1"), new DbItem("page2")
            })
            {
                var page1 = db.GetItem("/sitecore/content/page1");

                var args = new GetLookupSourceItemsArgs()
                {
                    Item = page1, Source = "{ItemField:FullName}"
                };

                var context   = new GetLookupsourceItemsRuleContext(args);
                var condition = new QueryContainsTokenCondition <GetLookupsourceItemsRuleContext>()
                {
                    Token = "ItemField"
                };

                var ruleStack = new RuleStack();

                condition.Evaluate(context, ruleStack);

                ruleStack.Should().HaveCount(1);
                ruleStack.Pop().Should().Be(true);
            }
        }
        public TrackingField Evaluate(Item mapItem, Item contextItem)
        {
            var context = new RuleContext
            {
                Item = contextItem
            };

            foreach (Rule <RuleContext> rule in RuleFactory.GetRules <RuleContext>(new[] { mapItem }, Templates.RulesProfileMap.Fields.Rules.ToString()).Rules)
            {
                if (rule.Condition != null)
                {
                    var stack = new RuleStack();

                    rule.Condition.Evaluate(context, stack);

                    if (context.IsAborted)
                    {
                        continue;
                    }

                    if ((stack.Count != 0) && ((bool)stack.Pop()))
                    {
                        return(GetTrackingField(mapItem));
                    }
                }
            }

            return(null);
        }
예제 #15
0
        public override void Evaluate([CanBeNull] object parameter, [NotNull] RuleStack stack)
        {
            Assert.ArgumentNotNull(parameter, nameof(parameter));
            Assert.ArgumentNotNull(stack, nameof(stack));

            LeftOperand.Evaluate(parameter, stack);
            RightOperand.Evaluate(parameter, stack);
        }
예제 #16
0
        public override void Evaluate([CanBeNull] object parameter, [NotNull] RuleStack stack)
        {
            Assert.ArgumentNotNull(stack, nameof(stack));

            Operand.Evaluate(parameter, stack);

            var result = (bool)stack.Pop();

            stack.Push(!result);
        }
        protected virtual RuleCondition <T> GetCondition(T ruleContext, RuleStack stack)
        {
            var type = GetDataType(ruleContext);

            if (type == null)
            {
                return(null);
            }
            var condition = AdaptiveManager.Provider.GetRuleCondition <T>(type, this, ruleContext);

            return(condition);
        }
        public override void Evaluate(T ruleContext, RuleStack stack)
        {
            var condition = GetCondition(ruleContext, stack);

            if (condition == null)
            {
                stack.Push(false);
                return;
            }
            condition.UniqueId = this.UniqueId;
            condition.Evaluate(ruleContext, stack);
        }
예제 #19
0
        public static bool EvaluateSingleRule(Rule<RuleContext> rule, RuleContext ruleContext)
        {
            if (rule.Condition == null)
                return true;

            var stack = new RuleStack();
            rule.Condition.Evaluate(ruleContext, stack);

            if (ruleContext.IsAborted)
            {
                return false;
            }
            return (stack.Count != 0) && ((bool)stack.Pop());
        }
예제 #20
0
        public override void Evaluate(T ruleContext, RuleStack stack)
        {
            var predicate = GetPredicate(ruleContext);

            if (predicate == null)
            {
                this.ApplyFilter(ruleContext, (Expression <Func <IndexedContact, bool> >)(c => false));
                stack.Push(false);
                return;
            }

            this.ApplyFilter(ruleContext, predicate);
            stack.Push(true);
        }
예제 #21
0
        /// <summary>
        /// Gets the rules device.
        /// </summary>
        /// <param name="database">The database.</param>
        /// <returns>Resolved device</returns>
        private static DeviceItem GetRulesDevice(Database database)
        {
            const string defaultLanguageName = "en";

            var savedLanguage = Context.Language;

            if (savedLanguage.Name != defaultLanguageName)
            {
                Context.Language = LanguageManager.GetLanguage(defaultLanguageName);
            }
            DeviceItem[] all = database.Resources.Devices.GetAll();

            foreach (var device in all)
            {
                var ruleContext = new RuleContext();

                foreach (Rule <RuleContext> rule in RuleFactory.GetRules <RuleContext>(new[]
                {
                    device.InnerItem
                }, "Conditions").Rules)
                {
                    if (rule.Condition != null)
                    {
                        var stack = new RuleStack();
                        rule.Condition.Evaluate(ruleContext, stack);
                        if (ruleContext.IsAborted)
                        {
                            continue;
                        }
                        if ((stack.Count != 0) && ((bool)stack.Pop()))
                        {
                            if (savedLanguage.Name != defaultLanguageName)
                            {
                                Context.Language = savedLanguage;
                            }

                            return(device);
                        }
                    }
                }
            }

            if (savedLanguage.Name != defaultLanguageName)
            {
                Context.Language = savedLanguage;
            }

            return(null);
        }
        public static bool ValidateRule(RuleList<RuleContext> rules, Item ruleItem, Item checkItem)
        {
            var ruleContext = new RuleContext { Item = checkItem };
            var result = false;
            using (
                new LongRunningOperationWatcher(Settings.Profiling.RenderFieldThreshold, "Long running rule set: {0}",
                    new string[1]
                    {
                        ruleItem.Name ?? string.Empty
                    }))
            {
                foreach (var rule in rules.Rules)
                {
                    if (rule.Condition == null)
                        continue;

                    var stack = new RuleStack();

                    try
                    {
                        rule.Condition.Evaluate(ruleContext, stack);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(
                            string.Format("Evaluation of condition failed. Rule item ID: {0}, condition item ID: {1}",
                                rule.UniqueId != (ID)null ? rule.UniqueId.ToString() : "Unknown",
                                rule.Condition.UniqueId != ID.Null.ToString()
                                    ? rule.Condition.UniqueId
                                    : "Unknown"), ex, typeof(RuleProcessor));
                        ruleContext.Abort();
                    }

                    if (ruleContext.IsAborted)
                        break;

                    if (stack.Count != 0 && (bool)stack.Pop())
                        result = true;
                    else
                    {
                        result = false;
                        break;
                    }
                }
            }

            return result;
        }
예제 #23
0
        public override void Evaluate([CanBeNull] object parameter, [NotNull] RuleStack stack)
        {
            Assert.ArgumentNotNull(stack, nameof(stack));

            LeftOperand.Evaluate(parameter, stack);

            var left = (bool)stack.Pop();

            if (!left)
            {
                stack.Push(false);
                return;
            }

            RightOperand.Evaluate(parameter, stack);
        }
예제 #24
0
        private void Evaluate(XmlTextWriter output, Item item, XElement root, RuleList <RuleContext> ruleList)
        {
            var ruleContext = new RuleContext
            {
                Item = item
            };

            var index = 0;

            foreach (var rule in ruleList.Rules)
            {
                var ruleElement = root.Element(index);

                index++;

                output.WriteElementString("entry", string.Format("Evaluating rule {0} of {1}.", index, ruleList.Rules.Count()));

                if (rule.Condition == null)
                {
                    output.WriteElementString("entry", string.Format("    There are no conditions and the rule is skipped.", index));
                    continue;
                }

                output.WriteElementString("entry", "    Evaluating conditions");

                var stack             = new RuleStack();
                var conditionsElement = ruleElement.Element("conditions");

                Evaluate(output, rule.Condition, ruleContext, stack, item.Database, conditionsElement.Element(0));

                if (ruleContext.IsAborted)
                {
                    output.WriteElementString("entry", string.Format("    Evaluation is aborted by a condition.", index));
                    break;
                }

                var result = stack.Count != 0 && (bool)stack.Pop();

                output.WriteElementString("entry", string.Format("    The evaluation result is {0}.", result ? "True" : "False"));

                if (result)
                {
                    RenderActions(output, item, ruleElement, rule);
                }
            }
        }
예제 #25
0
        public virtual Item GetRulesBasedSnippetDataSource(Item rulesBasedSnippetSnippetItem, Item contextItem)
        {
            var rulesValue = rulesBasedSnippetSnippetItem[Templates.RulesBasedSnippetSnippet.Fields.SnippetRules];

            if (string.IsNullOrWhiteSpace(rulesValue))
            {
                return(null);
            }

            var commerceContextItem = siteContext.CurrentCatalogItem ?? contextItem;
            var rules       = RuleFactory.ParseRules <RuleContext>(contextItem.Database, XElement.Parse(rulesValue));
            var ruleContext = new RuleContext()
            {
                Item = commerceContextItem
            };

            if (rules.Rules.Any())
            {
                foreach (var rule in rules.Rules)
                {
                    if (rule.Condition != null)
                    {
                        var stack = new RuleStack();
                        rule.Condition.Evaluate(ruleContext, stack);

                        if (ruleContext.IsAborted)
                        {
                            continue;
                        }
                        if ((stack.Count != 0) && ((bool)stack.Pop()))
                        {
                            rule.Execute(ruleContext);
                            var action    = rule.Actions.FirstOrDefault();
                            var snippetId = action is SelectSnippet <RuleContext>?((SelectSnippet <RuleContext>)action)?.SnippetId : string.Empty;
                            return(!string.IsNullOrEmpty(snippetId) ? contextItem.Database.GetItem(ID.Parse(snippetId)) : null);
                        }
                    }
                    else
                    {
                        rule.Execute(ruleContext);
                    }
                }
            }

            return(null);
        }
예제 #26
0
        public static bool EvaluateSingleRule(Rule <RuleContext> rule, RuleContext ruleContext)
        {
            if (rule.Condition == null)
            {
                return(true);
            }

            var stack = new RuleStack();

            rule.Condition.Evaluate(ruleContext, stack);

            if (ruleContext.IsAborted)
            {
                return(false);
            }
            return((stack.Count != 0) && ((bool)stack.Pop()));
        }
예제 #27
0
        public static bool EvaluateConditions <T>(this Item root, string field, T ruleContext)
            where T : RuleContext
        {
            var stack = new RuleStack();

            foreach (Rule <T> rule in RuleFactory.GetRules <T>(new[] { root }, field).Rules)
            {
                if (rule.Condition != null)
                {
                    rule.Condition.Evaluate(ruleContext, stack);

                    if (ruleContext.IsAborted)
                    {
                        continue;
                    }
                }
            }
            return(stack.Count != 0 && (bool)stack.Pop());
        }
예제 #28
0
        public void StartTurn(Game game)
        {
            foreach (var card in PlayedCards)
            {
                if (card.Card is IDuration d)
                {
                    d.NumberOfTurnsActive++;
                    foreach (var ability in d.GetOnTurnStartAbilities(d.NumberOfTurnsActive))
                    {
                        RuleStack.Push(ability);
                    }
                }
            }
            NumberOfActions = 1;
            NumberOfBuys    = 1;
            MoneyPlayed     = 0;

            PlayStatus = HasActionInHand() ? PlayStatus.ActionPhase : PlayStatus.BuyPhase;
        }
예제 #29
0
        public static Expression <Func <SearchResultItem, bool> > ProcessQueryRules(IProviderSearchContext context, string queryFilter, SearchOperation operation)
        {
            var predicate = operation == SearchOperation.Or
                ? PredicateBuilder.False <SearchResultItem>()
                : PredicateBuilder.True <SearchResultItem>();

            var crawler = context.Index.Crawlers.FirstOrDefault(c => c is SitecoreItemCrawler);

            if (crawler == null)
            {
                return(predicate);
            }

            var database = ((SitecoreItemCrawler)crawler).Database;

            if (string.IsNullOrEmpty(database))
            {
                return(predicate);
            }

            var ruleFactory = new Sitecore.ContentSearch.Rules.QueryableRuleFactory();
            var rules       = ruleFactory.ParseRules <Sitecore.ContentSearch.Rules.QueryableRuleContext <SearchResultItem> >(Factory.GetDatabase(database), queryFilter);

            foreach (var rule in rules.Rules)
            {
                if (rule.Condition == null)
                {
                    continue;
                }

                var ruleContext = new Sitecore.ContentSearch.Rules.QueryableRuleContext <SearchResultItem>(context);
                var stack       = new RuleStack();
                rule.Condition.Evaluate(ruleContext, stack);
                rule.Execute(ruleContext);
                if (stack.Any())
                {
                    predicate = ruleContext.Where;
                }
            }

            return(predicate);
        }
예제 #30
0
        public bool Evaluate([CanBeNull] object ruleContext)
        {
            var c = Condition;

            if (c == null)
            {
                return(true);
            }

            var stack = new RuleStack();

            c.Evaluate(ruleContext, stack);

            if (stack.Count == 0)
            {
                return(false);
            }

            return((bool)stack.Pop());
        }
예제 #31
0
        ///<summary>
        /// runs the set of rules and checks for any matches, if it finds a match it will run the rule's associated action
        /// </summary>
        /// <param name="ruleContext">Rule context that holds log parameters</param>
        /// <returns></returns>
        public static void RunRules(LoggerRuleContext ruleContext)
        {
            using (new SecurityDisabler())
            {
                Item rootRulesFolder = webDb.GetItem(Constants.IDs.RulesRootFolderId);
                if (rootRulesFolder == null)
                {
                    return;
                }
                var rulesItems = rootRulesFolder.Children.Where(i => i.TemplateID.Equals(Constants.Templates.LoggingRule));
                if (!rulesItems.Any())
                {
                    return;
                }
                foreach (var ruleItem in rulesItems)
                {
                    foreach (Rule <LoggerRuleContext> rule in RuleFactory.GetRules <LoggerRuleContext>(new[] { ruleItem }, Constants.Fields.Rule).Rules)
                    {
                        ruleContext.ItemId = ruleItem.ID;
                        if (rule.Condition != null)
                        {
                            var stack = new RuleStack();
                            rule.Condition.Evaluate(ruleContext, stack);

                            if (ruleContext.IsAborted)
                            {
                                continue;
                            }
                            if ((stack.Count != 0) && ((bool)stack.Pop()))
                            {
                                rule.Execute(ruleContext);
                            }
                        }
                        else
                        {
                            rule.Execute(ruleContext);
                        }
                    }
                }
            }
        }
예제 #32
0
        //this may need to be updated for future triggered abilities
        //this only works for simple triggered abilities
        public void RunTriggeredAbilities(PlayerAction playerAction, Card card)
        {
            foreach (var triggeredAbility in TriggeredAbilities.ToList())
            {
                if (triggeredAbility.Trigger.IsMet(playerAction, card))
                {
                    if (triggeredAbility.TriggeredAbilityDurationType != TriggeredAbilityDurationType.Once)
                    {
                        triggeredAbility.Ability.Resolved = false;
                    }

                    RuleStack.Push(triggeredAbility.Ability);

                    //we may not need this since resolved abilities won't play 2 times anyway
//                    if (triggeredAbility.TriggeredAbilityDurationType == TriggeredAbilityDurationType.Once)
//                    {
//                        TriggeredAbilities.Remove(triggeredAbility);
//                    }
                }
            }
        }
예제 #33
0
        public void ExecCorrectlyDetectsChild(string parentPath, string childPath, bool expectedResult, string message)
        {
            using (var db = GetFakeDb())
            {
                var item    = db.GetItem(childPath);
                var root    = db.GetItem(parentPath);
                var context = new RuleContext {
                    Item = item
                };

                var condition = new IsDescendentOfCondition <RuleContext>
                {
                    PotentialParent = root
                };

                var ruleStack = new RuleStack();

                condition.Evaluate(context, ruleStack);

                ruleStack.Should().HaveCount(1);
                ruleStack.Pop().Should().Be(expectedResult, message);
            }
        }
        private bool SatisfiesConditions(RuleList<RuleContext> ruleList, RuleContext ruleContext)
        {
            foreach (Rule<RuleContext> rule in ruleList.Rules)
            {
                if (rule.Condition == null)
                    continue;

                RuleStack stack = new RuleStack();
                rule.Condition.Evaluate(ruleContext, stack);

                if (ruleContext.IsAborted)
                    continue;

                if (stack.Count == 0)
                    continue;

                if (!(bool)stack.Pop())
                    continue;

                return true;
            }

            return false;
        }
        private List<ActionResponse> GetActionResponses(Item rootItem, string selectedValue)
        {
            List<ActionResponse> actions = new List<ActionResponse>();

            if (rootItem != null)
            {
                Item[] fieldListWithSection = rootItem.Axes.GetDescendants();
                List<Item> allDescendants = new List<Item>();
                //Doing that in case of sections
                foreach (Item item in fieldListWithSection)
                {
                    allDescendants.AddRange(item.Children);
                }
                allDescendants.AddRange(fieldListWithSection);

                foreach (Item fieldItem in allDescendants)
                {

                    RuleContext ruleContext = new RuleContext();
                    IEnumerable<Rule<RuleContext>> rules = RuleFactory.GetRules<RuleContext>(new[] { fieldItem }, "Rules").Rules;

                    foreach (Rule<RuleContext> rule in rules)
                    {
                        // Adding selectedValue every time so condition gets value,
                        // also when AND-condition or OR-condition added by user in Rule Editor.
                        // Since AND-condition or OR-condition puts Custom Conditions in nesting object hierarchy
                        ruleContext.Parameters.Add("selectedValue", selectedValue);
                        RuleStack stack = new RuleStack();
                        rule.Condition.Evaluate(ruleContext, stack);

                        if (ruleContext.IsAborted)
                        {
                            continue;
                        }

                        string fieldClass = fieldItem.Name;
                        ControlType controlType = fieldItem.TemplateID == Constants.WffmSectionTemplateId ? ControlType.Section : ControlType.Field;

                        if (controlType == ControlType.Section)
                        {
                            Item firstCildItem = fieldItem.Children.FirstOrDefault();
                            if (firstCildItem != null)
                            {
                                fieldClass = firstCildItem.Name;
                            }
                        }

                        if (rule.Condition.GetType() == typeof(ConditionalHide<RuleContext>))
                        {
                            ConditionalHide<RuleContext> condHide = (ConditionalHide<RuleContext>)rule.Condition;
                            SessionUtil.SetSessionValue(condHide.SessionVariable, selectedValue);
                        }

                        var resultFromConditionExecution = (stack.Count != 0) && ((bool)stack.Pop());
                        actions.Add(new ActionResponse { ControlType = controlType, CssClassSelector = fieldClass.Replace(" ", "+"), HideControl = resultFromConditionExecution });
                        if (resultFromConditionExecution)
                        {
                            rule.Execute(ruleContext);
                        }
                    }
                }
            }
            return actions;
        }
        private void CheckForRulesMatch(Database db, string requestedUrl, string requestedPathAndQuery, HttpRequestArgs args)
        {
            // Loop through the pattern match items to find a match
            foreach (Item possibleRedirectRule in GetRedirects(db, Constants.Templates.RedirectRule, Constants.Templates.VersionedRedirectRule, Sitecore.Configuration.Settings.GetSetting(Constants.Settings.QueryExactMatch)))
            {
                var ruleContext = new RuleContext();
                ruleContext.Parameters.Add("newUrl", requestedUrl);

                foreach (Rule<RuleContext> rule in RuleFactory.GetRules<RuleContext>((IEnumerable<Item>)new Item[1] { possibleRedirectRule }, "Redirect Rule").Rules)
                {
                    if (rule.Condition != null)
                    {
                        RuleStack stack = new RuleStack();
                        rule.Condition.Evaluate(ruleContext, stack);
                        if (!ruleContext.IsAborted && (stack.Count != 0 && (bool)stack.Pop()))
                        {
                            foreach (var action in rule.Actions)
                            {
                                action.Apply(ruleContext);
                            }
                        }
                    }
                }

                if (ruleContext.Parameters["newUrl"] != null && ruleContext.Parameters["newUrl"].ToString() != string.Empty && ruleContext.Parameters["newUrl"].ToString() != requestedUrl)
                {
                   var responseStatus = GetResponseStatus(possibleRedirectRule);
                    // The query string will be in the URL already, so don't break it apart.
                    SendResponse(ruleContext.Parameters["newUrl"].ToString(), string.Empty, responseStatus, args);
                }
            }
        }
        /// <summary>
        /// Gets the rules device.
        /// </summary>
        /// <param name="database">The database.</param>
        /// <returns>Resolved device</returns>
        private static DeviceItem GetRulesDevice(Database database)
        {
            DeviceItem[] all = database.Resources.Devices.GetAll();

              foreach (var device in all)
              {
            var ruleContext = new RuleContext();

            foreach (Rule<RuleContext> rule in RuleFactory.GetRules<RuleContext>(new[]
            {
              device.InnerItem }, "Conditions").Rules)
            {
              if (rule.Condition != null)
              {
            var stack = new RuleStack();
            rule.Condition.Evaluate(ruleContext, stack);
            if (ruleContext.IsAborted)
            {
              continue;
            }
            if ((stack.Count != 0) && ((bool)stack.Pop()))
            {
              return device;
            }
              }
            }
              }

              return null;
        }
        /// <summary>
        /// Evaluates if rule is active.
        /// </summary>
        /// <param name="ruleItem">The rule item.</param>
        /// <param name="contextItem">The context item.</param>
        /// <returns></returns>
        private static bool RuleIsActive(Item ruleItem, Item contextItem)
        {
            var personaHelper = PersonaHelper.GetHelper();
            personaHelper.SetAnalyticsContext();

            foreach (Rule<ConditionalRenderingsRuleContext> rule in RuleFactory.GetRules<ConditionalRenderingsRuleContext>(new[] { ruleItem }, "Rule").Rules)
            {
                if (rule.Condition != null)
                {
                    var ruleContext = new ConditionalRenderingsRuleContext(new List<RenderingReference>(), new RenderingReference(new Control())) { Item = contextItem };
                    var stack = new RuleStack();
                    rule.Condition.Evaluate(ruleContext, stack);
                    if (ruleContext.IsAborted)
                    {
                        return false;
                    }

                    bool ruleOutcome = false;
                    if ((stack.Count != 0) && ((bool)stack.Pop()))
                    {
                        ruleOutcome = true;
                    }
                    if (rule.Condition.GetType() == typeof(VisitorIdentificationCondition<ConditionalRenderingsRuleContext>))
                    {
                        ruleOutcome = !ruleOutcome;
                    }
                    return ruleOutcome;
                }
            }
            return false;
        }
        /// <summary>
        /// Gets the rules device.
        /// </summary>
        /// <param name="database">The database.</param>
        /// <returns>Resolved device</returns>
        private static DeviceItem GetRulesDevice(Database database)
        {
            const string defaultLanguageName = "en";

              var savedLanguage = Context.Language;
              if (savedLanguage.Name != defaultLanguageName)
              Context.Language = LanguageManager.GetLanguage(defaultLanguageName);
            DeviceItem[] all = database.Resources.Devices.GetAll();

              foreach (var device in all)
              {
            var ruleContext = new RuleContext();

            foreach (Rule<RuleContext> rule in RuleFactory.GetRules<RuleContext>(new[]
            {
              device.InnerItem }, "Conditions").Rules)
            {
              if (rule.Condition != null)
              {
            var stack = new RuleStack();
            rule.Condition.Evaluate(ruleContext, stack);
            if (ruleContext.IsAborted)
            {
              continue;
            }
            if ((stack.Count != 0) && ((bool)stack.Pop()))
            {
              if (savedLanguage.Name != defaultLanguageName)
                    Context.Language = savedLanguage;

              return device;
            }
              }
            }
              }

              if (savedLanguage.Name != defaultLanguageName)
            Context.Language = savedLanguage;

              return null;
        }