public async Task ConfigureFieldRules_should_create_events_and_update_schema_field_rules()
        {
            var command = new ConfigureFieldRules
            {
                FieldRules = new[]
                {
                    new FieldRuleCommand {
                        Field = "field1"
                    }
                }
            };

            await ExecuteCreateAsync();

            var result = await PublishIdempotentAsync(command);

            result.ShouldBeEquivalent(sut.Snapshot);

            Assert.NotEmpty(sut.Snapshot.SchemaDef.FieldRules);

            LastEvents
            .ShouldHaveSameEvents(
                CreateEvent(new SchemaFieldRulesConfigured {
                FieldRules = new FieldRules(FieldRule.Disable("field1"))
            })
                );
        }
示例#2
0
    private bool IsSkipRow(IRow row)
    {
        if (row == null)
        {
            return(true);
        }
        ICell    cell = row.GetCell(0);
        CellType type;
        object   obj = GetValueType(cell, out type);

        if (obj == null)
        {
            return(true);
        }
        string str = obj.ToString();

        if (str == "" || str.StartsWith("//"))
        {
            return(true);
        }
        IColor color = cell.CellStyle.FillForegroundColorColor;

        if (color == null)
        {
            return(false);
        }
        FieldRule rule = GetColorRule(color.RGB);

        if (rule == FieldRule.RULE_ERROR)
        {
            return(true);
        }
        return(false);
    }
示例#3
0
        private static int Parse(IEnumerable <string> input)
        {
            var rules         = new Dictionary <string, FieldRule>();
            var state         = State.Init;
            var invalidFields = new List <int>();

            foreach (var line in input)
            {
                if (line.StartsWith("your ticket:"))
                {
                    state = State.Your;
                }
                else if (line.StartsWith("nearby tickets:"))
                {
                    state = State.Nearby;
                }
                else if (line.Length == 0)
                {
                    // do nothing
                }
                else
                {
                    if (state == State.Init)
                    {
                        // departure location: 45-609 or 616-954
                        var ruleLine = line.Split(":");
                        var name     = ruleLine[0];
                        ruleLine = ruleLine[1].Trim().Split();
                        var r1        = ruleLine[0].Split("-");
                        var range1    = new RuleRange(int.Parse(r1[0]), int.Parse(r1[1]));
                        var r2        = ruleLine[2].Split("-");
                        var range2    = new RuleRange(int.Parse(r2[0]), int.Parse(r2[1]));
                        var fieldRule = new FieldRule(range1, range2);
                        rules[name] = fieldRule;
                    }
                    else if (state == State.Nearby)
                    {
                        var values = line.Split(",").Select(x => int.Parse(x)).ToList();
                        foreach (var value in values)
                        {
                            var isFoundValid = false;
                            foreach (var rule in rules.Values)
                            {
                                if (rule.IsValid(value))
                                {
                                    isFoundValid = true;
                                    break;
                                }
                            }
                            if (!isFoundValid)
                            {
                                invalidFields.Add(value);
                            }
                        }
                    }
                }
            }
            return(invalidFields.Sum());
        }
 public void BeforeEach()
 {
     _notification = new Notification();
     _model = new AddressModel();
     _strategy = new MaximumStringLengthFieldStrategy() { Length = 10 };
     _accessor = AccessorFactory.Create<AddressModel>(m => m.Address1);
     _rule = new FieldRule(_accessor, new TypeResolver(), _strategy);
 }
 public void BeforeEach()
 {
     _notification = new Notification();
     _model = new SimpleModel();
     _strategy = new GreaterThanZeroFieldStrategy();
     _accessor = AccessorFactory.Create<SimpleModel>(m => m.GreaterThanZero);
     _rule = new FieldRule(_accessor, new TypeResolver(), _strategy);
 }
