Example #1
0
        private void ReloadEverything()
        {
            // Set the caption
            string caption = "Transliterator Editor ";

            if (sourceLanguage != null)
            {
                caption += sourceLanguage.Code;
            }
            if (destinationLanguage != null)
            {
                caption += " -> " + destinationLanguage.Code;
            }
            Title = caption;

            // Load rules
            rules = new RuleCollection(repository);
            dataGridRules.ItemsSource                = rules;
            transliterator                           = new Transliterator(repository, sourceLanguage.Code, destinationLanguage.Code);
            TransliterationExample.Transliterator    = (s => transliterator.Transliterate(s, false));
            TransliterationExample.Trans_li_te_rator = (s => transliterator.Transliterate(s, true));
            rules.MyTransliterator                   = transliterator;

            // Load TransliterationExamples
            examplesCollection           = new ExampleCollection(repository);
            dataGridExamples.ItemsSource = examplesCollection;

            TransliterationExample.DestinationFunc = Oggy.TransliterationEditor.WordDistance.CalculateDistance;
            TextBox_TextChanged(null, null);
        }
        protected override RuleCollection ParseRules(IEnumerable <TransportRule> adTransportRules, RuleHealthMonitor ruleHealthMonitor)
        {
            RuleCollection ruleCollection  = base.ParseRules(adTransportRules, ruleHealthMonitor);
            RuleCollection ruleCollection2 = new RuleCollection(ruleCollection.Name);

            foreach (Rule rule in ruleCollection)
            {
                PolicyTipRule policyTipRule = (PolicyTipRule)rule;
                foreach (Microsoft.Exchange.MessagingPolicies.Rules.Action action in policyTipRule.Actions)
                {
                    if (action is SenderNotify)
                    {
                        if (policyTipRule.ForkConditions != null && policyTipRule.ForkConditions.Count > 0)
                        {
                            AndCondition andCondition = new AndCondition();
                            foreach (Condition item in policyTipRule.ForkConditions)
                            {
                                andCondition.SubConditions.Add(item);
                            }
                            andCondition.SubConditions.Add(policyTipRule.Condition);
                            policyTipRule.Condition      = andCondition;
                            policyTipRule.ForkConditions = null;
                        }
                        ruleCollection2.Add(policyTipRule);
                        break;
                    }
                }
            }
            return(ruleCollection2);
        }
 /// <summary>
 /// Initialize a new instance of <see cref="InfoDescriptor"/>. Exposed for testing purposes.
 /// </summary>
 /// <param name="Type"></param>
 /// <param name="name">The name of the <see cref="InfoDescriptor"/>.</param>
 /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception>
 /// <exception cref="ArgumentException"><paramref name="name"/> is a <see cref="string.Empty"/>.</exception>
 /// <exclude/>
 protected InfoDescriptor(Type runtimeType, string name)
 {
     Guard.ArgumentNotNullOrEmptyString(name, "name");
     RuntimeType = runtimeType;
     Name = name;
     Rules = new RuleCollection(this);
 }
Example #4
0
 internal static bool IsPolicyTipsEnabled(OrganizationId organizationId)
 {
     if (organizationId == null)
     {
         ExTraceGlobals.UserContextCallTracer.TraceError(0L, "Find OrganizationConfig-PolicyTipRules was called with null OrganizationId.");
         return(false);
     }
     try
     {
         RuleCollection ruleCollection = ADUtils.GetPolicyTipRulesPerTenantSettings(organizationId).RuleCollection;
         return(ruleCollection != null && ruleCollection.Count > 0);
     }
     catch (ADTransientException arg)
     {
         ExTraceGlobals.UserContextCallTracer.TraceError <OrganizationId, ADTransientException>(0L, "Find OrganizationConfig-PolicyTipRules for {0} threw exception: {1}", organizationId, arg);
     }
     catch (DataValidationException arg2)
     {
         ExTraceGlobals.UserContextCallTracer.TraceError <OrganizationId, DataValidationException>(0L, "Find OrganizationConfig-PolicyTipRules for {0} threw exception: {1}", organizationId, arg2);
     }
     catch (DataSourceOperationException arg3)
     {
         ExTraceGlobals.UserContextCallTracer.TraceError <OrganizationId, DataSourceOperationException>(0L, "Find OrganizationConfig-PolicyTipRules for {0} threw exception: {1}", organizationId, arg3);
     }
     catch (TransientException arg4)
     {
         ExTraceGlobals.UserContextCallTracer.TraceError <OrganizationId, TransientException>(0L, "Find OrganizationConfig-PolicyTipRules for {0} threw exception: {1}", organizationId, arg4);
     }
     return(false);
 }
