/// <summary>
        /// Generate SonarQube specifc rules based on Roslyn based diagnostics
        /// </summary>
        public Rules GenerateRules(IEnumerable<DiagnosticAnalyzer> analyzers)
        {
            if (analyzers == null)
            {
                throw new ArgumentNullException("analyzers");
            }

            Rules rules = new Rules();

            foreach (DiagnosticAnalyzer analyzer in analyzers)
            {
                Rules analyzerRules = GetAnalyzerRules(analyzer);
                
                foreach (Rule analyzerRule in analyzerRules)
                {
                    if (rules.Any(r => String.Equals(r.Key, analyzerRule.Key, Rule.RuleKeyComparer)))
                    {
                        logger.LogWarning(UIResources.RuleGen_DuplicateKey, analyzerRule.Key);
                        continue;
                    }

                    rules.Add(analyzerRule);
                }
            }
            
            return rules;
        }
        public void SerializeRules()
        {
            Rules rules = new Rules();

            rules.Add(new Rule()
            {
                Key         = "key1",
                InternalKey = "internalKey1",
                Name        = "Rule1",
                Description = "description 1",
                Severity    = "CRITICAL",
                Cardinality = "SINGLE",
                Status      = "READY",
                Tags        = new[] { "t1", "t2" }
            });

            rules.Add(new Rule()
            {
                Key         = "key2",
                InternalKey = "internalKey2",
                Name        = "Rule2",
                Description = @"<p>An Html <a href=""www.bing.com""> Description",
                Severity    = "MAJOR",
                Cardinality = "SINGLE",
                Status      = "READY",
            });

            string testDir   = TestUtils.CreateTestDirectory(this.TestContext);
            string rulesFile = Path.Combine(testDir, "rules.xml");

            rules.Save(rulesFile, new TestLogger());
            this.TestContext.AddResultFile(rulesFile);

            Assert.IsTrue(File.Exists(rulesFile), "Expected rules file does not exist: {0}", rulesFile);
            Rules reloaded = Rules.Load(rulesFile);

            string expectedXmlContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
<rules xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <rule>
    <key>key1</key>
    <name>Rule1</name>
    <internalKey>internalKey1</internalKey>
    <description><![CDATA[description 1]]></description>
    <severity>CRITICAL</severity>
    <cardinality>SINGLE</cardinality>
    <status>READY</status>
    <tag>t1</tag>
    <tag>t2</tag>
  </rule>
  <rule>
    <key>key2</key>
    <name>Rule2</name>
    <internalKey>internalKey2</internalKey>
    <description><![CDATA[<p>An Html <a href=""www.bing.com""> Description]]></description>
    <severity>MAJOR</severity>
    <cardinality>SINGLE</cardinality>
    <status>READY</status>
  </rule>
</rules>";

            // Save the expected XML to make comparisons using diff tools easier
            string expectedFilePath = TestUtils.CreateTextFile("expected.xml", testDir, expectedXmlContent);

            this.TestContext.AddResultFile(expectedFilePath);

            // Compare the serialized output
            string actualXmlContent = File.ReadAllText(rulesFile);

            Assert.AreEqual(expectedXmlContent, actualXmlContent, "Unexpected XML content");

            // Check the rule descriptions were decoded correctly
            Assert.AreEqual("description 1", reloaded[0].Description, "Description was not deserialized correctly");
            Assert.AreEqual(@"<p>An Html <a href=""www.bing.com""> Description", reloaded[1].Description, "Description was not deserialized correctly");
        }
Example #3
0
 public ClassBuilder <T> Dictionary <TK>(Func <T, TK> func, IDictionary <TK, string> dictionary)
 {
     Rules.Add(new ClassBuilderRuleDictionary <T, TK>(func, dictionary));
     return(this);
 }
Example #4
0
 public ClassBuilder <T> Get(Func <T, string> func)
 {
     Rules.Add(new ClassBuilderRuleGet <T>(func));
     return(this);
 }