示例#6
0
        public void Should_set_field_rules()
        {
            var schema_1 = schema_0.SetFieldRules(FieldRule.Hide("2"));
            var schema_2 = schema_1.SetFieldRules(FieldRule.Hide("2"));

            Assert.NotEmpty(schema_1.FieldRules);
            Assert.NotEmpty(schema_2.FieldRules);
            Assert.Same(schema_1, schema_2);
        }
示例#7
0
        public void TestConstructSwum()
        {
            string testSrcML = "<class>class <name>foo</name> <block>{<private type=\"default\"><decl_stmt><decl><type><name>int</name></type> <name>a</name></decl>;</decl_stmt></private>}</block>;</class>";
            XElement xml = XElement.Parse(string.Format(srcMLFormat, testSrcML), LoadOptions.PreserveWhitespace);
            FieldContext fc = ContextBuilder.BuildFieldContext(xml.Descendants(SRC.Declaration).First());

            FieldDeclarationNode fdn = new FieldDeclarationNode("a", fc);
            FieldRule rule = new FieldRule(posData, tagger, splitter);
            rule.ConstructSwum(fdn);
            Console.WriteLine(fdn.ToString());
        }
示例#8
0
    public bool ExportLuaFile(string path)
    {
        string        filename = path + this.exportname.ToLower() + ".config";
        StringBuilder sb       = new StringBuilder();

        sb.AppendLine("return {");
        foreach (Dictionary <string, RecordCol> record in this.records)
        {
            if (this.header.Count < 1)
            {
                break;
            }
            string field = this.header[0].name;
            string key   = record[field].val.ToString();
            if (record[field].type != CellType.Numeric)
            {
                key = QuoteStr(key);
            }
            sb.Append("\t[" + key + "] = {");
            for (int i = 0; i < this.header.Count; i++)
            {
                FieldRule rule = this.header[i].rule;
                field = this.header[i].name;
                if (rule == FieldRule.RULE_COMMON || rule == FieldRule.RULE_SERVER)
                {
                    object val = record[field].val;
                    string str = "nil";
                    if (val != null)
                    {
                        if (IsTable(val.ToString()))
                        {
                            str = ConvertLuaTable(val.ToString());
                        }
                        else if (record[field].type == CellType.Boolean)
                        {
                            str = val.ToString().ToLower();
                        }
                        else
                        {
                            str = QuoteStr(val.ToString());
                        }
                    }
                    /// float int
                    sb.Append(" " + field + " = " + str + ",");
                }
            }
            sb.AppendLine(" },");
        }
        sb.AppendLine("}");
        File.WriteAllBytes(filename, Encoding.UTF8.GetBytes(sb.ToString()));
        return(true);
    }
示例#9
0
        public void Should_create_events_if_field_rules_changed_changed()
        {
            var sourceSchema =
                new Schema("source")
                .SetFieldRules(FieldRule.Hide("2"));

            var targetSchema =
                new Schema("target")
                .SetFieldRules(FieldRule.Hide("1"));

            var events = sourceSchema.Synchronize(targetSchema, idGenerator);

            events.ShouldHaveSameEvents(
                new SchemaFieldRulesConfigured {
                FieldRules = FieldRules.Create(FieldRule.Hide("1"))
            }
                );
        }
        public void Create([FromBody] SubPrivacyPolicyInsertCommand command)
        {
            bool IsResourceRequired = true;

            var fieldRules = new List <FieldRule>();

            foreach (var rule in command.Rules)
            {
                var condition = _conditionalExpressionService.Parse(rule.Condition);
                var fieldRule = new FieldRule()
                {
                    Identifer    = rule.RuleID,
                    FieldEffects = rule.FieldEffects,
                    Condition    = condition
                };
                fieldRules.Add(fieldRule);

                if (!IsResourceRequired)
                {
                    IsResourceRequired = rule.Condition.Contains("\"Resource.");
                }
            }

            var policy = new PrivacyPolicy()
            {
                CollectionName = command.CollectionName,
                Description    = command.Description,
                Id             = command.PolicyID,
                Rules          = fieldRules,
                IsAttributeResourceRequired = IsResourceRequired
            };

            _privacyPolicyRepository.Add(policy);

            var priorty = new PriorityFunction()
            {
                Name = command.PolicyID, Priority = command.Priority
            };

            _privacyDomainRepository.AddPriorityFunctions(command.DomainName, priorty);
        }
