public ExampleList(LemmatizerSettings lsett): base() {
            this.lsett = lsett;

            this.dictExamples = new Dictionary<string, LemmaExample>();
            this.lstExamples = null;
            this.rlRules = new RuleList(lsett);
        }
        public void TestRetrieveMatchedRule_CompleteQuery()
        {
            TableDataRetriever dataRetriever       = new TableDataRetriever();
            string             group_customer      = "LTSHoldings";
            string             receivingCountry    = "DK";
            string             shippingCountry     = "SE";
            string             shippingCompany     = "Beijer Electronics Products AB";
            string             receivingCompany    = "KJ-Elektro";
            string             shippingPostalCode  = "21124";
            string             receivingPostalCode = "4800";

            string         euCountryCodes = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,UK, GB";
            IRuleRetriever ruleRetriever  = new RuleRetriever(dataRetriever.GetRuleListData(), euCountryCodes);
            RuleList       actualRuleList = ruleRetriever
                                            .ClearQueryConditions()
                                            .SetCriteria((x) => x.Group, group_customer)
                                            .SetCriteria((x) => x.Receiving_Country_Code, receivingCountry)
                                            .SetCriteria((x) => x.Shipping_Country_Code, shippingCountry)
                                            .SetCriteria((x) => x.Shipping_Company, shippingCompany)
                                            .SetCriteria((x) => x.Receving_Company, receivingCompany)
                                            .SetCriteria((x) => x.Shipping_PostalCode, shippingPostalCode)
                                            .SetCriteria((x) => x.Receiving_PostalCode, receivingPostalCode)
                                            .GetRule();

            Assert.AreEqual(1020, actualRuleList.Id);
        }
        private async Task PlayRuleAsync(RuleCard thisCard)
        {
            if (thisCard.Deck == EnumRuleText.ReverseOrder)
            {
                if (_gameContainer.PlayerList.Count() == 2)
                {
                    _gameContainer.SaveRoot !.AnotherTurn = true;
                    await _gameContainer.AnimatePlayAsync !(thisCard);
                    await _analyzeProcesses.AnalyzeQueAsync();

                    return;
                }
            }
            if (thisCard.Category != EnumRuleCategory.Basic && thisCard.Category != EnumRuleCategory.None)
            {
                var thisCat = thisCard.Category;
                _gameContainer.SaveRoot !.RuleList.RemoveAllOnly(items => items.Category == thisCat);
            }
            _gameContainer.SaveRoot !.RuleList.Add(thisCard);
            _gameContainer.RefreshRules();
            if (_gameContainer !.QuePlayList.Count == 0)
            {
                _analyzeProcesses.AnalyzeRules();
                if (_gameContainer.LeftToDraw > 0)
                {
                    _gameContainer.SaveRoot.DoAnalyze = true;
                    await _gameContainer.DrawAsync !();
                    return;
                }
            }
            await _analyzeProcesses.AnalyzeQueAsync();
        }
 private void RulesAppliedHandler(RuleList <ConditionalRenderingsRuleContext> ruleList, ConditionalRenderingsRuleContext ruleContext, RuleAction <ConditionalRenderingsRuleContext> action)
 {
     if (action.GetType().Name.StartsWith("SetRenderingVariantAction"))
     {
         _VariantId = (action as SetRenderingVariantAction <ConditionalRenderingsRuleContext>).VariantID;
     }
 }