Example #5
0
 public RenameObjectDTO(string name)
 {
     Rules.Add(RenameObjectDTORules.NameShouldNotBeTheSame);
     OriginalName = name;
     Name         = name;
 }
 public BishopRuleGroup()
 {
     Rules.Add(new CanOnlyTakeEnnemyRule());
     Rules.Add(new BishopMovementRule());
     Rules.Add(new WillNotMakeCheck());
 }
Example #7
0
 // constructors
 public BlackjackGame()
 {
     Name = "Blackjack";
     Rules.Add("Get 21 to win!");
     Type = "Card";
 }
Example #8
0
 public InitiatorRuleSet() : base()
 {
     Rules.Add(new NominatorSameAsInitiatorRule());
     Rules.Add(new NominatorDifferentThanInitiatorRule());
 }
 private void InitializeValidation( )
 {
     Rules.Add(new ValidationRule(nameof(OutputFolder), "Output Folder can not be empty!", () => string.IsNullOrEmpty(OutputFolder)));
     Rules.Add(new ValidationRule(nameof(OutputFolder), "Output Folder is not a valid Folder!", () => !Directory.Exists(OutputFolder)));
     Rules.Add(new ValidationRule(nameof(SelectedMmDeviceId), "Recording Device must be selected!", () => string.IsNullOrEmpty(SelectedMmDeviceId)));
 }
Example #10
0
 /// <summary>
 ///   Determines whether [is within date range].
 /// </summary>
 private void ConfigureRules()
 {
     Rules.Add(new MinValue <T>("MinValue", "The value must be equal to or greater than start range value.", target, startRange));
     Rules.Add(new MaxValue <T>("MinValue", "The value must be equal to or less than end range value.", target, endRange));
 }
Example #11
0
 public void AddRule(Rule rule)
 {
     Rules.Add(rule);
 }
Example #12
0
 public void AddNewRule(string inputString, string replacement) =>
 Rules.Add(new Pattern()
 {
     Input       = inputString,
     Replacement = replacement
 });
Example #13
0
 public void AddRule <TK>() where TK : IGeneralRule <T> => Rules.Add(typeof(TK));
        private Rules GetAnalyzerRules(DiagnosticAnalyzer analyzer)
        {
            // For info on SonarQube rules see http://docs.sonarqube.org/display/SONAR/Rules

            Rules rules = new Rules();

            foreach (DiagnosticDescriptor diagnostic in analyzer.SupportedDiagnostics)
            {
                if (String.IsNullOrWhiteSpace(diagnostic.Id))
                {
                    logger.LogWarning(UIResources.RuleGen_EmptyKey, analyzer.ToString());
                    continue;
                }

                Rule newRule = new Rule();
                
                newRule.Key = diagnostic.Id;
                newRule.InternalKey = diagnostic.Id;

                newRule.Description = GetDescriptionAsRawHtml(diagnostic);

                newRule.Name = diagnostic.Title.ToString(CultureInfo.InvariantCulture);
                newRule.Severity = GetSonarQubeSeverity(diagnostic.DefaultSeverity);

                // Rule XML properties that don't have an obvious Diagnostic equivalent:
                newRule.Cardinality = Cardinality;
                newRule.Status = Status;

                // Diagnostic properties that don't have an obvious Rule xml equivalent:
                //  diagnostic.Category
                //  diagnostic.IsEnabledByDefault
                //  diagnostic.MessageFormat

                /* Remark: Custom tags are used so that Visual Studio handles diagnostics and are not equivalent to SonarQube's tags
                *
                * http://stackoverflow.com/questions/24257222/relevance-of-new-parameters-for-diagnosticdescriptor-constructor
                * customTags is a general way to mark that a diagnostic should be treated or displayed somewhat 
                * different than normal diagnostics. The "unnecessary" tag means that in the IDE we fade out the span 
                * that the diagnostic applies to: this is how we fade out unnecessary usings or casts or such in the IDE. 
                * In some fancy scenarios you might want to define your own, but for the most part you'll either leave that empty 
                * or pass Unnecessary if you want the different UI handling. 
                * The EditAndContinue tag is for errors that are created if an edit-and-continue edit can't be applied 
                * (which are also displayed somewhat differently)...that's just for us (n.b. Roslyn) to use.
                */

                rules.Add(newRule);
            }
            return rules;
        }