示例#11
0
        public void Create([FromBody] PrivacyPolicyInsertCommand command)
        {
            bool IsResourceRequired = false;

            if (command.Target.Contains("\"Resource."))
            {
                IsResourceRequired = true;
            }

            var fieldRules = new List <FieldRule>();
            var target     = _conditionalExpressionService.Parse(command.Target);

            foreach (var rule in command.Rules)
            {
                var condition = _conditionalExpressionService.Parse(rule.Condition);
                var fieldRule = new FieldRule()
                {
                    Identifer    = rule.RuleID,
                    FieldEffects = rule.FieldEffects,
                    Condition    = condition
                };
                fieldRules.Add(fieldRule);

                if (!IsResourceRequired)
                {
                    IsResourceRequired = rule.Condition.Contains("\"Resource.");
                }
            }

            var policy = new PrivacyPolicy()
            {
                CollectionName = command.CollectionName,
                Description    = command.Description,
                PolicyId       = command.PolicyID,
                Rules          = fieldRules,
                IsAttributeResourceRequired = IsResourceRequired,
                Target = target
            };

            _privacyPolicyRepository.Add(policy);
        }
示例#12
0
        public void Should_serialize_and_deserialize_schema()
        {
            var schemaSource =
                TestUtils.MixedSchema(SchemaType.Singleton).Schema
                .ChangeCategory("Category")
                .SetFieldRules(FieldRule.Hide("2"))
                .SetFieldsInLists("field2")
                .SetFieldsInReferences("field1")
                .SetScripts(new SchemaScripts
            {
                Create = "<create-script>"
            })
                .SetPreviewUrls(new Dictionary <string, string>
            {
                ["web"] = "Url"
            }.ToReadonlyDictionary());

            var schemaTarget = schemaSource.SerializeAndDeserialize();

            schemaTarget.Should().BeEquivalentTo(schemaSource);
        }
示例#13
0
        public void FieldRule_IsValidValue_Tests()
        {
            var sut = new FieldRule("test", new[]
            {
                new Range(1, 3),
                new Range(5, 7)
            });

            // ASSERT
            sut.IsValidValue(1).Should().BeTrue();
            sut.IsValidValue(2).Should().BeTrue();
            sut.IsValidValue(3).Should().BeTrue();

            sut.IsValidValue(5).Should().BeTrue();
            sut.IsValidValue(6).Should().BeTrue();
            sut.IsValidValue(7).Should().BeTrue();

            sut.IsValidValue(4).Should().BeFalse();
            sut.IsValidValue(0).Should().BeFalse();
            sut.IsValidValue(8).Should().BeFalse();
            sut.IsValidValue(100).Should().BeFalse();
        }
示例#14
0
 private void ProcessHead(IRow head)
 {
     this.header.Clear();
     for (int i = head.FirstCellNum; i < head.LastCellNum; i++)
     {
         ICell    cell = head.GetCell(i);
         CellType type;
         object   obj = GetValueType(cell, out type);
         if (obj != null)
         {
             IColor    color = cell.CellStyle.FillForegroundColorColor;
             FieldRule rule  = GetColorRule(color.RGB);
             string    name  = obj.ToString();
             if (name != "" && color != null && rule != FieldRule.RULE_IGNORE && rule != FieldRule.RULE_ERROR)
             {
                 HeadeCol col = new HeadeCol();
                 col.index = i;
                 col.rule  = rule;
                 col.name  = name;
                 this.header.Add(col);
             }
         }
     }
 }
 /// <summary>Конструктор</summary>
 /// <param name="nOwner">значение</param>
 public MyFieldPropertyDescriptor(FieldValue nOwner) : base(nOwner.Rule.FName, null)
 {
     _owner = nOwner;
     _rule  = _owner.Rule;
 }