Beispiel #5
0
        public static RuleList RemoveFactorization(RuleList ruleList)
        {
            var didChange = true;

            while (didChange)
            {
                didChange = false;
                var nonTermsToAdd = new List <string>();
                foreach (var nonTerm in ruleList.NonTerminals.ToList())
                {
                    var alphabet           = ruleList.Alphabet;
                    var rulesToPrefixCheck = ruleList.Rules.Where(x => x.NonTerminal == nonTerm).ToList();

                    var factorizedRules = GetLongestCommonPrefix(rulesToPrefixCheck, ref alphabet, ref didChange,
                                                                 ref nonTermsToAdd);
                    ruleList.Alphabet = alphabet;

                    foreach (var rule in ruleList.Rules.Where(x => x.NonTerminal == nonTerm).ToList())
                    {
                        ruleList.Rules.Remove(rule);
                    }
                    foreach (var factorizedRule in factorizedRules)
                    {
                        ruleList.Rules.Add(factorizedRule);
                    }
                    foreach (var item in nonTermsToAdd)
                    {
                        ruleList.NonTerminals.Add(item);
                    }
                }
            }

            return(ruleList);
        }
        /// <summary>
        ///     Invoke global device resolution rules.
        /// </summary>
        /// <returns>True if a global device resolution rule applied.</returns>
        protected bool RunModuleRules()
        {
            Item moduleRuleItem = Context.Database.GetItem("{143624D2-7C7F-460A-B97E-068283D646B9}");
            if (moduleRuleItem == null)
                return false;

            string ruleXml = moduleRuleItem["Rule"];

            if (String.IsNullOrEmpty(ruleXml) || moduleRuleItem["Disable"] == "1")
                return false;

            // parse the rule XML
            RuleList<RuleContext> rules = new RuleList<RuleContext> {Name = moduleRuleItem.Paths.Path};
            RuleList<RuleContext> parsed = RuleFactory.ParseRules<RuleContext>(
                Context.Database,
                ruleXml);
            rules.AddRange(parsed.Rules);

            if (rules.Count < 1)
                return false;

            // invoke the rule
            RuleContext ruleContext = new RuleContext {Item = Context.Item};
            rules.Run(ruleContext);

            // rule applied
            return ruleContext.IsAborted;
        }
        public void RunEventRules(string eventName, Item pageItem = null, params string[] values)
        {
            Assert.IsNotNullOrEmpty(eventName, $"{nameof(RulesService)}.{nameof(RunEventRules)} parameter {nameof(eventName)} is required");

            var ruleContext = new EventRuleContext()
            {
                EventName = eventName,
                Item      = pageItem,
                Value1    = ParamUtil.GetValue(1, values),
                Value2    = ParamUtil.GetValue(2, values),
                Value3    = ParamUtil.GetValue(3, values)
            };

            // Run Global Rules
            using (new SecurityDisabler())
            {
                var root = Utils.ItemUtil.GetItemById(ItemIds.GlobalRules.EventRules);
                if (root == null)
                {
                    return; // no root, exit
                }
                RuleList <EventRuleContext> rules = RuleFactory.GetRules <EventRuleContext>(root, "Rule");
                if (rules != null)
                {
                    rules.Run(ruleContext);
                }
            }
        }
        private static List <ExpandoObject> IterateGeneralRules(ref List <ExpandoObject> propertyObject,
                                                                RuleList ruleList,
                                                                ref List <ExpandoObject> destDataRows, ref List <ExpandoObject> errorMessages)
        {
            foreach (var row in propertyObject)
            {
                foreach (var eachRuleSet in ruleList.RuleSets)
                {
                    foreach (var eachBaseRule in eachRuleSet.RuleSets)
                    {
                        if (!(eachBaseRule is IErrorCheck))
                        {
                            eachBaseRule.Configure(row);
                        }
                    }
                }

                try
                {
                    ruleList.Execute(row, ref destDataRows);
                }
                catch (ErrorCheckException ecEx)
                {
                    var ex = new ExpandoObject() as IDictionary <string, object>;
                    ex.Add("ErrorMessage", ecEx.Message);
                    errorMessages.Add((ExpandoObject)ex);
                }
            }

            return(destDataRows);
        }
        protected override void Evaluate(CustomizeRenderingArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Item item = args.PageContext.Item;

            if (item != null)
            {
                RenderingReference    renderingReference    = CustomizeRenderingProcessor.GetRenderingReference(args.Rendering, Context.Language, args.PageContext.Database);
                GetRenderingRulesArgs getRenderingRulesArgs = new GetRenderingRulesArgs(item, renderingReference);
                GetRenderingRulesPipeline.Run(getRenderingRulesArgs);
                RuleList <ConditionalRenderingsRuleContext> ruleList = getRenderingRulesArgs.RuleList;
                if (ruleList != null && ruleList.Count != 0)
                {
                    List <RenderingReference> references = new List <RenderingReference>
                    {
                        renderingReference
                    };
                    ConditionalRenderingsRuleContext conditionalRenderingsRuleContext = new ConditionalRenderingsRuleContext(references, renderingReference)
                    {
                        Item = item
                    };
                    conditionalRenderingsRuleContext.Parameters["mvc.rendering"] = args.Rendering;
                    RunRules(ruleList, conditionalRenderingsRuleContext);
                    ApplyActions(args, conditionalRenderingsRuleContext);
                    args.IsCustomized = true;
                }
            }
        }
Beispiel #10
0
        protected override void Evaluate(Sitecore.Pipelines.InsertRenderings.InsertRenderingsArgs args, Sitecore.Data.Items.Item item)
        {
            RuleList <ConditionalRenderingsRuleContext> globalRules = this.GetGlobalRules(item);

            foreach (RenderingReference reference in new List <RenderingReference>((IEnumerable <RenderingReference>)args.Renderings))
            {
                string conditions = reference.Settings.Conditions;
                if (!string.IsNullOrEmpty(conditions))
                {
                    List <Item> conditionItems = this.GetConditionItems(item.Database, conditions);
                    if (conditionItems.Count > 0)
                    {
                        RuleList <ConditionalRenderingsRuleContext> rules = RuleFactory.GetRules <ConditionalRenderingsRuleContext>((IEnumerable <Item>)conditionItems, "Rule");
                        ConditionalRenderingsRuleContext            renderingsRuleContext = new ConditionalRenderingsRuleContext(args.Renderings, reference);
                        renderingsRuleContext.Item = item;
                        ConditionalRenderingsRuleContext ruleContext = renderingsRuleContext;
                        rules.Run(ruleContext);
                    }
                }
                if (globalRules != null)
                {
                    ConditionalRenderingsRuleContext renderingsRuleContext = new ConditionalRenderingsRuleContext(args.Renderings, reference);
                    renderingsRuleContext.Item = item;
                    ConditionalRenderingsRuleContext ruleContext = renderingsRuleContext;
                    globalRules.Run(ruleContext);
                }

                GetCustomRules(args, item, reference);
            }
        }