Example #15
0
 public static void AddSyntaxRule(Delegate predicate, params string[] words)
 {
     Rules.Add(new ParserRule(predicate, words));
 }
Example #16
0
 public ChannelResource AddRule(ChannelVersionRuleResource rule)
 {
     Rules.Add(rule);
     return(this);
 }
Example #17
0
		/// <summary>
		///     Parses the rules' patterns.
		/// </summary>
		/// <param name="proj">The project.</param>
		/// <param name="module">The module description.</param>
		/// <param name="context">The working context.</param>
		/// <returns>Parsed rule patterns.</returns>
		/// <exception cref="System.ArgumentException">
		///     One of the rules has invalid pattern.
		/// </exception>
		protected Rules ParseRules(ConfuserProject proj, ProjectModule module, ConfuserContext context) {
			var ret = new Rules();
			var parser = new PatternParser();
			foreach (Rule rule in proj.Rules.Concat(module.Rules)) {
				try {
					ret.Add(rule, parser.Parse(rule.Pattern));
				}
				catch (InvalidPatternException ex) {
					context.Logger.ErrorFormat("Invalid rule pattern: " + rule.Pattern + ".", ex);
					throw new ConfuserException(ex);
				}
				foreach (var setting in rule) {
					if (!protections.ContainsKey(setting.Id)) {
						context.Logger.ErrorFormat("Cannot find protection with ID '{0}'.", setting.Id);
						throw new ConfuserException(null);
					}
				}
			}
			return ret;
		}
Example #18
0
 public OutputIntervalDTO()
 {
     Rules.Add(startTimeLessThanEndTime);
     Rules.Add(endTimeGreaterThanStartTime);
 }
Example #19
0
        public override void InitializeRules()
        {
            // white pawn rules
            Rules.Add(new Rule(
                          m => Color == ChessColor.White,
                          m => !m.WithEat,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY + 1
                          ));

            Rules.Add(new Rule(
                          m => Color == ChessColor.White,
                          m => !m.WithEat,
                          m => m.StartY == 1,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY + 2
                          ));

            Rules.Add(new Rule(
                          m => Color == ChessColor.White,
                          m => m.WithEat,
                          m => m.EndX == m.StartX + 1,
                          m => m.EndY == m.StartY + 1
                          ));

            Rules.Add(new Rule(
                          m => Color == ChessColor.White,
                          m => m.WithEat,
                          m => m.EndX == m.StartX - 1,
                          m => m.EndY == m.StartY + 1
                          ));


            // black pawn rules
            Rules.Add(new Rule(
                          m => Color == ChessColor.Black,
                          m => !m.WithEat,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY - 1
                          ));

            Rules.Add(new Rule(
                          m => Color == ChessColor.Black,
                          m => !m.WithEat,
                          m => m.StartY == 6,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY - 2
                          ));

            Rules.Add(new Rule(
                          m => Color == ChessColor.Black,
                          m => m.WithEat,
                          m => m.EndX == m.StartX + 1,
                          m => m.EndY == m.StartY - 1
                          ));

            Rules.Add(new Rule(
                          m => Color == ChessColor.Black,
                          m => m.WithEat,
                          m => m.EndX == m.StartX - 1,
                          m => m.EndY == m.StartY - 1
                          ));
        }