示例#16
0
        public static FormValidateModels FieldsRuleSetup(this HtmlHelper h, String f, FieldRule r, FieldMessage m, Dictionary <String, String> xr)
        {
            FormValidateModels o = new FormValidateModels()
            {
                fieldName = f
            };

            if (r != null)
            {
                o.rules = r;
            }
            if (m != null)
            {
                o.messages = m;
            }
            if (xr != null)
            {
                o.ExtraRule = xr;
            }

            return(o);
        }
示例#17
0
 public static FormValidateModels FieldsRuleSetup <TModel, TProperty>(this HtmlHelper <TModel> h,
                                                                      Expression <Func <TModel, TProperty> > e,
                                                                      FieldRule r, FieldMessage m, Dictionary <String, String> xr)
 {
     return(FieldsRuleSetup(h, ExpressionHelper.GetExpressionText(e), r, m, xr));
 }
示例#18
0
        private static long Parse2(IEnumerable <string> input)
        {
            var rules         = new Dictionary <string, FieldRule>();
            var state         = State.Init;
            var invalidFields = new List <int>();
            var myTicket      = new List <int>();
            var validTickets  = new List <List <int> >();

            foreach (var line in input)
            {
                if (line.StartsWith("your ticket:"))
                {
                    state = State.Your;
                }
                else if (line.StartsWith("nearby tickets:"))
                {
                    state = State.Nearby;
                }
                else if (line.Length == 0)
                {
                    // do nothing
                }
                else
                {
                    if (state == State.Init)
                    {
                        // departure location: 45-609 or 616-954
                        var ruleLine = line.Split(":");
                        var name     = ruleLine[0];
                        ruleLine = ruleLine[1].Trim().Split();
                        var r1        = ruleLine[0].Split("-");
                        var range1    = new RuleRange(int.Parse(r1[0]), int.Parse(r1[1]));
                        var r2        = ruleLine[2].Split("-");
                        var range2    = new RuleRange(int.Parse(r2[0]), int.Parse(r2[1]));
                        var fieldRule = new FieldRule(range1, range2);
                        rules[name] = fieldRule;
                    }
                    else if (state == State.Your)
                    {
                        myTicket = line.Split(",").Select(x => int.Parse(x)).ToList();
                    }
                    else if (state == State.Nearby)
                    {
                        var values     = line.Split(",").Select(x => int.Parse(x)).ToList();
                        int validCount = 0;
                        foreach (var value in values)
                        {
                            var isFoundValid = false;
                            foreach (var rule in rules.Values)
                            {
                                if (rule.IsValid(value))
                                {
                                    isFoundValid = true;
                                    break;
                                }
                            }
                            if (!isFoundValid)
                            {
                                invalidFields.Add(value);
                            }
                            else
                            {
                                validCount++;
                            }
                        }
                        if (validCount == values.Count)
                        {
                            validTickets.Add(values);
                        }
                    }
                }
            }
            var validRules = new List <List <string> >();

            for (int i = 0; i < myTicket.Count; i++)
            {
                validRules.Add(rules.Keys.ToList());
            }

            // Remove all invalid
            foreach (var ticket in validTickets)
            {
                for (int i = 0; i < validRules.Count; i++)
                {
                    var remove = new HashSet <string>();
                    foreach (var ruleKV in rules)
                    {
                        if (!ruleKV.Value.IsValid(ticket[i]))
                        {
                            remove.Add(ruleKV.Key);
                        }
                    }
                    foreach (var r in remove)
                    {
                        if (validRules[i].Contains(r))
                        {
                            validRules[i].Remove(r);
                        }
                    }
                }
            }

            var finalRules = new string[validRules.Count];

            // Exclude
            bool loop = true;

            while (loop)
            {
                loop = false;
                for (int i = 0; i < validRules.Count; i++)
                {
                    if (finalRules[i] == null && validRules[i].Count == 1)
                    {
                        // remove from all other
                        for (int j = 0; j < validRules.Count; j++)
                        {
                            if (i != j)
                            {
                                validRules[j].Remove(validRules[i].First());
                                loop = true;
                            }
                        }
                        finalRules[i] = validRules[i].First();
                    }
                }
            }
            var prod = 1L;

            for (int i = 0; i < finalRules.Length; i++)
            {
                if (finalRules[i].StartsWith("departure"))
                {
                    prod *= myTicket[i];
                }
            }

            return(prod);
        }
