Esempio n. 1
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);
            }
        }
Esempio n. 2
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);
                }
            }
        }
        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);
        }
Esempio n. 4
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);
        }
        /// <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);
        }
Esempio n. 6
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);
            }
        }
    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);

    }
Esempio n. 8
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);
            }
        }
Esempio n. 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);
                }
            }
        }
        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)}"">" : "");
        }
        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);
            }
        }
Esempio n. 12
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);
            }
        }
Esempio n. 13
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);
        }
Esempio n. 14
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());
        }
Esempio n. 15
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;
        }
Esempio n. 17
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);
        }
Esempio n. 18
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);
        }
Esempio n. 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()));
        }
Esempio n. 20
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);
                }
            }
        }
Esempio n. 21
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());
        }
Esempio n. 22
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());
        }
Esempio n. 23
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);
                        }
                    }
                }
            }
        }
Esempio n. 24
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;
        }
Esempio n. 26
0
        // Run Forest Run!
        protected virtual void RunIgnoreTrackingExceptions(T ruleContext, bool stopOnFirstMatching, out int executedRulesCount)
        {
            Assert.ArgumentNotNull(ruleContext, "ruleContext");
            executedRulesCount = 0;
            if (this.Count == 0)
            {
                return;
            }
            using (new LongRunningOperationWatcher(Settings.Profiling.RenderFieldThreshold, "Long running rule set: {0}", new string[]
            {
                this.Name ?? string.Empty
            }))
            {
                foreach (Rule <T> current in this.Rules)
                {
                    if (current.Condition != null)
                    {
                        RuleStack ruleStack = new RuleStack();
                        try
                        {
                            PersonalizationRuleList <T> .RaiseConditionEventHandler(this.Evaluating, this, ruleContext, current);

                            current.Condition.Evaluate(ruleContext, ruleStack);
                            PersonalizationRuleList <T> .RaiseConditionEventHandler(this.Evaluated, this, ruleContext, current);
                        }
                        // only skip when there is a tracker like operation
                        catch (InvalidOperationException invalidOperation)
                        {
                            string arg  = (current.Name != null) ? current.Name.ToString() : "Unknown";
                            string arg2 = (current.Condition.UniqueId != null) ? current.Condition.UniqueId.ToString() : "Unknown";

                            if (invalidOperation.Message.Contains("Tracker"))
                            {
                                Log.Warn(String.Format("Tracker.Current not available - rule with name: {0} skipped, condtion item ID: {1}", arg, arg2), invalidOperation, this);
                            }
                            else
                            {
                                Log.Error(string.Format("Evaluation of condition failed. Rule item ID: {0}, condition item ID: {1}", arg, arg2), invalidOperation, this);
                                ruleContext.Abort();
                            }
                        }
                        catch (Exception exception)
                        {
                            string arg  = (current.Name != null) ? current.Name.ToString() : "Unknown";
                            string arg2 = (current.Condition.UniqueId != null) ? current.Condition.UniqueId.ToString() : "Unknown";

                            Log.Error(string.Format("Evaluation of condition failed. Rule item ID: {0}, condition item ID: {1}", arg, arg2), exception, this);
                            ruleContext.Abort();
                        }
                        if (ruleContext.IsAborted)
                        {
                            break;
                        }
                        if (ruleStack.Count != 0)
                        {
                            bool flag = (bool)ruleStack.Pop();
                            if (!flag || ruleContext.SkipRule)
                            {
                                ruleContext.SkipRule = false;
                            }
                            else
                            {
                                foreach (RuleAction <T> current2 in current.Actions)
                                {
                                    try
                                    {
                                        current2.Apply(ruleContext);
                                        PersonalizationRuleList <T> .RaiseActionEventHandler(this.Applied, this, ruleContext, current2);
                                    }
                                    catch (Exception exception2)
                                    {
                                        string arg3 = (current.Name != null) ? current.Name : "Unknown";
                                        string arg4 = (current2.UniqueId != null) ? current2.UniqueId.ToString() : "Unknown";
                                        Log.Error(string.Format("Execution of action failed. Rule item ID: {0}, action item ID: {1}", arg3, arg4), exception2, this);
                                        ruleContext.Abort();
                                    }
                                    if (ruleContext.IsAborted)
                                    {
                                        return;
                                    }
                                }
                                executedRulesCount++;
                                if (stopOnFirstMatching)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <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;
        }
Esempio n. 28
0
        private void Evaluate(XmlTextWriter output, RuleCondition <RuleContext> condition, RuleContext ruleContext, RuleStack stack, Database database, XElement element)
        {
            var andCondition = condition as AndCondition <RuleContext>;

            if (andCondition != null)
            {
                Evaluate(output, andCondition.LeftOperand, ruleContext, stack, database, element.Element(0));
                if (!(bool)stack.Pop())
                {
                    stack.Push(false);
                }
                else
                {
                    Evaluate(output, andCondition.RightOperand, ruleContext, stack, database, element.Element(1));
                }

                return;
            }

            var orCondition = condition as OrCondition <RuleContext>;

            if (orCondition != null)
            {
                Evaluate(output, orCondition.LeftOperand, ruleContext, stack, database, element.Element(0));
                if ((bool)stack.Pop())
                {
                    stack.Push(true);
                }
                else
                {
                    Evaluate(output, orCondition.RightOperand, ruleContext, stack, database, element.Element(1));
                }

                return;
            }

            var notCondition = condition as NotCondition <RuleContext>;

            if (notCondition != null)
            {
                Evaluate(output, notCondition.Operand, ruleContext, stack, database, element.Element(0));

                var flag = (bool)stack.Pop();
                stack.Push(!flag);

                return;
            }

            condition.Evaluate(ruleContext, stack);

            var text = condition.GetType().Name;

            var conditionItem = database.GetItem(element.GetAttributeValue("id"));

            if (conditionItem != null)
            {
                text = Expand(database, conditionItem["Text"], element);
            }

            var result = stack.Peek();

            output.WriteElementString("entry", string.Format("        Condition \"{0}\" returned \"{1}\".", text, result.ToString()));
        }
        protected override void Run(T ruleContext, bool stopOnFirstMatching, out int executedRulesCount)
        {
            Assert.ArgumentNotNull(ruleContext, "ruleContext");
            executedRulesCount = 0;
            if (Count == 0)
            {
                return;
            }

            using (new LongRunningOperationWatcher(Settings.Profiling.RenderFieldThreshold, "Long running rule set: {0}", new string[1] {
                this.Name ?? string.Empty
            }))
            {
                foreach (var rule in 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}",
                                !ID.IsNullOrEmpty(rule.UniqueId) ? rule.UniqueId.ToString() : "Unknown",
                                !string.IsNullOrWhiteSpace(rule.Condition.UniqueId) ? rule.Condition.UniqueId : "Unknown"),
                            ex, this);
                        ruleContext.Abort();
                    }

                    if (ruleContext.IsAborted)
                    {
                        break;
                    }

                    if (stack.Count == 0)
                    {
                        continue;
                    }

                    if (!(bool)stack.Pop() || ruleContext.SkipRule)
                    {
                        ruleContext.SkipRule = false;
                        continue;
                    }

                    foreach (var action in rule.Actions)
                    {
                        try
                        {
                            action.Apply(ruleContext);
                        }
                        catch (Exception ex)
                        {
                            Log.Error(
                                string.Format(
                                    "Execution of action failed. Rule item ID: {0}, action item ID: {1}",
                                    !ID.IsNullOrEmpty(rule.UniqueId) ? rule.UniqueId.ToString() : "Unknown",
                                    !string.IsNullOrWhiteSpace(action.UniqueId) ? action.UniqueId : "Unknown"),
                                ex, this);
                            ruleContext.Abort();
                        }

                        if (ruleContext.IsAborted)
                        {
                            return;
                        }

                        if (ruleContext.StopProcessingThisRuleset)
                        {
                            ruleContext.StopProcessingThisRuleset = false;
                            return;
                        }
                        if (ruleContext.StopProcessingThisRule)
                        {
                            ruleContext.StopProcessingThisRule = false;
                            break;
                        }
                    }
                    ++executedRulesCount;

                    if (stopOnFirstMatching)
                    {
                        break;
                    }
                }
            }
        }
        /// <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;
        }
        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);
                }
            }
        }
        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;
        }