Example #20
0
        public override void ReadRules(string filepath)
        {
            //Regex for finding rules
            Regex regexRulesStart     = new Regex(@"class [a-zA-z]+ IF : .*");
            Regex regexClassification = new Regex(@"(?<=class\s).*(?=\sIF)");
            Regex regexRuleItem       = new Regex(@"([A-Za-z() _-]+)(=|<|>|<=|>=)([0-9](\.[0-9]))");

            using (StreamReader sr = new StreamReader(filepath))
            {
                string currentLine;
                int    currentRule = 0;
                while ((currentLine = sr.ReadLine()) != null)
                {
                    if (regexRulesStart.Match(currentLine).Success)
                    {
                        Rules.Add(new Rule());
                        Rules[currentRule].SetClassification(regexClassification.Match(currentLine).ToString());

                        //Regex for getting elemnts of rules
                        Regex featureMatch  = new Regex(pattern: @"([A-Za-z]+((( )|\.|-)*)?([(a-zA-Z)]|[0-9]*)?(( )|\.|-)?)+");
                        Regex operatorMatch = new Regex(pattern: @"<=|>=|<|>|=");
                        Regex valueMatch    = new Regex(pattern: @"[0-9]+\.[0-9]+");

                        //splitting up rule items, remove initial class text
                        string[] ruleItems = currentLine.Split('^');
                        ruleItems[0] = Regex.Replace(ruleItems[0], @"class [a-zA-Z]+ IF : ", "").TrimStart();

                        foreach (var item in ruleItems)
                        {
                            MatchCollection ruleItemOperatorMatches = operatorMatch.Matches(item);
                            MatchCollection ruleItemValueMatches    = valueMatch.Matches(item);
                            string          op1 = ruleItemOperatorMatches[0].ToString();
                            string          op2 = "";

                            if (ruleItemOperatorMatches.Count == 2 && ruleItemValueMatches.Count == 2)
                            {
                                op2 = ruleItemOperatorMatches[1].ToString();

                                if (ruleItemOperatorMatches[0].ToString() == "<=" || ruleItemOperatorMatches[0].ToString() == ">=")
                                {
                                    op1 = ruleItemOperatorMatches[0].ToString().Replace('<', '>');
                                }
                            }

                            string   feature  = featureMatch.Match(item).ToString();
                            RuleItem ruleItem = new RuleItem(feature);

                            double value = Convert.ToDouble(ruleItemValueMatches[0].ToString());
                            ruleItem.SetValue(value);
                            if (ruleItemValueMatches.Count > 1)
                            {
                                double value2 = Convert.ToDouble(ruleItemValueMatches[1].ToString());
                                ruleItem.SetValue(value2);
                            }
                            ruleItem.SetOp(op1);
                            if (ruleItemOperatorMatches.Count > 1)
                            {
                                ruleItem.SetOp(op2);
                            }

                            Rules[currentRule].RuleItems.Add(ruleItem);
                        }
                        currentRule++;
                    }
                }
                sr.Close();
            }
        }
Example #21
0
        public override void InitializeRules()
        {
            // white pawn rules
            Rules.Add(new Rule(
                          m => Color == 'W',
                          m => !m.WithCaputure,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY + 1
                          ));

            Rules.Add(new Rule(
                          m => Color == 'W',
                          m => !m.WithCaputure,
                          m => m.StartY == 1,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY + 2
                          ));

            Rules.Add(new Rule(
                          m => Color == 'W',
                          m => m.WithCaputure,
                          m => m.EndX == m.StartX + 1,
                          m => m.EndY == m.StartY + 1
                          ));

            Rules.Add(new Rule(
                          m => Color == 'W',
                          m => m.WithCaputure,
                          m => m.EndX == m.StartX - 1,
                          m => m.EndY == m.StartY + 1
                          ));


            // black pawn rules
            Rules.Add(new Rule(
                          m => Color == 'B',
                          m => !m.WithCaputure,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY - 1
                          ));

            Rules.Add(new Rule(
                          m => Color == 'B',
                          m => !m.WithCaputure,
                          m => m.StartY == 6,
                          m => m.EndX == m.StartX,
                          m => m.EndY == m.StartY - 2
                          ));

            Rules.Add(new Rule(
                          m => Color == 'B',
                          m => m.WithCaputure,
                          m => m.EndX == m.StartX + 1,
                          m => m.EndY == m.StartY - 1
                          ));

            Rules.Add(new Rule(
                          m => Color == 'B',
                          m => m.WithCaputure,
                          m => m.EndX == m.StartX - 1,
                          m => m.EndY == m.StartY - 1
                          ));
        }
Example #22
0
 public void AddRule(IChannelRule rule)
 {
     Rules.Add(rule);
 }