示例#19
0
    public bool ExportServerCsvFile(string path)
    {
        bool result   = false;
        bool isDelete = true;

        string filename = path + this.exportname.ToLower() + ".csv";

        using (StreamWriter writer = new StreamWriter(filename, false, Encoding.Unicode))
        {
            bool isFirstCol = true;
            for (int i = 0; i < this.header.Count; i++)
            {
                FieldRule rule = this.header[i].rule;
                if (rule == FieldRule.RULE_SERVER || rule == FieldRule.RULE_COMMON)
                {
                    if (!isFirstCol)
                    {
                        writer.Write("\t");
                    }
                    isFirstCol = false;
                    writer.Write(this.header[i].name);
                }
            }
            writer.WriteLine();

            int index = 0;

            foreach (Dictionary <string, RecordCol> record in this.records)
            {
                index++;
                if (index <= 2)
                {
                    continue;
                }

                isFirstCol = true;
                for (int i = 0; i < this.header.Count; i++)
                {
                    FieldRule rule  = this.header[i].rule;
                    string    field = this.header[i].name;
                    if (rule == FieldRule.RULE_COMMON || rule == FieldRule.RULE_SERVER)
                    {
                        object val = record[field].val;
                        string str = "";
                        if (val != null)
                        {
                            str = val.ToString();
                        }
                        //                            if (IsTable(val.ToString()))
                        //                                str = Table2String(val.ToString());
                        //                            else
                        //                                str = val.ToString();
                        if (!isFirstCol)
                        {
                            writer.Write("\t");
                        }
                        isFirstCol = false;
                        isDelete   = false;
                        writer.Write(str);
                    }
                }
                writer.WriteLine();
            }

            if (isDelete == false)
            {
                Console.WriteLine("后端配置 {0}.csv 导出成功~", exportname.ToLower());
            }
            else
            {
                Console.WriteLine("后端配置 {0}.csv 不需要导出", exportname.ToLower());
            }

            result = true;
        }

        if (isDelete && File.Exists(filename))
        {
            File.Delete(filename);
        }

        return(result);
    }
