private bool[,] GetRulePipelineResults() { bool[,] results = new bool[_board.Size, _board.Size]; CellRule rule = new CellRule(); rule.PipelineObject = rule.GetType(); rule.PipelineObjectNamespaceName = true.GetType().FullName; var processes = new RuleFactory<IPipelineObject>().GetProcessors(rule).ToList(); //cast to avoid multiple enumerations for (int y = 0; y < _board.Size; y++) { for (int x = 0; x < _board.Size; x++) { rule.Initialize(_board, x, y); var result = Pipeline<IPipelineObject>.Execute(processes, rule) as CellRule; if (result == null) { throw new Exception("The pipeline being executed for cell rules must return a cell rule object."); } results[x, y] = result.Status; } } return results; }
public bool RuleIsSatisfied() { RuleFactory ruleFactory = new RuleFactory(); IRuleStrategy ruleStrategy = ruleFactory.GetRuleStrategy(_rule); Context ruleContext = new Context(ruleStrategy); if (ruleContext.Execute(_rule, _liveEventsThatFitIntoRule.ToList())) { ClearProcessedEvents(); return(true); } return(false); }
public void Tests(TestCase test) { JsonSchema schema = SchemaReader.ReadSchema(test.SchemaText, TestUtil.TestFilePath); var target = new Validator(schema); Result[] results = target.Validate(test.InstanceText, TestUtil.TestFilePath); results.Length.Should().Be(test.ExpectedMessages.Length); List <string> actualMessages = results.Select( r => r.FormatForVisualStudio( RuleFactory.GetRuleFromRuleId(r.RuleId))).ToList(); actualMessages.Should().ContainInOrder(test.ExpectedMessages); }
public async Task ProcessRuleAsyncPass() { await PopulateTodoItems(TotalItems); var request = CreateRequest(); var response = CreateResponse(); var rule = new TodoItemNotFoundRule(Context); await rule.ProcessAsync(request, response, RuleFactory.CreateEmptyListOfUpdateRules()); Assert.AreEqual(RuleStatusType.Passed, rule.Status); Assert.IsTrue(rule.ContinueProcessing); Assert.AreEqual(0, response.Notifications.Count); }
public IRule CopyRule(int ruleIndex, Strategy target) { IRule rule = rules[ruleIndex]; IRule newRule = RuleFactory.GetInstance().CreateRuleInstance(rule.GetType()); //we do not initialize rule here coz when str is added to rep, its //initialize method is called which calles init of its rules //newRule.Initialize(this); rule.CopyState(newRule); target.AddRule(newRule); return(newRule); }
private string FormatSchemaErrors(string path, IEnumerable <Result> errors) { string firstMessageLine = string.Format(CultureInfo.CurrentCulture, MultitoolResources.ErrorInvalidSarifLogFile, path); var sb = new StringBuilder(firstMessageLine); sb.AppendLine(); foreach (Result error in errors) { sb.AppendLine(error.FormatForVisualStudio(RuleFactory.GetRuleFromRuleId(error.RuleId))); } return(sb.ToString()); }
public static bool EvaluateRules(string strRules, Item contextItem, bool failEmpty = false) { if (string.IsNullOrEmpty(strRules) || strRules.Length < 70) { return(!failEmpty); } // hacking the rules xml var rules = RuleFactory.ParseRules <RuleContext>(Factory.GetDatabase(ApplicationSettings.RulesDb), strRules); var ruleContext = new RuleContext { Item = contextItem }; return(!rules.Rules.Any() || rules.Rules.Any(rule => rule.Evaluate(ruleContext))); }
public void PropertyRuleShouldBeConstructable() { // Arrange var data = new PropertyRuleData { Name = Guid.NewGuid().ToString() }; var sut = new RuleFactory(); // Act var actual = sut.Construct(data); // Assert Assert.NotNull(actual); }
/// <summary> /// Invoke global device resolution rules. /// </summary> /// <returns>True if a global device resolution rule applied.</returns> protected bool InvokeGlobalRules() { Sitecore.Data.Items.Item ruleRoot = Sitecore.Context.Database.GetItem( "/sitecore/system/Settings/Rules/Determine Context Device/Rules"); if (ruleRoot == null) { return(false); } // TODO: use descendants instead of children // for each possible global rule definition item foreach (Sitecore.Data.Items.Item child in ruleRoot.Children) { string ruleXml = child["Rule"]; if (String.IsNullOrEmpty(ruleXml) || child["Disabled"] == "1") { continue; } // parse the rule XML RuleList <RuleContext> rules = new RuleList <RuleContext>(); rules.Name = child.Paths.Path; RuleList <RuleContext> parsed = RuleFactory.ParseRules <RuleContext>( Sitecore.Context.Database, ruleXml); rules.AddRange(parsed.Rules); if (rules == null || rules.Count < 1) { continue; } // invoke the rule RuleContext ruleContext = new RuleContext(); ruleContext.Item = Sitecore.Context.Item; rules.Run(ruleContext); // rule applied if (ruleContext.IsAborted) { return(true); } } return(false); }
/// <summary> Gets global conditional rules </summary> /// <param name="item">item to proceed</param> /// <returns>rulles collection</returns> protected RuleList <ConditionalRenderingsRuleContext> GetGlobalRules(Item item) { Assert.ArgumentNotNull(item, "item"); RuleList <ConditionalRenderingsRuleContext> rules = null; using (new SecurityDisabler()) { Item parentItem = item.Database.GetItem(ItemIDs.ConditionalRenderingsGlobalRules); if (parentItem != null) { rules = RuleFactory.GetRules <ConditionalRenderingsRuleContext>(parentItem, "Rule"); } } return(rules); }
public void CreateRule_GivenNullRuleDataModel_ThrowsArgumentNullException() { // Arrange RuleDataModel ruleDataModel = null; IContentSerializationProvider <ContentType> contentSerializationProvider = Mock.Of <IContentSerializationProvider <ContentType> >(); RuleFactory <ContentType, ConditionType> ruleFactory = new RuleFactory <ContentType, ConditionType>(contentSerializationProvider); // Act ArgumentNullException argumentNullException = Assert.Throws <ArgumentNullException>(() => ruleFactory.CreateRule(ruleDataModel)); // Assert argumentNullException.Should().NotBeNull(); argumentNullException.ParamName.Should().Be(nameof(ruleDataModel)); }
public async Task ProcessRuleAsyncPass(string scenario, object expectedItem) { var expectedTodoItemEntity = (TodoItemEntity)expectedItem; var request = CreateRequest((int)expectedTodoItemEntity.Id); var response = CreateResponse(); var rule = new ResponseRule(); await rule.ProcessAsync(request, response, RuleFactory.CreateEmptyListOfSaveRules()); VerifyTodoItem.AssertTodoItem(expectedTodoItemEntity, response.Item); Assert.AreEqual(RuleStatusType.Passed, rule.Status); Assert.IsTrue(rule.ContinueProcessing); Assert.AreEqual(0, response.Notifications.Count); }
private void Execute(XmlTextWriter output, string databaseName, string itemId, string rules) { var database = Factory.GetDatabase(databaseName); if (database == null) { output.WriteElementString("entry", "Database not found."); return; } var item = database.GetItem(itemId); if (item == null) { output.WriteElementString("entry", "Source item not found."); return; } XElement root; try { var doc = XDocument.Parse(rules); root = doc.Root; } catch { output.WriteElementString("entry", "Rules Xml is not welformed."); return; } if (root == null) { output.WriteElementString("entry", "There are no rules defined."); return; } var ruleList = RuleFactory.ParseRules <RuleContext>(database, rules); if (!ruleList.Rules.Any()) { output.WriteElementString("entry", "There are no rules defined."); return; } Evaluate(output, item, root, ruleList); }
/// <summary> /// Overrides the base class implementation and adds execution of rules to determine allowed renderings. /// </summary> protected override List <Sitecore.Data.Items.Item> GetRenderings(Sitecore.Data.Items.Item placeholderItem, out bool allowedControlsSpecified) { // Get the initial list of renderings from the base implementation. var list = base.GetRenderings(placeholderItem, out allowedControlsSpecified); // Get the rules from the placeholder item. string rulesXml = placeholderItem[Constants.RulesFieldId]; if (string.IsNullOrWhiteSpace(rulesXml)) { return(list); } // Parse the rules. var parsedRules = RuleFactory.ParseRules <PlaceholderSettingsRuleContext>(placeholderItem.Database, rulesXml); // Construct the context. PlaceholderSettingsRuleContext context = new PlaceholderSettingsRuleContext(); context.Item = placeholderItem; context.AllowedRenderingItems = list; context.DeviceId = DeviceId; context.PlaceholderKey = PlaceholderKey; context.ContentDatabase = ContentDatabase; context.LayoutDefinition = LayoutDefinition; // Execute the rules. RuleList <PlaceholderSettingsRuleContext> rules = new RuleList <PlaceholderSettingsRuleContext>(); rules.Name = placeholderItem.Paths.Path; rules.AddRange(parsedRules.Rules); rules.Run(context); // Did the rules specify if the selection tree should be displayed? if (context.DisplaySelectionTree.HasValue) { allowedControlsSpecified = !context.DisplaySelectionTree.Value; } // If not, only display the tree if there are no allowed renderings. else { allowedControlsSpecified = context.AllowedRenderingItems.Count > 0; } // Return the list. return(context.AllowedRenderingItems); }
public async Task ProcessRuleAsyncNotSameId() { var request = CreateRequest(); request.Id = NotSameId; var response = CreateResponse(); var rule = new TodoItemNotSameIdRule(); await rule.ProcessAsync(request, response, RuleFactory.CreateEmptyListOfUpdateRules()); Assert.IsInstanceOfType(rule, typeof(BaseRule <UpdateTodoItemRequest, Response <TodoItemEntity> >)); Assert.AreEqual(RuleStatusType.Failed, rule.Status); Assert.IsFalse(rule.ContinueProcessing); VerifyNotification.AssertResponseNotifications(CreateExpectedResponse(), response); }
protected override void BeginProcessing() { Item currentItem = InputObject.BaseObject() as Item; string ruleDatabaseName = RuleDatabase; if (!string.IsNullOrEmpty(ruleDatabaseName)) { ruleDatabaseName = currentItem != null ? currentItem.Database.Name : ApplicationSettings.RulesDb; } Database ruleDatabase = Factory.GetDatabase(ruleDatabaseName); rules = RuleFactory.ParseRules <RuleContext>(ruleDatabase, Rule); }
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); }
private static Rule CreateRandomCrossRule() // Generate a random Cross Rule. { int rndNum = RandomHolder.Instance.Next(3); if (rndNum == 0) // Create a Cross( Overlay, Overlay) rule. { return(RuleFactory.createCrossRule(IndicatorFactory.getRandomPriceOverlayIndicator(), IndicatorFactory.getRandomPriceOverlayIndicator())); } else if (rndNum == 1) // Create a Cross( Overlay, PriceArray) rule. { return(RuleFactory.createCrossRule(IndicatorFactory.getRandomPriceOverlayIndicator(), IndicatorFactory.createRandomABPriceArray())); } else // Create a Cross( PriceArray, Overlay) rule. { return(RuleFactory.createCrossRule(IndicatorFactory.createRandomABPriceArray(), IndicatorFactory.getRandomPriceOverlayIndicator())); } }
private void InitializeControl() { var contextMenuHandler = new ContextMenuHandler(); var displayHandler = new DisplayHandler(); var downloadLogger = logger.CloneFor($"{nameof(DownloadHandler)} {Id}"); var downloadHandler = new DownloadHandler(appConfig, settings, downloadLogger); var keyboardHandler = new KeyboardHandler(); var lifeSpanHandler = new LifeSpanHandler(); var requestFilter = new RequestFilter(); var requestLogger = logger.CloneFor($"{nameof(RequestHandler)} {Id}"); var requestHandler = new RequestHandler(appConfig, settings.Filter, requestFilter, requestLogger, text); displayHandler.FaviconChanged += DisplayHandler_FaviconChanged; displayHandler.ProgressChanged += DisplayHandler_ProgressChanged; downloadHandler.ConfigurationDownloadRequested += DownloadHandler_ConfigurationDownloadRequested; keyboardHandler.ReloadRequested += ReloadRequested; keyboardHandler.ZoomInRequested += ZoomInRequested; keyboardHandler.ZoomOutRequested += ZoomOutRequested; keyboardHandler.ZoomResetRequested += ZoomResetRequested; lifeSpanHandler.PopupRequested += LifeSpanHandler_PopupRequested; requestHandler.RequestBlocked += RequestHandler_RequestBlocked; if (settings.Filter.ProcessContentRequests || settings.Filter.ProcessMainRequests) { var factory = new RuleFactory(); foreach (var settings in settings.Filter.Rules) { var rule = factory.CreateRule(settings.Type); rule.Initialize(settings); requestFilter.Load(rule); } logger.Debug($"Initialized request filter with {settings.Filter.Rules.Count} rule(s)."); } control = new BrowserControl(contextMenuHandler, displayHandler, downloadHandler, keyboardHandler, lifeSpanHandler, requestHandler, url); control.AddressChanged += Control_AddressChanged; control.LoadingStateChanged += Control_LoadingStateChanged; control.TitleChanged += Control_TitleChanged; control.Initialize(); logger.Debug("Initialized browser control."); }
private static Task <int> Main(string[] args) { var rootCommand = new RootCommand { new Option <FileInfo>("--config", "Path to a configuration that defines how validation will occur.") { IsRequired = true, AllowMultipleArgumentsPerToken = false, Argument = new Argument <FileInfo> { Arity = ArgumentArity.ExactlyOne } }.ExistingOnly(), new Option <FileInfo[]>("--project", "Path to a Visual Studio solution or project files that should be validated. Can be specified multiple times") { IsRequired = true, AllowMultipleArgumentsPerToken = true, Argument = new Argument <FileInfo[]> { Arity = ArgumentArity.OneOrMore } }.ExistingOnly(), new Option <bool>("--verbose", description: "Verbose output of progress", getDefaultValue: () => false), new Option <bool>("--silent", description: "Don't output anything on stdout", getDefaultValue: () => false) }; rootCommand.Description = "Validator for Visual Studio projects"; rootCommand.Handler = CommandHandler.Create( async(FileInfo config, FileInfo[] project, bool verbose, bool silent, IConsole console) => { var logger = new Output(console, silent, verbose); var rulesFactory = new RuleFactory(); var rulesLoader = new RulesLoader(rulesFactory, logger); var rules = await rulesLoader.LoadRules(config).ToListAsync(); var projectLoader = new ProjectLoader(logger); var validator = new Validator(rules, projectLoader, logger); return(await validator.Validate(project)); }); return(rootCommand.InvokeAsync(args)); }
public static bool EvaluateRulesForView(string strRules, RuleContext ruleContext, bool failNonSpecific = false) { if (string.IsNullOrEmpty(strRules) || strRules.Length < 70) { return(!failNonSpecific); } var viewName = ruleContext.Parameters["ViewName"]; if (failNonSpecific && (!"ValidViewName".IsSubstringOf(strRules) || !$"\"{viewName}\"".IsSubstringOf(strRules))) { return(false); } var rules = RuleFactory.ParseRules <RuleContext>(Factory.GetDatabase(ApplicationSettings.RulesDb), strRules); return(!rules.Rules.Any() || rules.Rules.Any(rule => rule.Evaluate(ruleContext))); }
public static string Render(string markdown) { var rules = RuleFactory.CreateAllRules(); var sourceTags = rules.Select(rule => rule.SourceTag); var renderedLines = new List <string>(); var parser = new MainParser(sourceTags); var render = new Render(rules); var escapedText = EscapeSpecialSymbols(markdown); foreach (var line in Regex.Split(escapedText, Environment.NewLine)) { var tokens = parser.ParseLine(line); var renderedLine = render.RenderLine(line, tokens); renderedLines.Add(renderedLine); } return(string.Join(Environment.NewLine, renderedLines)); }
public void ExecuteNotEqualRuleOnFlatNullablePropertyPassed() { var rule = new RuleFactory().Create(RuleOperator.NotEqual); rule.LeftNode = "BirthDate"; rule.RightNode = null; rule.ValidationMessage = "Nullable Date must not be empty or null"; var person = new Person { Name = "Faenor" }; var engine = new RuleEngine(); var compiledRule = engine.CompileRules <Person>(rule); var result = engine.Validate(person, compiledRule); Assert.AreEqual(false, result.Passed); Assert.AreEqual(0, result.ValidationMessageSummary.Length); }
public void ExecuteEqualRuleOnFlatPropertyPassed() { var rule = new RuleFactory().Create(RuleOperator.Equal); rule.LeftNode = "Name"; rule.RightNode = "Faenor"; rule.ValidationMessage = "Name should be equal to Faenor."; var person = new Person { Name = "Faenor" }; var engine = new RuleEngine(); var compiledRule = engine.CompileRules <Person>(rule); var result = engine.Validate(person, compiledRule); Assert.AreEqual(true, result.Passed); Assert.AreEqual(0, result.ValidationMessageSummary.Length); }
private static IEnumerable <object[]> SetupProcessRuleAsyncSkipped() { var rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); yield return(new object[] { "Rules: 0 of 3 required rules, 0 MockRule", rules }); rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); rules.Add(RuleFactory.CreateMockSaveRule()); yield return(new object[] { "Rules: 0 of 3 required rules, 1 MockRule", rules }); rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); rules.Add(RuleFactory.CreateMockSaveRule()); rules.Add(RuleFactory.CreatePassedRule <RequestRule>()); yield return(new object[] { "Rules: 1 of 3 required rules (RequestRule), 1 MockRule", rules }); rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); rules.Add(RuleFactory.CreateMockSaveRule()); rules.Add(RuleFactory.CreatePassedRule <ResponseRule>()); yield return(new object[] { "Rules: 1 of 3 required rules (ResponseRule), 1 MockRule", rules }); rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); rules.Add(RuleFactory.CreateMockSaveRule()); rules.Add(RuleFactory.CreatePassedRule <TodoItemPriorityRule>()); yield return(new object[] { "Rules: 1 of 3 required rules (TodoItemPriorityRule), 1 MockRule", rules }); rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); rules.Add(RuleFactory.CreateMockSaveRule()); rules.Add(RuleFactory.CreatePassedRule <RequestRule>()); rules.Add(RuleFactory.CreatePassedRule <ResponseRule>()); yield return(new object[] { "Rules: 2 of 3 required rules (RequestRule, ResponseRule), 1 MockRule", rules }); rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); rules.Add(RuleFactory.CreateMockSaveRule()); rules.Add(RuleFactory.CreatePassedRule <RequestRule>()); rules.Add(RuleFactory.CreatePassedRule <TodoItemPriorityRule>()); yield return(new object[] { "Rules: 2 of 3 required rules (RequestRule, TodoItemPriorityRule), 1 MockRule", rules }); rules = RuleFactory.CreateEmptyListOfSaveRules().ToList(); rules.Add(RuleFactory.CreateMockSaveRule()); rules.Add(RuleFactory.CreatePassedRule <ResponseRule>()); rules.Add(RuleFactory.CreatePassedRule <TodoItemPriorityRule>()); yield return(new object[] { "Rules: 2 of 3 required rules (ResponseRule, TodoItemPriorityRule), 1 MockRule", rules }); }
protected bool ApplyDeviceRules() { // for each device foreach (DeviceItem device in Sitecore.Context.Database.Resources.Devices.GetAll()) { // for each field of the device foreach (Field field in device.InnerItem.Fields) { // ignore empty fields and fields of type other than rules. if (field.TypeKey != "rules" || String.IsNullOrEmpty(field.Value)) { continue; } // parse the rule definition XML in the field. RuleList <SetContextDeviceRuleContext> rules = new RuleList <SetContextDeviceRuleContext>(); rules.Name = field.Item.Paths.Path; RuleList <SetContextDeviceRuleContext> parsed = RuleFactory.ParseRules <SetContextDeviceRuleContext>(field.Database, field.Value); rules.AddRange(parsed.Rules); if (rules == null || rules.Count < 1) { continue; } // invoke the rule. SetContextDeviceRuleContext ruleContext = new SetContextDeviceRuleContext( device); rules.Run(ruleContext); // rule applied. if (ruleContext.IsAborted) { return(true); } } } return(false); }
/// <summary> /// Returns rules of a landing workflow action. /// </summary> /// <param name="processorItem"> /// The processor item. /// </param> /// <returns> /// Returns RuleList of landing workflow. /// </returns> protected RuleList <WorkflowRuleContext> BuildRuleList(ProcessorItem processorItem) { Assert.ArgumentNotNull(processorItem, "processorItem"); Item actionItem = processorItem.InnerItem; RuleList <WorkflowRuleContext> ruleList = new RuleList <WorkflowRuleContext>(); if (!string.IsNullOrEmpty(actionItem["Rule"])) { ruleList.AddRange(RuleFactory.GetRules <WorkflowRuleContext>(actionItem.Fields["Rule"]).Rules); } if (!string.IsNullOrEmpty(actionItem["Rules"])) { Item[] rules = ((MultilistField)actionItem.Fields["Rules"]).GetItems(); ruleList.AddRange(RuleFactory.GetRules <WorkflowRuleContext>(rules, "Rule").Rules); } return(ruleList); }
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()); }
private PlaceholderSettingsRuleContext EvaluateRules(Item placeholder) { PlaceholderSettingsRuleContext ruleContext = new PlaceholderSettingsRuleContext(); ruleContext.Item = _contextItem; foreach (Rule <PlaceholderSettingsRuleContext> rule in RuleFactory.GetRules <PlaceholderSettingsRuleContext>(new[] { placeholder }, AllowedModulesRulesField).Rules) { if (rule.Condition != null) { var passed = rule.Evaluate(ruleContext); if (passed) { rule.Execute(ruleContext); } } } return(ruleContext); }
public override void Process(ProcessItemArgs args) { Assert.ArgumentNotNull((object)args, "args"); var obj = Context.Item; if (obj == null) return; var parentItem = obj.Database.GetItem(Constants.ProcessItemRules); if (parentItem == null) return; var rules = RuleFactory.GetRules<RuleContext>(parentItem, "Rule"); if (rules == null) return; var ruleContext = new RuleContext() { Item = obj }; rules.Run(ruleContext); }
protected virtual IEnumerable <string> GetDataSoursesForLayout(Item pageItem, ID layoutFieldId) { if (pageItem == null) { return(Enumerable.Empty <string>()); } var datasourses = new List <string>(); var renderings = pageItem .GetLayoutDefinition(layoutFieldId)? .Devices? .ToArray()? .Select(x => (DeviceDefinition)x)? .SelectMany(d => d.Renderings.Cast <RenderingDefinition>())? .ToArray() ?? new RenderingDefinition[0]; foreach (var rendering in renderings) { datasourses.Add(rendering.Datasource); if (rendering.Rules != null && rendering.Rules.HasElements) { var rules = RuleFactory.ParseRules <ConditionalRenderingsRuleContext>(pageItem.Database, rendering.Rules); var actions = rules.Rules? .SelectMany(x => x.Actions) .Select(x => x as SetDataSourceAction <ConditionalRenderingsRuleContext>) .Where(x => x != null) .ToArray(); foreach (var action in actions ?? Enumerable.Empty <SetDataSourceAction <ConditionalRenderingsRuleContext> >()) { datasourses.Add(action.DataSource); } } } return(datasourses .Where(x => !string.IsNullOrWhiteSpace(x)) .Distinct() .ToList()); }