Example #23
0
 public PawnRuleGroup()
 {
     Rules.Add(new PawnMovementRule());
     Rules.Add(new CanOnlyTakeEnnemyRule());
     Rules.Add(new WillNotMakeCheck());
 }
Example #24
0
 public override void EnterParserRuleSpec([NotNull] ANTLRv4Parser.ParserRuleSpecContext context)
 {
     Rules.Add(context.RULE_REF().GetText());
     _parser = true;
 }
Example #25
0
 public ClassBuilder <T> If(string className, Func <T, bool> func)
 {
     Rules.Add(new ClassBuilderRuleIf <T>(className, func));
     return(this);
 }
Example #26
0
 public ApplicationBuilderDTO()
 {
     Rules.Add(moleuleNameShouldBePresentInProjectRule());
 }
Example #27
0
 public ClassBuilder <T> Class(string className)
 {
     Rules.Add(new ClassBuilderRuleClass <T>(className));
     return(this);
 }
Example #28
0
 public When_ And(Rule rule)
 {
     Rules.Add(rule);
     return(this);
 }
Example #29
0
 public virtual void AddRule(RuleBase <TInstance> rule)
 {
     Rules.Add(rule);
 }
Example #30
0
 public CoinflipGame()
 {
     Name = "Coinflip";
     Rules.Add("You must pick a side.");
     Type = "Coin";
 }
Example #31
0
        /// <summary>
        ///     Loads the project from specified XML document.
        /// </summary>
        /// <param name="doc">The XML document storing the project.</param>
        /// <exception cref="Confuser.Core.Project.ProjectValidationException">
        ///     The project XML contains schema errors.
        /// </exception>
        public void Load(XmlDocument doc)
        {
            doc.Schemas.Add(Schema);
            var exceptions = new List <XmlSchemaException>();

            doc.Validate((sender, e) => {
                if (e.Severity != XmlSeverityType.Error)
                {
                    return;
                }
                exceptions.Add(e.Exception);
            });
            if (exceptions.Count > 0)
            {
                throw new ProjectValidationException(exceptions);
            }

            XmlElement docElem = doc.DocumentElement;

            OutputDirectory = docElem.Attributes["outputDir"].Value;
            BaseDirectory   = docElem.Attributes["baseDir"].Value;

            if (docElem.Attributes["seed"] != null)
            {
                Seed = docElem.Attributes["seed"].Value.NullIfEmpty();
            }
            else
            {
                Seed = null;
            }

            if (docElem.Attributes["debug"] != null)
            {
                Debug = bool.Parse(docElem.Attributes["debug"].Value);
            }
            else
            {
                Debug = false;
            }

            Packer = null;
            Clear();
            ProbePaths.Clear();
            PluginPaths.Clear();
            Rules.Clear();
            foreach (XmlElement i in docElem.ChildNodes.OfType <XmlElement>())
            {
                if (i.Name == "rule")
                {
                    var rule = new Rule();
                    rule.Load(i);
                    Rules.Add(rule);
                }
                else if (i.Name == "packer")
                {
                    Packer = new SettingItem <Packer>();
                    Packer.Load(i);
                }
                else if (i.Name == "probePath")
                {
                    ProbePaths.Add(i.InnerText);
                }
                else if (i.Name == "plugin")
                {
                    PluginPaths.Add(i.InnerText);
                }
                else
                {
                    var asm = new ProjectModule();
                    asm.Load(i);
                    Add(asm);
                }
            }
        }
 public CFRule AddRule(CFRule rule)
 {
     Rules.Add(rule);
     return(rule);
 }
        public void SerializeRules()
        {
            Rules rules = new Rules();

            rules.Add(new Rule()
            {
                Key = "key1",
                InternalKey = "internalKey1",
                Name = "Rule1",
                Description= "description 1",
                Severity = "CRITICAL",
                Cardinality = "SINGLE",
                Status = "READY",
                Tags = new[] { "t1", "t2" }  
            });

            rules.Add(new Rule()
            {
                Key = "key2",
                InternalKey = "internalKey2",
                Name = "Rule2",
                Description = @"<p>An Html <a href=""www.bing.com""> Description",
                Severity = "MAJOR",
                Cardinality = "SINGLE",
                Status = "READY",
            });

            string testDir = TestUtils.CreateTestDirectory(this.TestContext);
            string rulesFile = Path.Combine(testDir, "rules.xml");

            rules.Save(rulesFile, new TestLogger());
            this.TestContext.AddResultFile(rulesFile);

            Assert.IsTrue(File.Exists(rulesFile), "Expected rules file does not exist: {0}", rulesFile);
            Rules reloaded = Rules.Load(rulesFile);

            string expectedXmlContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
<rules xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <rule>
    <key>key1</key>
    <name>Rule1</name>
    <internalKey>internalKey1</internalKey>
    <description><![CDATA[description 1]]></description>
    <severity>CRITICAL</severity>
    <cardinality>SINGLE</cardinality>
    <status>READY</status>
    <tag>t1</tag>
    <tag>t2</tag>
  </rule>
  <rule>
    <key>key2</key>
    <name>Rule2</name>
    <internalKey>internalKey2</internalKey>
    <description><![CDATA[<p>An Html <a href=""www.bing.com""> Description]]></description>
    <severity>MAJOR</severity>
    <cardinality>SINGLE</cardinality>
    <status>READY</status>
  </rule>
</rules>";

            // Save the expected XML to make comparisons using diff tools easier
            string expectedFilePath = TestUtils.CreateTextFile("expected.xml", testDir, expectedXmlContent);
            this.TestContext.AddResultFile(expectedFilePath);

            // Compare the serialized output
            string actualXmlContent = File.ReadAllText(rulesFile);
            Assert.AreEqual(expectedXmlContent, actualXmlContent, "Unexpected XML content");

            // Check the rule descriptions were decoded correctly
            Assert.AreEqual("description 1", reloaded[0].Description, "Description was not deserialized correctly");
            Assert.AreEqual(@"<p>An Html <a href=""www.bing.com""> Description", reloaded[1].Description, "Description was not deserialized correctly");
        }