Beispiel #11
0
        public static IClaimCalculator create()
        {
            RuleList        ruleList        = new RuleList();
            FixedConditions fixedConditions = new FixedConditions();

            return(new StandardClaimCalculator(ruleList, fixedConditions));
        }
 private void ClearProperties()
 {
     RuleList.Clear();
     BagList.Clear();
     NodeList.Clear();
     ChildList.Clear();
 }
        public void TestRetrieveMatchedRule_CompareAgainstNonSpecific_EUCountry()
        {
            TableDataRetriever dataRetriever       = new TableDataRetriever();
            string             group_customer      = "LTSHoldings";
            string             shippingCountry     = "DE";
            string             receivingCountry    = "SE";
            string             shippingCompany     = "LTS Holdings";
            string             receivingCompany    = "LTS";
            string             shippingPostalCode  = "4800";
            string             receivingPostalCode = "21124";

            string         euCountryCodes = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,UK, GB";
            IRuleRetriever ruleRetriever  = new RuleRetriever(dataRetriever.GetRuleListData(), euCountryCodes);
            RuleList       actualRuleList = ruleRetriever
                                            .ClearQueryConditions()
                                            .SetCriteria((x) => x.Group, group_customer)
                                            .SetCriteria((x) => x.Receiving_Country_Code, ruleRetriever.GetCountryToCompare(group_customer, receivingCountry, rule => rule.Receiving_Country_Code))
                                            .SetCriteria((x) => x.Shipping_Country_Code, ruleRetriever.GetCountryToCompare(group_customer, shippingCountry, rule => rule.Shipping_Country_Code))
                                            .SetCriteria((x) => x.Shipping_Company, shippingCompany)
                                            .SetCriteria((x) => x.Receving_Company, receivingCompany)
                                            .SetCriteria((x) => x.Shipping_PostalCode, shippingPostalCode)
                                            .SetCriteria((x) => x.Receiving_PostalCode, receivingPostalCode)
                                            .GetRule();

            Assert.AreEqual(5, actualRuleList.Id);
            Assert.AreEqual("EU", actualRuleList.Shipping_Country_Code);        //Should match with 'EU' country since no rule definition for specific country
        }
        /// <summary> Gets item renderings </summary>
        /// <param name="item">item to proceed</param>
        /// <returns>list of item renderings</returns>
        protected List <RenderingReference> GetRenderings(Item item)
        {
            RuleList <ConditionalRenderingsRuleContext> globalRules = this.GetGlobalRules(item);
            List <RenderingReference> resultCollection = new List <RenderingReference>(item.Visualization.GetRenderings(Sitecore.Context.Device, true));

            foreach (RenderingReference reference in new List <RenderingReference>(resultCollection))
            {
                string conditions = reference.Settings.Conditions;
                if (!string.IsNullOrEmpty(conditions))
                {
                    List <Item> conditionItems = this.GetConditionItems(item.Database, conditions);
                    if (conditionItems.Count > 0)
                    {
                        RuleList <ConditionalRenderingsRuleContext> rules       = RuleFactory.GetRules <ConditionalRenderingsRuleContext>(conditionItems, "Rule");
                        ConditionalRenderingsRuleContext            ruleContext = new ConditionalRenderingsRuleContext(resultCollection, reference)
                        {
                            Item = item
                        };
                        rules.Run(ruleContext);
                    }
                }

                if (globalRules != null)
                {
                    ConditionalRenderingsRuleContext globalRuleContext = new ConditionalRenderingsRuleContext(resultCollection, reference)
                    {
                        Item = item
                    };
                    globalRules.Run(globalRuleContext);
                }
            }

            return(resultCollection);
        }
        public void TestRetrieveMatchedRule_CompareAgainstSpecificEUCountry()
        {
            TableDataRetriever dataRetriever       = new TableDataRetriever();
            string             group_customer      = "LTSHoldings";
            string             shippingCountry     = "FI";
            string             receivingCountry    = "FI";
            string             shippingCompany     = "Beijer Electronics Products AB";
            string             receivingCompany    = "KJ-Elektro";
            string             shippingPostalCode  = "21124";
            string             receivingPostalCode = "4800";

            string         euCountryCodes = "AT,BE,BG,HR,CY,CZ,DK,EE,FI,FR,DE,GR,HU,IE,IT,LV,LT,LU,MT,NL,PL,PT,RO,SK,SI,ES,SE,UK, GB";
            IRuleRetriever ruleRetriever  = new RuleRetriever(dataRetriever.GetRuleListData(), euCountryCodes);
            RuleList       actualRuleList = ruleRetriever
                                            .ClearQueryConditions()
                                            .SetCriteria((x) => x.Group, group_customer)
                                            .SetCriteria((x) => x.Receiving_Country_Code, ruleRetriever.GetCountryToCompare(group_customer, receivingCountry, rule => rule.Receiving_Country_Code))
                                            .SetCriteria((x) => x.Shipping_Country_Code, ruleRetriever.GetCountryToCompare(group_customer, shippingCountry, rule => rule.Shipping_Country_Code))
                                            .SetCriteria((x) => x.Shipping_Company, shippingCompany)
                                            .SetCriteria((x) => x.Receving_Company, receivingCompany)
                                            .SetCriteria((x) => x.Shipping_PostalCode, shippingPostalCode)
                                            .SetCriteria((x) => x.Receiving_PostalCode, receivingPostalCode)
                                            .GetRule();

            Assert.AreEqual(1022, actualRuleList.Id);
            Assert.AreEqual("FI", actualRuleList.Shipping_Country_Code);        //Should match with 'FI' country instead of 'EU' due to specific definition of rule for specific country
        }
        protected virtual void Evaluate(CustomizeRenderingArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Item item = args.PageContext.Item;

            if (item != null)
            {
                RenderingReference    renderingReference    = GetRenderingReference(args.Rendering, args.Rendering.Item.Language, args.Rendering.Item.Database);
                GetRenderingRulesArgs getRenderingRulesArgs = new GetRenderingRulesArgs(item, renderingReference);
                GetRenderingRulesPipeline.Run(getRenderingRulesArgs);
                RuleList <ConditionalRenderingsRuleContext> ruleList = getRenderingRulesArgs.RuleList;
                if (ruleList != null && ruleList.Count != 0)
                {
                    List <RenderingReference> references = new List <RenderingReference>
                    {
                        renderingReference
                    };
                    ConditionalRenderingsRuleContext conditionalRenderingsRuleContext = new ConditionalRenderingsRuleContext(references, renderingReference)
                    {
                        Item = item
                    };
                    conditionalRenderingsRuleContext.Parameters["mvc.rendering"] = args.Rendering;
                    var matchingRule = GetMatchingRule(ruleList, conditionalRenderingsRuleContext);
                    ApplyActions(args, conditionalRenderingsRuleContext, matchingRule);
                }
            }
        }
        public bool RunRule(Item outcomeItem)
        {
            if (outcomeItem == null)
                return false;

            string ruleXml = outcomeItem[RulesField];

            if (String.IsNullOrEmpty(ruleXml))
                return false;

            RuleList<RuleContext> rules = new RuleList<RuleContext> { Name = outcomeItem.Paths.Path };
            RuleList<RuleContext> parsed = RuleFactory.ParseRules<RuleContext>(
                Context.Database,
                ruleXml);
            rules.AddRange(parsed.Rules);

            if (rules.Count < 1)
                return false;

            RuleContext ruleContext = new RuleContext { Item = Context.Item };
            ruleContext.Parameters.Add("DefinitionItem",outcomeItem);
            
            rules.Run(ruleContext);
            return ruleContext.IsAborted;
        }  
        public string ApplyDesign(Item ruleProgram, Item page, string crawlDepth = null)
        {
            BotLog.Log.Info($"::START:: program {ruleProgram?.DisplayName} on page {page.DisplayName}, {page.ID}, crawl depth {crawlDepth}");
            Log.Info($"DESIGNBOT::START:: program {ruleProgram?.DisplayName} on page {page.DisplayName}, {page.ID}, crawl depth {crawlDepth}", this);

            // Get design rules
            RuleList <DesignBotRuleContext> rules = RuleFactory.GetRules <DesignBotRuleContext>(ruleProgram, "Rule");

            if (rules != null)
            {
                // Apply design program
                int depth;
                if (!int.TryParse(crawlDepth ?? "0", out depth))
                {
                    depth = 0;
                }
                depth = Math.Max(0, depth);

                using (new SecurityDisabler())
                {
                    using (new ScreenshotGenerationDisabler())
                    {
                        RunProgram_r(rules, page, depth);
                    }
                }
            }

            BotLog.Log.Info($"::END:: program {ruleProgram?.DisplayName} on page {page.DisplayName}, {page.ID}, crawl depth {crawlDepth}");
            Log.Info($"DESIGNBOT::END:: program {ruleProgram?.DisplayName} on page {page.DisplayName}, {page.ID}, crawl depth {crawlDepth}", this);
            return("Success");
            // item.Editing.BeginEdit();
            // item.Editing.EndEdit(updateStatistics: true, silent: false);
            // item.Editing.CancelEdit();
        }