Example #5
0
        public void TestGetRuleByName()
        {
            RuleCollection rc = new RuleCollection((IRandom)m_Random.MockInstance);

            Rule rule1 = new Rule();

            rule1.Name        = "r";
            rule1.Probability = 1.0;

            rc.Add(rule1);

            m_Random.ExpectAndReturn("NextDouble", 0.0);
            Assert.AreSame(rule1, rc.GetRuleByName("r"));

            Rule rule2 = new Rule();

            rule2.Name        = "r";
            rule2.Probability = 1.0;

            rc.Add(rule2);

            m_Random.ExpectAndReturn("NextDouble", 0.2);
            Assert.AreSame(rule1, rc.GetRuleByName("r"), "rule 1 expected");
            m_Random.ExpectAndReturn("NextDouble", 0.6);
            Assert.AreSame(rule2, rc.GetRuleByName("r"), "rule 2 expected");

            m_Random.Verify();
        }
Example #6
0
 private static ReduceAction CreateReduceAction(ActionSubRecord record, SymbolCollection symbols,
     RuleCollection rules)
 {
     SymbolTerminal symbol = symbols[record.SymbolIndex] as SymbolTerminal;
     Rule rule = rules[record.Target];
     return new ReduceAction(symbol, rule);
 }
        /// <summary>
        /// Creates a new action by specifying the needed information.
        /// </summary>
        /// <param name="record">A part of the LALR record from the file content.</param>
        /// <param name="states">The LALR states.</param>
        /// <param name="symbols">The symbols.</param>
        /// <param name="rules">The rules.</param>
        /// <returns>A new action object.</returns>
        public static Action CreateAction(ActionSubRecord record, StateCollection states, SymbolCollection symbols,
                                          RuleCollection rules)
        {
            Action action;

            switch (record.Action)
            {
            case 1:
                action = CreateShiftAction(record, symbols, states);
                break;

            case 2:
                action = CreateReduceAction(record, symbols, rules);
                break;

            case 3:
                action = CreateGotoAction(record, symbols, states);
                break;

            case 4:
                action = CreateAcceptAction(record, symbols);
                break;

            default:
                return(null);    //todo: make exception
            }
            return(action);
        }
Example #8
0
 public WorldEditor()
 {
     m_rootRoom    = new Room_2D(DEFAULT_WIDTH, DEFAULT_HEIGHT);
     m_liveRules   = new RuleCollection();
     m_deathRules  = new RuleCollection();
     m_rebornRules = new RuleCollection();
 }
Example #9
0
        public ActionResult CreateRule(policyData vData, int linkId)
        {
            vData.PolicyLink           = new PolicyLinkEntity(linkId);
            vData.Policy               = vData.PolicyLink.Policy;
            vData.Rule                 = new RuleEntity();
            vData.Rule.Policy          = vData.Policy;
            vData.Rule.Condition.Type  = constants.conditionType;
            vData.Condition            = vData.Rule.Condition;
            vData.Condition.CombineAnd = true;

            RuleCollection      maxColl = new RuleCollection();
            PredicateExpression pe      = new PredicateExpression(RuleFields.PolicyId == vData.PolicyLink.PolicyId);
            object maxObj = maxColl.GetScalar(RuleFieldIndex.Order, null, AggregateFunction.Max, pe);

            if (maxObj != null && maxObj != DBNull.Value)
            {
                vData.Rule.Order = (int)maxObj + 1;
            }
            else
            {
                vData.Rule.Order = 0;
            }

            EffectCollection ecoll = new EffectCollection();

            ecoll.GetMulti((EffectFields.Name == "permit"));
            vData.Rule.EffectId = ecoll[0].Id;

            vData.Rule.Save(true);

            return(RedirectToAction("EditRule", new { id = vData.Rule.Id, linkId = linkId }));
        }