示例#20
0
        private IRuleMapper <T> Init <T>(IRuleMapper <T> ruleMapper = null) where T : DbObject, new()
        {
            Func <object, object> item  = null;
            Func <object, object> func4 = null;
            Func <object, object> func5 = null;
            Func <object, bool>   func6 = null;

            ruleMapper = ruleMapper ?? new RuleEngine <T>();
            Type type = typeof(T);

            foreach (PropertyInfo info1 in type.GetProperties())
            {
                Func <object, object>         func  = null;
                Func <object, object>         func2 = null;
                List <Func <object, object> > funcs;
                MethodInfo          getMethod;
                string              fieldName;
                DynamicPropertyInfo info = DbObjectTools.GetDynamicPropertyInfo(type, info1);
                if (info != null)
                {
                    Type propertyType = info.PropertyType;
                    funcs = new List <Func <object, object> >();
                    if (!info.AllowDBNull)
                    {
                        if (item == null)
                        {
                            item = o => ValidateExtend.NotNull <object>(o);
                        }
                        funcs.Add(item);
                    }
                    if ((propertyType == typeof(string)) && (info.Length > 0))
                    {
                        if (func == null)
                        {
                            func = delegate(object o)
                            {
                                if (o != null)
                                {
                                    ValidateExtend.LengthBelowOrEqual((string)o, info.Length, false);
                                }
                                return(o);
                            };
                        }
                        funcs.Add(func);
                    }
                    if (((propertyType != typeof(DateTime)) && (propertyType != typeof(DateTime?))) && ((info.NumericPercision != -1) || (info.NumericScale != -1)))
                    {
                        if (func2 == null)
                        {
                            func2 = delegate(object o)
                            {
                                if (o != null)
                                {
                                    ValidateExtend.IsDecimal <object>(o, info.NumericPercision, info.NumericScale);
                                }
                                return(o);
                            };
                        }
                        funcs.Add(func2);
                    }
                    if (propertyType == typeof(DateTime))
                    {
                        if (func4 == null)
                        {
                            func4 = delegate(object o)
                            {
                                if (o != null)
                                {
                                    ValidateExtend.GreaterThanOrEqual <DateTime>((DateTime)o, SqlDateTime.MinValue.Value);
                                }
                                return(o);
                            };
                        }
                        funcs.Add(func4);
                    }
                    if (propertyType == typeof(DateTime?))
                    {
                        if (func5 == null)
                        {
                            func5 = delegate(object o)
                            {
                                if (o != null)
                                {
                                    DateTime?nullable = (DateTime?)o;
                                    ValidateExtend.GreaterThanOrEqual <DateTime>(nullable.Value, SqlDateTime.MinValue.Value);
                                }
                                return(o);
                            };
                        }
                        funcs.Add(func5);
                    }
                    List <FieldRule> list = null;
                    if (!ruleMapper.FieldRules.TryGetValue(info1.Name, out list))
                    {
                        list = new List <FieldRule>();
                        ruleMapper.FieldRules.Add(info1.Name, list);
                    }
                    getMethod = info1.GetGetMethod();
                    fieldName = info1.Name;
                    FieldRule rule2 = new FieldRule();
                    rule2.GetField = (t => getMethod.Invoke(t, null));
                    rule2.Validate = (delegate(object o, string action)
                    {
                        Action <Func <object, object> > action2 = null;
                        object obj2;
                        try
                        {
                            if (action2 == null)
                            {
                                action2 = delegate(Func <object, object> f)
                                {
                                    f(o);
                                };
                            }
                            funcs.ForEach(action2);
                            obj2 = o;
                        }
                        catch (ValidateException exception)
                        {
                            throw new FieldValidateException(exception.Message, fieldName, exception.FieldValue);
                        }
                        return(obj2);
                    });
                    rule2.Actions = (new string[] { DbOperation.Create.ToString(), (DbOperation.None | DbOperation.Update).ToString() });
                    if (func6 == null)
                    {
                        func6 = t => true;
                    }
                    rule2.When = (func6);
                    FieldRule rule = rule2;
                    list.Insert(0, rule);
                }
            }
            return(ruleMapper);
        }
示例#21
0
 public void TestToString()
 {
     FieldRule rule = new FieldRule(null, null, null);
     Console.WriteLine(rule.ToString());
 }
示例#22
0
 public static FieldRuleDto FromDomain(FieldRule fieldRule)
 {
     return(SimpleMapper.Map(fieldRule, new FieldRuleDto()));
 }
 /// <summary></summary>
 /// <param name="rule"></param>
 /// <returns></returns>
 public string GetValue(FieldRule rule)
 {
     return(_owner.FieldList.FirstOrDefault(f => f.Rule.FName == rule.FName)?.GetString());
 }
 /// <summary></summary>
 /// <param name="nOwnerRule"></param>
 public MyFieldPropertyDescriptor(FieldRule nOwnerRule) : base(nOwnerRule.FName, null)
 {
     _rule = nOwnerRule;
 }