Beispiel #19
0
        public void TestMethod1()
        {
            IDictionary <string, object> src = new Dictionary <string, object>();
            var dest = new List <ExpandoObject>();

            src.Add(new KeyValuePair <string, object>("objectOne", "valueOne"));
            src.Add(new KeyValuePair <string, object>("objectTwo", "valueTwo"));
            src.Add(new KeyValuePair <string, object>("objectThree", "valueThree"));
            src.Add(new KeyValuePair <string, object>("objectFour", "valueFour"));

            var ruleList = new RuleList();
            var ruleOne  = new IncludeRule("!=", "string", "valueZero", true);
            var ruleSet  = new RuleSet();
            var iRules   = new List <IRule> {
                ruleOne
            };

            ruleList.RuleSets.Add(ruleSet);
            var ruleTwo   = new IncludeRule("==", "string", "valueOne", true);
            var ruleThree = new IncludeRule("==", "string", "valueTwo", true);
            var ruleFour  = new IncludeRule("==", "string", "valueThree", true);
            var ruleFive  = new ExcludeRule("==", "string", "valueThree", true);
            var ruleSix   = new ErrorCheckRule("!=", "string", "valueZero", true);


            //ruleList.RuleSets.Add();
            ruleList.Execute(src, ref dest);
        }
        /// <summary>
        ///   Retrieves the rules.
        /// </summary>
        /// <param name="action"> The action. </param>
        /// <returns> </returns>
        public static RuleList RetrieveRules(Action action)
        {
            RuleList rules = new RuleList();
            try
            {
                if(action == null)
                {
                    throw new ArgumentNullException("action");
                }

                RuleBuilderFactory actionRuleFactory = new ActionRuleFactory();
                RuleBuilderFactory fieldRuleFactory = new FieldRuleFactory();
                RuleBuilderFactory propertyRuleFactory = new PropertyRuleFactory();

                RuleBuilderDirector director = new RuleBuilderDirector();
                director.Builders.Add(new ActionObjectRuleBuilder(new ActionRuleSource(actionRuleFactory, action)));
                director.Builders.Add(new ActionPropertyRuleBuilder(new PropertyRuleSource(propertyRuleFactory, action)));
                director.Builders.Add(new ActionFieldRuleBuilder(new FieldRuleSource(fieldRuleFactory, action)));

                foreach(RuleBuilderBase builder in director.Builders)
                {
                    director.DefineBuilder(builder);
                    director.CreateRules();
                    rules.AddRange(director.RetrieveRules());
                }
            }
            catch(Exception)
            {
                throw;
            }
            return rules;
        }