Example #10
0
        public override void Apply(Cart cart)
        {
            cart.Total = 0;
            var distinctProducts = cart.Items.Select(x => x.ItemCode).Distinct().ToList();

            foreach (var productCode in distinctProducts)
            {
                var productRule  = RuleCollection.Where(x => x.ProductCode == productCode).FirstOrDefault();
                var productPrice = cart.Items.Where(x => x.ItemCode == productCode)
                                   .Select(x => x.Price).First();
                var productListCount = cart.Items.Where(x => x.ItemCode == productCode).Count();

                if (productRule != null)
                {
                    var groupOfferCount = productListCount / productRule.Quantity;
                    var remainingCount  = productListCount % productRule.Quantity;

                    cart.Total += groupOfferCount * productRule.Amount;
                    cart.Total += remainingCount * productPrice;
                }
                else
                {
                    cart.Total += productPrice * productListCount;
                }
            }
        }
Example #11
0
        public void RegisterScripts()
        {
            _validator.ControlToValidate = "txtClientName";
            const string propertyName = "ClientName";

            _validator.PropertyName = propertyName;
            Type bookingType = typeof(Booking);

            _validator.ModelType = bookingType.AssemblyQualifiedName;

            ValidationAttribute[] attributes = new ValidationAttribute[] { new RequiredAttribute() };
            _mockValidationRunner.Setup(
                runner => runner.GetValidators(bookingType, propertyName)).Returns(
                attributes).Verifiable();

            RuleCollection rules = new RuleCollection(new List <Rule> {
                new Rule {
                    Name = "required", Options = true
                }
            });

            _mockRuleProvider.Setup(provider => provider.GetRules(attributes)).Returns(
                rules).Verifiable();

            _mockScriptManager.Setup(manager => manager.RegisterScripts(rules)).Verifiable();

            _validator.RegisterScripts();

            _mockRuleProvider.Verify();
            _mockValidationRunner.Verify();
            _mockScriptManager.Verify();
        }
 public GridViewer()
 {
     InitializeComponent();
     gridMap        = new Map();
     rules          = new RuleCollection();
     gridController = new GameController(gridMap, rules);
 }
Example #13
0
        /// <summary>
        /// Deletes all Inbox rules named MoveInterestingToJunk. Deletion to the Inbox rules
        /// collection can be batched into a single EWS call.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        static void DeleteInboxRule(ExchangeService service)
        {
            // Get all the Inbox rules in the user's mailbox. This results in a GetInboxRules operation
            // call to EWS.
            RuleCollection ruleCollection = service.GetInboxRules();

            Console.WriteLine("Returned your inbox rules from Exchange...");

            // Inbox rule updates, including deletions, can be batched into a single call to EWS.
            Collection <RuleOperation> ruleOperations = new Collection <RuleOperation>();

            foreach (Rule rule in ruleCollection)
            {
                if (rule.DisplayName == "MoveInterestingToJunk")
                {
                    Console.WriteLine("Found an Inbox rule to delete...");

                    DeleteRuleOperation deleteRule = new DeleteRuleOperation(rule.Id);

                    // Add each rule to deletion into a RuleOperation collection. Update operations
                    // can also be added to batch up changes to Inbox rules.
                    ruleOperations.Add(deleteRule);

                    Console.WriteLine("Added the Inbox rule to the collection of rules to update...");
                }
            }

            // The inbox rules are deleted here. This results in an UpdateInboxrules operaion call to EWS.
            service.UpdateInboxRules(ruleOperations, true);

            Console.WriteLine("Deleted Inbox rule(s)...");
        }