Example #34
0
 public LockStep()
 {
     LockName   = "TAP_Mutex1";
     SystemWide = true;
     Rules.Add(() => LockName.Contains("\\") == false, "Lock Name does not support '\\'", "LockName");
 }
        private void UpdateCharacter(Sheet sheet)
        {
            this.sheet = sheet;
            if (sheet == null) {
                return;
            }

            this.AbilityScores = new AbilityScores(this.sheet.Stats);
            this.Defenses = new Defenses(this.sheet.Stats);
            this.Skills = new Skills(this.Sheet.Stats);

            // fixup links
            foreach (var stat in this.sheet.Stats) {
                foreach (var mod in stat.Modifiers) {
                    if (String.IsNullOrWhiteSpace(mod.StatLink)) {
                        continue;
                    }

                    mod.Link = this.sheet.Stats[mod.StatLink];
                }
            }

            // fixup rules
            // first, add all the item rules
            var weaponRules = (from i in this.sheet.Items
                               from r in i.Rules
                               select r).Distinct();
            var union = this.sheet.Rules.Union(weaponRules);
            Rules rules = new Rules();
            foreach (var rule in union) {
                rules.Add(rule);
            }
            this.sheet.Rules = rules;

            // next, expand all the weapon rules on powers
            foreach (var power in this.sheet.Powers) {
                foreach (var weapon in power.Weapons) {
                    var ids = (from r in weapon.Rules
                               select r.InternalId).ToArray();
                    weapon.Rules.Clear();
                    foreach (var id in ids) {
                        weapon.Rules.Add(this.sheet.Rules[id]);
                    }
                }
            }
        }
Example #36
0
        private Rules GetRules(List<RuleRef> ruleRefs)
        {
            Rules rules = new Rules();

              ruleRefs.Sort(new RuleRefComparer());

              foreach (RuleRef ruleRef in ruleRefs)
              {
            Rule rule = _rules.Find(x => x.Id == ruleRef.Value);
            if (rule != null) rules.Add(rule);
              }

              return rules;
        }