Beispiel #21
0
 private void EnhancedRuleList_Applied(RuleList <T> ruleList, T ruleContext, RuleAction <T> action)
 {
     if (ruleContext.StopProcessingThisRuleset)
     {
         ruleContext.Abort();
     }
 }
Beispiel #22
0
        private static IEnumerable <RuleItem> FindUpRule(RuleList ruleList, RuleItem emptyItem, ref List <Used> usedRules)
        {
            var lead = new HashSet <RuleItem>();

            foreach (var rule in ruleList.Rules)
            {
                var item = rule.Items.Where(x => x.Value == emptyItem.Value).ToList();
                if (item.Count != 0)
                {
                    foreach (var index in item.Select(t => rule.Items.IndexOf(t)))
                    {
                        if (!usedRules.Contains(new Used(rule, index)))
                        {
                            if (index == rule.Items.Count - 1)
                            {
                                usedRules.Add(new Used(rule, index));
                                var newEmptyItem = new RuleItem(rule.NonTerminal, false);
                                lead.UnionWith(FindUpRule(ruleList, newEmptyItem, ref usedRules));
                            }
                            else
                            {
                                lead.Add(rule.Items[index + 1]);
                            }
                        }
                    }
                }
            }

            return(lead);
        }
            override public RuleList Copy()
            {
                var ret = new RuleList();

                lock (Sync) ret.arrayList.AddRange(arrayList);
                return(ret);
            }
        public void OnItemAdded(object sender, EventArgs args)
        {
            var addedItem = ExtractItem(args);

            if (addedItem == null)
            {
                return;
            }

            var rulesFolderId  = ID.Parse(ItemAddedRulesConstants.ItemAddedRules.ItemId);
            var itemAddedRules = addedItem.Database.GetItem(rulesFolderId);

            if (itemAddedRules == null)
            {
                return;
            }

            var ruleContext = new RuleContext();

            ruleContext.Item = addedItem;

            RuleList <RuleContext> rules = RuleFactory.GetRules <RuleContext>(itemAddedRules, "Rule");

            if (rules.Count > 0)
            {
                rules.Run(ruleContext);
            }
        }
Beispiel #25
0
 private void EnhancedRuleList_Evaluating(RuleList <T> ruleList, T ruleContext, Rule <T> rule)
 {
     if (ruleContext.StopProcessingThisRuleset)
     {
         ruleContext.Abort();
     }
 }