Example #14
0
        private void RuleRibbonToggleButton_PressedButtonChanged(object sender, EventArgs e)
        {
            if (!(sender is RibbonToggleButton pressedRule))
            {
                return;
            }

            string ruleName = pressedRule.Text;
            bool   pressed  = pressedRule.Pressed;

            IRule newRule = _rules.Where(x => x.Name == ruleName).FirstOrDefault();

            newRule.AppliesTo.Add(new FieldRange(new string[] { "Product", "Country", "Color", "Discount" }));

            RuleCollection appliedRules = _rulesManager.Rules;
            IRule          existingRule = appliedRules.Where(x => x.Name == ruleName).FirstOrDefault();

            if (!pressed && appliedRules.Contains(existingRule))
            {
                appliedRules.Remove(existingRule);
            }
            if (pressed && existingRule is null)
            {
                appliedRules.Add(newRule);
            }
        }
Example #15
0
        private void AddExamples_Click(object sender, RoutedEventArgs e)
        {
            RuleCollection rules = (RuleCollection)(dataGridRules.ItemsSource);

            List <string> words = new List <string>();

            foreach (var rule in rules)
            {
                if (rule.Examples != null)
                {
                    words.AddRange(rule.Examples.Split(new char[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries));
                }
                if (rule.CounterExamples != null)
                {
                    words.AddRange(rule.CounterExamples.Split(new char[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries));
                }
            }

            ExampleCollection examples = (ExampleCollection)(dataGridExamples.ItemsSource);
            var wordsInExamples        = examples.Select(example => example.Source);

            // Show the dialog
            var addExamplesWindow = new AddExamples(words.Distinct().Except(wordsInExamples), examples);

            addExamplesWindow.ShowDialog();
        }
Example #16
0
 protected override RuleCollection <Item> ConfigureRules(RuleCollection <Item> ruleCollection)
 {
     return(ruleCollection
            .AddRule(e => e.Id, new RequiredRule())
            .AddRule(e => e.Text, new RequiredRule())
            .AddRule(e => e.Description, new MaxLengthRule(20)));
 }
Example #17
0
 internal WorldMap(Room_2D room, RuleCollection deathRules, RuleCollection rebornRules, RuleCollection liveRules)
 {
     m_room        = room;
     m_deathRules  = deathRules;
     m_rebornRules = rebornRules;
     m_liveRules   = liveRules;
     m_worldViews  = new LinkedList <WorldView>();
 }
Example #18
0
        public void RuleConstructorTest()
        {
            Dictionary <char, string> jokers = new Dictionary <char, string>();

            RuleCollection collection = new RuleCollection();

            collection.Add(new Rule("ate", "ejt", jokers, collection));
        }
Example #19
0
 protected override RuleCollection <Address> ConfigureRules(RuleCollection <Address> ruleCollection)
 {
     return(ruleCollection
            .AddRule(e => e.City, new RequiredRule())
            .AddRule(e => e.CountryIsoCode, new CountryIsoCodeRule())
            .AddRule(e => e.PostalCode, new PostalCodeRule())
            .AddRule(e => e.StreetAddress, new RequiredRule(), new MaxLengthRule(100)));
 }
Example #20
0
 /// <summary>
 /// Populates the Rules ListView object with the provided RuleCollection object
 /// </summary>
 /// <param name="collection">RuleCollection to be processed into the Rules ListView object</param>
 private void PopulateRulesList(RuleCollection collection)
 {
     LVRulesList.Items.Clear();
     foreach (RuleRef r in collection.Rules)
     {
         LVRulesList.Items.Add(r.Title);
     }
 }
        private static ReduceAction CreateReduceAction(ActionSubRecord record, SymbolCollection symbols,
                                                       RuleCollection rules)
        {
            SymbolTerminal symbol = symbols[record.SymbolIndex] as SymbolTerminal;
            Rule           rule   = rules[record.Target];

            return(new ReduceAction(symbol, rule));
        }
Example #22
0
        private void RulesReferencer_Load(object sender, EventArgs e)
        {
            //fill the rule collection
            fullRuleset = new RuleCollection(@"DND5ERulesList.xml");

            //populate the controls
            PopulateRulesList(fullRuleset);
        }
Example #23
0
        //gavdcodeend 20

        //gavdcodebegin 21
        static void GetInboxRules(ExchangeService ExService)
        {
            RuleCollection allRules = ExService.GetInboxRules("*****@*****.**");

            foreach (Rule oneRule in allRules)
            {
                Console.WriteLine(oneRule.DisplayName + " - " + oneRule.Id);
            }
        }
Example #24
0
        public void ExecuteViaUnity()
        {
            UnityContainer container = new UnityContainer();
            container.RegisterType<IEngine<string>,Engine<string>>();
            IRuleCollection<string> coll = new RuleCollection<string>();
            container.RegisterInstance(coll);

            var engine = container.Resolve<IEngine<string>>();
            Assert.IsNotNull(engine);
        }
Example #25
0
        /// <summary>
        ///
        /// </summary>
        public LanguageDefinition()
        {
            File.WriteAllText(FileDefinitionPath.DestPath + "HtmlTransform.xslt", Resources.HtmlTransform);
            File.WriteAllText(FileDefinitionPath.DestPath + "langageDefinition.xml", Resources.langageDefinition);
            File.WriteAllText(FileDefinitionPath.DestPath + "RtfTransform.xslt", Resources.RtfTransform);
            File.WriteAllText(FileDefinitionPath.DestPath + "StructureDefinitionLangage.xml", Resources.StructureDefinitionLangage);
            File.WriteAllText(FileDefinitionPath.DestPath + "StructureFichierXML.xml", Resources.StructureFichierXML);
            File.WriteAllText(FileDefinitionPath.DestPath + "Style.css", Resources.Style);

            rules = new RuleCollection();
        }
        // Token: 0x06001A26 RID: 6694 RVA: 0x0005F260 File Offset: 0x0005D460
        internal static string GetRuleNamesForTracking(RuleCollection ruleCollection)
        {
            StringBuilder stringBuilder = new StringBuilder();

            foreach (Rule rule in ruleCollection)
            {
                stringBuilder.Append(rule.Name);
                stringBuilder.Append(",");
            }
            return(stringBuilder.ToString());
        }
Example #27
0
        public async Task InsertRules(List <RuleModel> rules, string connectionString)
        {
            string         parameterName  = "rules";
            RuleCollection ruleCollection = new RuleCollection();

            foreach (var rule in rules)
            {
                ruleCollection.Add(rule);
            }
            await _db.InsertWithUDT("dbo.spInsertRules", parameterName, ruleCollection, connectionString);
        }
Example #28
0
        private void OK_Click(object sender, RoutedEventArgs e)
        {
            RuleCollection newRules = (RuleCollection)(dataGridExamples.ItemsSource);

            foreach (var rule in newRules)
            {
                oldRules.Add(rule);
            }

            this.DialogResult = true;
            this.Close();
        }
        // Token: 0x06001A24 RID: 6692 RVA: 0x0005F09C File Offset: 0x0005D29C
        internal static ExecutionStatus RunRules(RuleCollection rules, ScanResultStorageProvider scanResultStorageProvider, Item storeItem, string fromAddress, ShortList <string> recipients, out List <DlpPolicyMatchDetail> dlpPolicyMatchDetails, out bool noContentMatch, out string ruleEvalLatency, out string ruleEvalResult, PolicyTipRequestLogger policyTipRequestLogger)
        {
            OwaRulesEvaluationContext owaRulesEvaluationContext = new OwaRulesEvaluationContext(rules, scanResultStorageProvider, storeItem, fromAddress, recipients, policyTipRequestLogger);
            OwaRulesEvaluator         owaRulesEvaluator         = new OwaRulesEvaluator(owaRulesEvaluationContext);

            owaRulesEvaluator.Run();
            dlpPolicyMatchDetails = owaRulesEvaluationContext.DlpPolicyMatchDetails;
            noContentMatch        = owaRulesEvaluationContext.NoContentMatch;
            ruleEvalLatency       = owaRulesEvaluationContext.RuleEvalLatency;
            ruleEvalResult        = owaRulesEvaluationContext.RuleEvalLResult;
            return(owaRulesEvaluationContext.ExecutionStatus);
        }
Example #30
0
 /// <summary>
 /// Searches through the full rules collection for any Rule objects which contain the search term in their title or their text.
 /// </summary>
 /// <param name="searchTerm"></param>
 private void SearchRules(string searchTerm)
 {
     searchedRuleset = new RuleCollection();
     foreach (RuleRef r in fullRuleset)
     {
         if (r.Title.ToUpper().Contains(searchTerm.ToUpper()) || r.Details.ToUpper().Contains(searchTerm.ToUpper()))
         {
             searchedRuleset.Add(r);
         }
     }
     PopulateRulesList(searchedRuleset);
 }
Example #31
0
        public void ThereCanOnlybeOneInstanceOfARuleInACollection()
        {
            RuleCollection ruleList = new RuleCollection();

            SingleRule testRule = new SingleRule(7, SpawnOrSurviveRule.SpawnRule);

            SingleRule testRule2 = new SingleRule(7, SpawnOrSurviveRule.SpawnRule);

            ruleList.Add(testRule);
            ruleList.Add(testRule2);

            Assert.AreEqual(1, ruleList.Count);
        }
Example #32
0
        public void ExecuteViaUnity()
        {
            UnityContainer container = new UnityContainer();

            container.RegisterType <IEngine <string>, Engine <string> >();
            container.RegisterType <IResultsFormatter, NoopFormatter>();
            IRuleCollection <string> coll = new RuleCollection <string>();

            container.RegisterInstance(coll);
            var engine = container.Resolve <IEngine <string> >();

            Assert.IsNotNull(engine);
        }
 public ClientAccessRulesEvaluationContext(RuleCollection rules, string username, IPEndPoint remoteEndpoint, ClientAccessProtocol protocol, ClientAccessAuthenticationMethod authenticationType, IReadOnlyPropertyBag userPropertyBag, ObjectSchema userSchema, Action <ClientAccessRulesEvaluationContext> denyAccessDelegate, Action <Rule, ClientAccessRulesAction> whatIfActionDelegate, long traceId) : base(rules)
 {
     this.AuthenticationType = authenticationType;
     this.UserName           = username;
     this.RemoteEndpoint     = remoteEndpoint;
     this.Protocol           = protocol;
     this.User                 = userPropertyBag;
     this.UserSchema           = userSchema;
     this.DenyAccessDelegate   = denyAccessDelegate;
     this.WhatIfActionDelegate = whatIfActionDelegate;
     this.WhatIf               = (whatIfActionDelegate != null);
     base.Tracer               = new ClientAccessRulesTracer(traceId);
 }
Example #34
0
 /// <summary>
 /// Creates a new action by specifying the needed information.
 /// </summary>
 /// <param name="record">A part of the LALR record from the file content.</param>
 /// <param name="states">The LALR states.</param>
 /// <param name="symbols">The symbols.</param>
 /// <param name="rules">The rules.</param>
 /// <returns>A new action object.</returns>
 public static Action CreateAction(ActionSubRecord record,
     StateCollection states,
     SymbolCollection symbols,
     RuleCollection rules)
 {
     Action action;
     switch (record.Action)
     {
         case 1: action = CreateShiftAction(record,symbols,states); break;
         case 2: action = CreateReduceAction(record,symbols,rules); break;
         case 3: action = CreateGotoAction(record,symbols,states); break;
         case 4: action = CreateAcceptAction(record,symbols); break;
         default: return null; //todo: make exception
     }
     return action;
 }
		/// <summary>
		/// The evaluation implementation in the pseudo-code described in the specification.
		/// </summary>
		/// <param name="context">The evaluation context instance.</param>
		/// <param name="rules">The policies that must be evaluated.</param>
		/// <returns>The final decission for the combination of the rule evaluation.</returns>
		public Decision Evaluate( EvaluationContext context, RuleCollection rules )
		{
			Decision decision = Decision.Indeterminate;
			context.Trace( "Evaluating rules..." );
			context.AddIndent();
			try
			{
				foreach( Rule rule in rules )
				{
					decision = rule.Evaluate( context );
					context.TraceContextValues();

					if( decision == Decision.Deny )
					{
						decision = Decision.Deny;
						return decision;
					}
					if( decision == Decision.Permit )
					{
						decision = Decision.Permit;
						return decision;
					}
					if( decision == Decision.NotApplicable )
					{
						continue;
					}
					if( decision == Decision.Indeterminate )
					{
						decision = Decision.Indeterminate;
						return decision;
					}
				}
				return Decision.NotApplicable;
			}
			finally
			{
				context.Trace( "Rule combination algorithm: {0}", decision.ToString() );
				context.RemoveIndent();
			}
		}
Example #36
0
        public Project(ProjectNode root)
        {
            m_Random = root.Serializer.Random;
            m_Rules = new RuleCollection(m_Random);

            foreach (IProjectNode node in root.Children)
            {
                switch (node.NodeType)
                {
                    case ProjectNodeType.TokenSetDeclaration:
                        this.TokenSets.Add(new TokenSet(node, m_Random));
                        break;
                    case ProjectNodeType.RuleDeclaration:
                        this.Rules.Add(new Rule(node as RuleNode));
                        break;
                    case ProjectNodeType.StartingRuleDeclaration:
                        StartingRuleNode srn = node as StartingRuleNode;
                        this.StartRules.Add(srn.Name, srn.Amount);
                        break;
                    case ProjectNodeType.ColumnDeclaration:
                        ColumnNode cn = node as ColumnNode;
                        this.Columns.Add(cn.Title, cn.Expression);
                        break;
                    default:
                        break;
                }
            }

            foreach (Rule r in this.Rules)
            {
                foreach (Whee.WordBuilder.Model.Commands.CommandBase c in r.Commands)
                {
                    c.CheckSanity(this, root.Serializer);
                }
            }
        }
Example #37
0
 public void InitializeNodes()
 {
     LSystem ls = new LSystem();
     RuleCollection rc = new RuleCollection();
     rc.GenerateRules();
     Debug.Log("Size = " + rc.GetCollection().Count);
     int selectedIndex = Random.Range(0, rc.GetCollection().Count);
     LRule r = (LRule)rc.GetCollection()[selectedIndex];
     ls.axiom = r.axiom;
     ls.delta = r.delta;
     // JUST GO THROUGH THE RANDOMLY SELECTED RULE, USE ITS COLLECTION IN THE EXPAND AND INTERPRET
     Debug.Log(r.name);
     ls.expand(r.expandingIterations, r.rules);
     ls.interpret();
 }
Example #38
0
 public Project(IRandom random)
 {
     m_Random = random;
     m_Rules = new RuleCollection(m_Random);
 }
        public ActionResult CreateRule(policyData vData, int linkId)
        {
            vData.PolicyLink = new PolicyLinkEntity(linkId);
            vData.Policy = vData.PolicyLink.Policy;
            vData.Rule = new RuleEntity();
            vData.Rule.Policy = vData.Policy;
            vData.Rule.Condition.Type = constants.conditionType;
            vData.Condition = vData.Rule.Condition;
            vData.Condition.CombineAnd = true;

            RuleCollection maxColl = new RuleCollection();
            PredicateExpression pe = new PredicateExpression(RuleFields.PolicyId == vData.PolicyLink.PolicyId);
            object maxObj = maxColl.GetScalar(RuleFieldIndex.Order, null, AggregateFunction.Max, pe);
            if (maxObj != null && maxObj != DBNull.Value)
                vData.Rule.Order = (int)maxObj + 1;
            else
                vData.Rule.Order = 0;

            EffectCollection ecoll = new EffectCollection();
            ecoll.GetMulti((EffectFields.Name == "permit"));
            vData.Rule.EffectId = ecoll[0].Id;

            vData.Rule.Save(true);

            return RedirectToAction("EditRule", new { id = vData.Rule.Id, linkId = linkId });
        }
        public ActionResult RuleOrder(policyData vData, int id, int linkId, FormCollection collection)
        {
            RuleEntity rule = new RuleEntity(id);
            RuleCollection coll = new RuleCollection();

            PredicateExpression pe = new PredicateExpression(RuleFields.Id != rule.Id);
            pe.Add(RuleFields.PolicyId == rule.PolicyId);
            SortExpression se = null;

            if (collection["up"] != null)
            {
                // Find all categories with display index less than ours.
                pe.Add(RuleFields.Order <= rule.Order);

                // Order by display index, highest first.
                se = new SortExpression(RuleFields.Order | SortOperator.Descending);
            }
            else
            {
                // Find all categories with display index greater than ours.
                pe.Add(RuleFields.Order >= rule.Order);

                // Order by display index, lowest first.
                se = new SortExpression(RuleFields.Order | SortOperator.Ascending);
            }

            // Swap with closest one.
            if (coll.GetMulti(pe, 1, se) && coll.Count > 0)
            {
                int temp = coll[0].Order;
                coll[0].Order = rule.Order;
                rule.Order = temp;

                rule.Save();
                coll.SaveMulti();
            }

            return RedirectToAction("EditPolicy", new { id = linkId });
        }
        /// <summary>
        /// The evaluation implementation in the pseudo-code described in the specification.
        /// </summary>
        /// <param name="context">The evaluation context instance.</param>
        /// <param name="rules">The policies that must be evaluated.</param>
        /// <returns>The final decission for the combination of the rule evaluation.</returns>
        public Decision Evaluate(EvaluationContext context, RuleCollection rules)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (rules == null) throw new ArgumentNullException("rules");
            var decision = Decision.Indeterminate;
            bool atLeastOneError = false;
            bool potentialPermit = false;
            bool atLeastOneDeny = false;

            context.Trace("Evaluating rules...");
            context.AddIndent();
            try
            {
                foreach (Rule rule in rules)
                {
                    decision = rule.Evaluate(context);

                    context.TraceContextValues();

                    if (decision == Decision.Deny)
                    {
                        atLeastOneDeny = true;
                        continue;
                    }
                    if (decision == Decision.Permit)
                    {
                        decision = Decision.Permit;
                        return decision;
                    }
                    if (decision == Decision.NotApplicable)
                    {
                        continue;
                    }
                    if (decision == Decision.Indeterminate)
                    {
                        atLeastOneError = true;
                        if (rule.RuleDefinition.Effect == Effect.Permit)
                        {
                            potentialPermit = true;
                        }
                        continue;
                    }
                }
                if (potentialPermit)
                {
                    decision = Decision.Indeterminate;
                    return decision;
                }
                if (atLeastOneDeny)
                {
                    decision = Decision.Deny;
                    return decision;
                }
                if (atLeastOneError)
                {
                    decision = Decision.Indeterminate;
                    return decision;
                }
                decision = Decision.NotApplicable;
                return decision;
            }
            finally
            {
                context.Trace("Rule combination algorithm: {0}", decision.ToString());
                context.RemoveIndent();
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetInboxRulesResponse"/> class.
 /// </summary>
 internal GetInboxRulesResponse()
     : base()
 {
     this.ruleCollection = new RuleCollection();
 }