Beispiel #26
0
 /// <summary>
 /// Create Event Handlers and attach to the Rule Collection
 /// </summary>
 /// <param name="ruleCollection"></param>
 public void RegisterRuleList(PDB holder, RuleList ruleCollection)
 {
     this._rule_holder       = holder;
     this._rules             = ruleCollection;
     this.RuleAddedHandler   = new RuleEventHandler(this.OnRuleAsserted);
     this.RuleRemovedHandler = new RuleEventHandler(this.OnRuleRetracted);
     this.AttachEventHandlers(this._rules);
 }
 public PDB(bool isStaticKB)
 {
     isStorage = isStaticKB;
     _rules    = new RuleList();
     if (isStorage)
     {
         _rules.syncPDB = this;
     }
 }
 /// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
 public Connect()
 {
     _rules = new RuleList();
     _ruleFactories = new List<RuleFactory>();
     _ruleFactories.Add(new SimpleRuleFactory(typeof(ByFileRule), typeof(ExpressionRuleData)));
     _ruleFactories.Add(new SimpleRuleFactory(typeof(ByFuncRule), typeof(ExpressionRuleData)));
     _ruleFactories.Add(new SimpleRuleFactory(typeof(ByModuleRule), typeof(ModuleRuleData)));
     _handlers = new List<ExceptionHandler>();
 }
 // - la dernière mesure de la partition doit comporter une ou plusieurs notes, sans accord
 public LastMeasureValidationRule(int n, params Measure[] measures)
 {
     RuleList.Add(new ValidationRule <Measure[]>(measures, m => m.Last().Type == MeasureType.ACCORD || m.Last().Type == MeasureType.SILENCE)
     {
         Number    = n,
         Measures  = measures,
         ErrorCode = ValidationError.HARMONY_LAST_MEASUREMENT_TYPE_ERROR,
     });
 }
        /// <summary>
        /// Gets the matching rule from the rulelist
        /// </summary>
        /// <param name="rules"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        protected virtual Rule <ConditionalRenderingsRuleContext> GetMatchingRule(RuleList <ConditionalRenderingsRuleContext> rules, ConditionalRenderingsRuleContext context)
        {
            Assert.ArgumentNotNull(rules, "rules");
            Assert.ArgumentNotNull(context, "context");

            var matchingRule = rules.Rules.FirstOrDefault(r => r.Evaluate(context)) ?? rules.Rules.FirstOrDefault(r => r.UniqueId == ID.Null);

            return(matchingRule);
        }
Beispiel #31
0
 private static void RunPromoRule(Sitecore.Pipelines.InsertRenderings.InsertRenderingsArgs args, Sitecore.Data.Items.Item item, RenderingReference reference, Item promo, string fieldName)
 {
     if (promo != null && !string.IsNullOrEmpty(fieldName))
     {
         RuleList <ConditionalRenderingsRuleContext> rules = RuleFactory.GetRules <ConditionalRenderingsRuleContext>(promo.Fields[fieldName]);
         var ruleContext = new ConditionalRenderingsRuleContext(args.Renderings, reference);
         ruleContext.Item = item;
         rules.Run(ruleContext);
     }
 }
Beispiel #32
0
 /// <summary>
 /// Executes the specified builderSource.
 /// </summary>
 /// <returns></returns>
 /// ///
 public RuleList BuildRules()
 {
     Rules = new RuleList();
     foreach (var attribute in ValidationAttributes)
     {
         ValidationAttribute validation = (ValidationAttribute)attribute;
         Rules.Add(validation.CreateRule(validation.Target));
     }
     return(Rules);
 }
 protected override void RunRules(RuleList <ConditionalRenderingsRuleContext> rules, ConditionalRenderingsRuleContext context)
 {
     Assert.ArgumentNotNull(rules, "rules");
     Assert.ArgumentNotNull(context, "context");
     if (!RenderingRuleEvaluatedPipeline.IsEmpty())
     {
         rules.Evaluated += RulesEvaluatedHandler;
         rules.Applied   += RulesAppliedHandler;
     }
     rules.RunFirstMatching(context);
 }
Beispiel #34
0
 private Rule(Conclusion conclusion, Dictionary <string, List <Rule> > RuleLists)
 {
     this.conclusion = conclusion;
     if (this.RuleList is null)
     {
         RuleList = new List <Rule>();
         RuleLists.Add(conclusion.ToString(), RuleList);
     }
     RuleList.Add(this);
     this.RuleLists = RuleLists;
 }
Beispiel #35
0
        public static RuleList RemoveLeftRecursion(RuleList ruleList)
        {
            var newRuleList   = new List <Rule>();
            var nonTerminals  = ruleList.NonTerminals;
            var nonTermsToAdd = new HashSet <string>();

            foreach (var nonTerm in nonTerminals)
            {
                var commonRules        = new List <Rule>();
                var leftRecursionRules = new List <Rule>();
                var freeLetter         = ruleList.Alphabet[0];
                foreach (var rule in ruleList.Rules.Where(x => x.NonTerminal == nonTerm))
                {
                    if (rule.Items[0].Value == nonTerm)
                    {
                        leftRecursionRules.Add(rule);
                    }
                    else
                    {
                        commonRules.Add(rule);
                    }
                }
                if (leftRecursionRules.Any())
                {
                    nonTermsToAdd.Add(freeLetter);
                    ruleList.Alphabet.RemoveAt(0);
                    foreach (var commonRule in commonRules)
                    {
                        if (commonRule.Items.Count == 1 && commonRule.Items[0].Value == Constants.EmptySymbol)
                        {
                            commonRule.Items.RemoveAt(0);
                        }
                        commonRule.Items.Add(new RuleItem(freeLetter, false));
                        newRuleList.Add(commonRule);
                    }

                    foreach (var leftRecursionItems in leftRecursionRules.Select(leftRecursionRule =>
                                                                                 leftRecursionRule.Items.Skip(1).ToList()))
                    {
                        leftRecursionItems.Add(new RuleItem(freeLetter, false));
                        newRuleList.Add(new Rule
                        {
                            NonTerminal = freeLetter,
                            Items       = leftRecursionItems
                        });
                    }

                    newRuleList.Add(new Rule
                    {
                        NonTerminal = freeLetter,
                        Items       = new List <RuleItem> {
                            new(Constants.EmptySymbol, true)
                        }
                    });
        public RulesForm(RuleList rules, List<RuleFactory> ruleFactories)
        {
            InitializeComponent();

            this.rules = rules;
            this.lastSelectedItemIndex = -1;
            PopulateList();

            this.ruleFactories = ruleFactories;
            cbRuleType.DataSource = this.ruleFactories;
            cbRuleType.DisplayMember = "Description";
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RuleList rules = new RuleList();
            List<RuleFactory> ruleFactories = new List<RuleFactory>();
            ruleFactories.Add(new SimpleRuleFactory(typeof(ByFileRule), typeof(ExpressionRuleData)));
            ruleFactories.Add(new SimpleRuleFactory(typeof(ByFuncRule), typeof(ExpressionRuleData)));
            ruleFactories.Add(new SimpleRuleFactory(typeof(ByModuleRule), typeof(ModuleRuleData)));
            Application.Run(new RulesForm(rules, ruleFactories));
        }
Beispiel #38
0
        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 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;
        }
 internal static RuleList getRuleList(HttpResponseMessage responce)
 {
     var ruleList = new RuleList();
     var jsonObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(responce.Content.ReadAsStringAsync().Result);
     if(jsonObj.ContainsKey("rules"))
     {
         var rulesArray = JsonConvert.DeserializeObject<List<object>>(jsonObj["rules"].ToString());
         foreach(var ruleObj in rulesArray)
         {
             var rule = new Rule();
             rule = JsonConvert.DeserializeObject<Rule>(ruleObj.ToString());
             ruleList.Add(rule);
         }
     }
     return ruleList;
 }
Beispiel #41
0
        public ExampleList(SerializationInfo info, StreamingContext context)
        {
            lsett = (LemmatizerSettings)info.GetValue("lsett", typeof(LemmatizerSettings));

            this.dictExamples = new Dictionary<string, LemmaExample>();
            this.lstExamples = null;
            this.rlRules = new RuleList(lsett);

            string[] aWords = (string[])info.GetValue("aWords", typeof(string[]));
            string[] aLemmas = (string[])info.GetValue("aLemmas", typeof(string[]));
            double[] aWeights = (double[])info.GetValue("aWeights", typeof(double[]));
            string[] aMsds = (string[])info.GetValue("aMsds", typeof(string[]));

            for (int iExm = 0; iExm < aWords.Length; iExm++)
                AddExample(aWords[iExm], aLemmas[iExm], aWeights[iExm], aMsds[iExm]);
        }
        public static RuleList ParseRules(string newFormat, RuleGrid grid)
        {
            // format string
            RuleList rules = new RuleList(newFormat);

            for (int r = grid.FixedRows; r < grid.RowsCount; r++)
            {
                if (!(bool)grid[r, RuleGrid.ColControl].Value)
                    continue;
                if (!grid.CheckRow(r))
                    continue;

                rules.Add(ParseRule(grid.GetCellsAtRow(r)));
            }

            return rules;
        }
        /// <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;
        }
Beispiel #44
0
        //private static bool fieldsNotEmpty(RuleGrid grid, int row, int[] columns)
        //{
        //    foreach (int i in columns)
        //    {
        //        if (((String)grid[row, i].Value) == null)
        //        {
        //            //throw new Exception("Some fields are incomplete.");
        //            return false;
        //        }
        //        if (((String)grid[row, i].Value).Equals(String.Empty))
        //        {
        //            return false;
        //        }
        //    }
        //    return true;
        //}
        public static RuleList ParseRule(string text)
        {
            StringReader sr = new StringReader(Helper.CleanRuleText(text));
            // format string
            RuleList rules = new RuleList(sr.ReadLine()); ;

            string[] tokens;
            string s;
            while ((s = sr.ReadLine()) != null)
            {
                // rule
                tokens = s.Split('\t');
                if (tokens[0].Equals("copy") || tokens[0].Equals("cpy"))
                //Copy Rule
                {
                    string[] searchPatterns = new string[tokens.Length - 2];
                    Array.Copy(tokens, 2, searchPatterns, 0, searchPatterns.Length);
                    rules.Add(new CopyRule(tokens[1], searchPatterns));
                }
                else if (tokens[0].Equals("delete") || tokens[0].Equals("del"))
                //Delete Rule
                {
                    if (tokens.Length == 1)
                        throw new System.ArgumentException(Textual.ErrorDeleteRule);
                    string[] searchPatterns = new string[tokens.Length - 1];
                    Array.Copy(tokens, 1, searchPatterns, 0, searchPatterns.Length);
                    rules.Add(new DeleteRule(searchPatterns));
                }
                else if (tokens[0].Equals("replace") || tokens[0].Equals("rpl"))
                //Replace Rule
                {
                    if (tokens.Length < 3)
                        throw new System.ArgumentException(Textual.ErrorReplaceRule);
                    string[] searchPatterns = new string[tokens.Length - 2];
                    Array.Copy(tokens, 2, searchPatterns, 0, searchPatterns.Length);
                    rules.Add(new ReplaceRule(tokens[1], tokens[2], searchPatterns));
                }
            }

            return rules;
        }
        /// <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;
        }
        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;
        }
Beispiel #47
0
        public void Load(Latino.BinarySerializer binRead, LemmatizerSettings lsett)
        {
            //load metadata
            bool bThisTopObject = binRead.ReadBool();

            //load refernce types if needed -------------------------
            if (bThisTopObject)
                this.lsett = new LemmatizerSettings(binRead);
            else
                this.lsett = lsett;

            rlRules = new RuleList(binRead, this.lsett);

            bool bCreateLstExamples = binRead.ReadBool();

            lstExamples = bCreateLstExamples ? new List<LemmaExample>() : null;
            dictExamples = new Dictionary<string, LemmaExample>();

            //load dictionary items
            int iCount = binRead.ReadInt();
            for (int iId = 0; iId < iCount; iId++) {
                LemmaRule lrRule = rlRules[binRead.ReadString()];
                LemmaExample le = new LemmaExample(binRead, this.lsett, lrRule);

                dictExamples.Add(le.Signature, le);
                if (bCreateLstExamples) lstExamples.Add(le);
            }
        }
Beispiel #48
0
 public CheckItem()
 {
     Rules = new RuleList();
 }
 private void RulesOnEvaluated(RuleList<RuleContext> ruleList, RuleContext ruleContext, Rule<RuleContext> rule)
 {
     var listviewItem = ResultItems.Items.First(p => p.Value == ruleContext.Item.ID.ToString());
     listviewItem.Checked = true;
     ResultItems.Refresh();
 }
 private void RulesOnEvaluating(RuleList<RuleContext> ruleList, RuleContext ruleContext, Rule<RuleContext> rule)
 {
     //var listviewItem = ResultItems.Items.First(p => p.Value == ruleContext.Item.ID.ToString());
     //listviewItem.Style["background"] = "yellow";
     //ResultItems.Refresh();
 }
Beispiel #51
0
        internal void PreviewRename(RuleList rules)
        {
            FileName fn = null;
            for (int i = 1; i < RowsCount; i++)
            {
                fn = (FileName)this[i, FileOldNameCol].Value;
                string newName = rules.Convert(fn.GetRenamableNamePart());

                if (Properties.Settings.Default.RemoveBrackets)
                {
                    newName = newName.Replace("()", String.Empty).Replace("[]", String.Empty).Replace("{}", String.Empty);
                }

                if (Properties.Settings.Default.RemoveMultipleSpace)
                {
                    newName = Regex.Replace(newName, @"\s+", " ");
                }

                if (Properties.Settings.Default.RemoveEndSpace)
                {
                    newName = newName.Trim();
                }

                if (newName.Length > 0)
                {
                    if (!fn.IsDirectory())
                    {
                        this[i, FileNewNameCol].Value = newName + fn.GetExtension();
                    }
                    else
                    {
                        this[i, FileNewNameCol].Value = newName;
                    }
                }
                else
                {
                    this[i, FileNewNameCol].Value = String.Empty;
                }
            }
            AutoSizeCells();
        }
 /// <summary>
 ///     Renders the rules.
 /// </summary>
 /// <param name="rules"> The rules. </param>
 /// <returns> </returns>
 public IValidationContext RenderRules(RuleList rules)
 {
     this.rules = rules;
     return RenderRules();
 }
Beispiel #53
0
 /// <summary>
 ///   Creates the rules.
 /// </summary>
 public void CreateRules()
 {
     rules = source.BuildRules();
 }
Beispiel #54
0
 private void ResetRules()
 {
     ruleGrid.ClearValues();
     rules = null;
     Properties.Settings.Default.LastRulePath = null;
 }
Beispiel #55
0
 private void PreviewRename(RuleList rules)
 {
     fileGrid.PreviewRename(rules);
     SetStatus(String.Empty);
 }
 /// <summary>
 /// Executes the specified builderSource.
 /// </summary>
 /// <returns></returns>
 /// ///
 public RuleList BuildRules()
 {
     Rules = new RuleList();
     foreach(var attribute in ValidationAttributes)
     {
         ValidationAttribute validation = (ValidationAttribute)attribute;
         Rules.Add(validation.CreateRule(validation.Target));
     }
     return Rules;
 }
 public RuleProcessor(RuleList<RuleContext> rules, Item ruleItem)
 {
     Rules = rules;
     RuleItem = ruleItem;
 }
Beispiel #58
0
        // include rules refresh
        private void PreviewRename()
        {
            if (inPreview)
            {
                if (ruleGrid.RowsCount == ruleGrid.FixedRows)
                {
                    return;
                }

                try
                {
                    rules = UI.RuleListFactory.ParseRules(newFormatTextBox.Text, ruleGrid);
                }
                catch(Exception e)
                {
                    SetStatus(e.Message);
                }

                PreviewRename(rules);
            }
        }
 public RulesFilter(RuleList<RuleContext> rules)
 {            
     _rules = rules;        
 }