public void DocBuilder_WithValidator_ReturnsRuleDescription() { var singleRuleValidator = new SingleRuleValidator(); var expectedRuleDescription = new RuleDescriptor { MemberName = "First Name", Rules = new List <RuleDescription> { new RuleDescription { FailureSeverity = "Error", OnFailure = "Continue", ValidationMessage = "Mock message", ValidatorName = "NotEmptyValidator" } } }; var mockRuleDescriptor = new Mock <IRuleBuilder>(); mockRuleDescriptor.Setup(x => x.BuildRuleDescription(It.IsAny <IEnumerable <IPropertyValidator> >(), It.IsAny <string>(), It.IsAny <CascadeMode>(), It.IsAny <PropertyRule>())).Returns(expectedRuleDescription); var docBuilder = new DocBuilder(mockRuleDescriptor.Object); var actualResult = docBuilder.Document(singleRuleValidator).ToList(); actualResult.Should().HaveCount(1); actualResult.Should().BeEquivalentTo(expectedRuleDescription); }
public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { IList <SqlRuleProblem> problems = new List <SqlRuleProblem>(); TSqlObject modelElement = ruleExecutionContext.ModelElement; if (IsInlineTableValuedFunction(modelElement)) { return(problems); } string elementName = GetElementName(ruleExecutionContext, modelElement); TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; WaitForDelayVisitor visitor = new WaitForDelayVisitor(); fragment.Accept(visitor); IList <WaitForStatement> waitForDelayStatements = visitor.WaitForDelayStatements; foreach (WaitForStatement waitForStatement in waitForDelayStatements) { var problem = new SqlRuleProblem(string.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement, waitForStatement); problems.Add(problem); } return(problems); }
public static IRuleDescriptor ConvertToRuleDescriptor(this Diagnostic diagnostic) { // TODO we should consume the standard Roslyn->SARIF emit code here. DiagnosticDescriptor diagnosticDescriptor = diagnostic.Descriptor; var ruleDescriptor = new RuleDescriptor(); ruleDescriptor.FormatSpecifiers = new Dictionary<string, string>(); ruleDescriptor.FormatSpecifiers["Default"] = diagnosticDescriptor.MessageFormat.ToString(); ruleDescriptor.FullDescription = diagnosticDescriptor.Description.ToString(); ruleDescriptor.HelpUri = new Uri(diagnosticDescriptor.HelpLinkUri); ruleDescriptor.Id = diagnosticDescriptor.Id; // TODO: review this decision ruleDescriptor.Name = diagnostic.GetType().Name; ruleDescriptor.Properties = new Dictionary<string, string>(); foreach (string tag in diagnosticDescriptor.CustomTags) { ruleDescriptor.Properties[tag] = String.Empty; } ruleDescriptor.Properties["Category"] = diagnosticDescriptor.Category; ruleDescriptor.Properties["DefaultSeverity"] = diagnosticDescriptor.DefaultSeverity.ToString(); ruleDescriptor.Properties["IsEnabledByDefault"] = diagnosticDescriptor.IsEnabledByDefault.ToString(); ruleDescriptor.ShortDescription = diagnosticDescriptor.Title.ToString(); // No Roslyn analog for these available from diagnostic //ruleDescriptor.Options return ruleDescriptor; }
public void RuleDescriptionBuilder_WithSingleChildRuleValidator_ReturnsChildRuleValidatorRuleDescription() { const CascadeMode cascadeMode = CascadeMode.Continue; var validator = new SingleChildValidator(); var propertyRule = validator.CreateDescriptor().GetRulesForMember(validator.CreateDescriptor().GetMembersWithValidators().First().Key).First() as PropertyRule; var propertyName = propertyRule.GetDisplayName(); var expectedRuleDescription = new RuleDescriptor { MemberName = "Address", Rules = new List <RuleDescription> { new RuleDescription { FailureSeverity = "Error", OnFailure = "Continue", ValidationMessage = "N/A - Refer to specific AddressValidator documentation", ValidatorName = "AddressValidator" } } }; var ruleDescriptionBuilder = new RuleDescriptionBuilder(Mock.Of <IValidatorErrorMessageBuilder>()); var actualRuleDescription = ruleDescriptionBuilder.BuildRuleDescription(propertyRule.Validators, propertyName, cascadeMode, propertyRule); actualRuleDescription.Rules.Should().HaveCount(1); actualRuleDescription.ShouldBeEquivalentTo(expectedRuleDescription); }
public static IRuleDescriptor ConvertToRuleDescriptor(this Diagnostic diagnostic) { // TODO we should consume the standard Roslyn->SARIF emit code here. DiagnosticDescriptor diagnosticDescriptor = diagnostic.Descriptor; var ruleDescriptor = new RuleDescriptor(); ruleDescriptor.FormatSpecifiers = new Dictionary <string, string>(); ruleDescriptor.FormatSpecifiers["Default"] = diagnosticDescriptor.MessageFormat.ToString(); ruleDescriptor.FullDescription = diagnosticDescriptor.Description.ToString(); ruleDescriptor.HelpUri = new Uri(diagnosticDescriptor.HelpLinkUri); ruleDescriptor.Id = diagnosticDescriptor.Id; // TODO: review this decision ruleDescriptor.Name = diagnostic.GetType().Name; ruleDescriptor.Properties = new Dictionary <string, string>(); foreach (string tag in diagnosticDescriptor.CustomTags) { ruleDescriptor.Properties[tag] = String.Empty; } ruleDescriptor.Properties["Category"] = diagnosticDescriptor.Category; ruleDescriptor.Properties["DefaultSeverity"] = diagnosticDescriptor.DefaultSeverity.ToString(); ruleDescriptor.Properties["IsEnabledByDefault"] = diagnosticDescriptor.IsEnabledByDefault.ToString(); ruleDescriptor.ShortDescription = diagnosticDescriptor.Title.ToString(); // No Roslyn analog for these available from diagnostic //ruleDescriptor.Options return(ruleDescriptor); }
public override void MissingNode(RuleDescriptor ruleDescriptor) { if ((Options & PrettyPrintOptions.MissingNodes) == PrettyPrintOptions.MissingNodes) { WriteSpan(_missingNodeClass, ruleDescriptor.Name); } _lastMissing = _buffer.Length; }
public RuleDescriptor BuildRuleDescription(IEnumerable <IPropertyValidator> validationRules, string propertyName, CascadeMode cascadeMode, PropertyRule rule) { if (validationRules == null) { throw new ArgumentNullException(nameof(validationRules)); } var propertyValidators = validationRules as IList <IPropertyValidator> ?? validationRules.ToList(); if (!propertyValidators.Any()) { throw new InvalidOperationException("No validation rules to document"); } if (string.IsNullOrWhiteSpace(propertyName)) { throw new ArgumentNullException(nameof(propertyName)); } var ruleDescriptor = new RuleDescriptor { MemberName = propertyName }; var ruleDescriptions = new List <RuleDescription>(); foreach (var propertyValidator in propertyValidators) { string validatorName; Severity?validationFailureSeverity; string validationMessage; if (propertyValidator is ChildValidatorAdaptor childValidator) { validatorName = childValidator.ValidatorType.Name; validationFailureSeverity = childValidator.Severity; validationMessage = $"N/A - Refer to specific {validatorName} documentation"; } else { validatorName = propertyValidator.GetType().Name; validationFailureSeverity = propertyValidator.Severity; validationMessage = _validatorErrorMessageBuilder.GetErrorMessage(propertyValidator, rule, propertyName); } ruleDescriptions.Add(new RuleDescription { ValidatorName = validatorName, FailureSeverity = validationFailureSeverity.ToString(), OnFailure = cascadeMode.ToString(), ValidationMessage = validationMessage }); } ruleDescriptor.Rules = ruleDescriptions; return(ruleDescriptor); }
public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = this.GetElementName(ruleExecutionContext, modelElement); TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; var problems = this.ElicitProblems(fragment, ruleDescriptor, elementName, modelElement); return(problems); }
private static SqlRuleProblem AddProblem(TSqlObject modelElement, RuleDescriptor ruleDescriptor, TSqlFragment fragment) { var description = string.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription); var problem = new SqlRuleProblem(description, modelElement, fragment) { Severity = SqlRuleProblemSeverity.Warning }; return(problem); }
private void OutputSarifRulesMetada(string outputFilePath, ImmutableArray <IRuleDescriptor> skimmers, ImmutableArray <IOptionsProvider> options) { var log = new ResultLog(); log.Version = SarifVersion.ZeroDotFour; // The SARIF spec currently requires an array // of run logs with at least one member log.RunLogs = new List <RunLog>(); var runLog = new RunLog(); runLog.ToolInfo = new ToolInfo(); runLog.ToolInfo.InitializeFromAssembly(this.GetType().Assembly, Prerelease); runLog.Results = new List <Result>(); log.RunLogs.Add(runLog); runLog.ToolInfo.RuleInfo = new List <RuleDescriptor>(); SortedDictionary <int, RuleDescriptor> sortedRuleDescriptors = new SortedDictionary <int, RuleDescriptor>(); foreach (IRuleDescriptor descriptor in skimmers) { var ruleDescriptor = new RuleDescriptor(); ruleDescriptor.Id = descriptor.Id; ruleDescriptor.Name = descriptor.Name; ruleDescriptor.Options = descriptor.Options; ruleDescriptor.HelpUri = descriptor.HelpUri; ruleDescriptor.Properties = descriptor.Properties; ruleDescriptor.FullDescription = descriptor.FullDescription; ruleDescriptor.FormatSpecifiers = descriptor.FormatSpecifiers; ruleDescriptor.ShortDescription = ruleDescriptor.ShortDescription; int numericId = GetIdIntegerSuffix(ruleDescriptor.Id); sortedRuleDescriptors[numericId] = ruleDescriptor; } foreach (RuleDescriptor ruleDescriptor in sortedRuleDescriptors.Values) { runLog.ToolInfo.RuleInfo.Add(ruleDescriptor); } var settings = new JsonSerializerSettings() { ContractResolver = SarifContractResolver.Instance, Formatting = Formatting.Indented, }; File.WriteAllText(outputFilePath, JsonConvert.SerializeObject(log, settings)); }
public RuleTemplateInfo GetTemplate(RuleDescriptor descriptor) { Guard.NotNull(descriptor, nameof(descriptor)); var info = new RuleTemplateInfo { TemplateName = GetValueTemplateName(descriptor) }; return(info); }
protected virtual IList <SqlRuleProblem> CreateProblems(RuleDescriptor ruleDescriptor, string elementName, TSqlObject modelElement, IEnumerable <TSqlFragment> invalidSqlFragments, SqlRuleProblemSeverity severity) { var problems = new List <SqlRuleProblem>(); foreach (var invalidFragment in invalidSqlFragments) { var problem = new SqlRuleProblem(string.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement, invalidFragment); problem.Severity = severity; problems.Add(problem); } return(problems); }
public void RuleDescriptionBuilder_WithMultipleRuleValidator_ReturnsStructuredRuleDescription() { const string validationErrorMessage = "Mock message"; var validator = new MultipleRuleValidator(); var propertyRule = validator.CreateDescriptor().GetRulesForMember(validator.CreateDescriptor().GetMembersWithValidators().Last().Key).First() as PropertyRule; var propertyName = propertyRule.GetDisplayName(); var mockValidatorErrorMessageBuilder = new Mock <IValidatorErrorMessageBuilder>(); mockValidatorErrorMessageBuilder.Setup(m => m.GetErrorMessage(It.IsAny <IPropertyValidator>(), It.IsAny <PropertyRule>(), It.IsAny <string>())) .Returns(validationErrorMessage); var expectedOutput = new RuleDescriptor { MemberName = "Last Name", Rules = new List <RuleDescription> { new RuleDescription { FailureSeverity = "Error", OnFailure = "Continue", ValidationMessage = validationErrorMessage, ValidatorName = "NotEmptyValidator" }, new RuleDescription { FailureSeverity = "Error", OnFailure = "Continue", ValidationMessage = validationErrorMessage, ValidatorName = "MinimumLengthValidator" }, new RuleDescription { FailureSeverity = "Error", OnFailure = "Continue", ValidationMessage = validationErrorMessage, ValidatorName = "MaximumLengthValidator" } } }; var ruleDescriptionBuilder = new RuleDescriptionBuilder(mockValidatorErrorMessageBuilder.Object); var actualRuleDescription = ruleDescriptionBuilder.BuildRuleDescription(propertyRule.Validators, propertyName, CascadeMode.Continue, propertyRule); actualRuleDescription.Rules.Should().HaveCount(3); actualRuleDescription.ShouldBeEquivalentTo(expectedOutput, options => options.WithStrictOrdering()); }
/// <summary> /// For element-scoped rules the Analyze method is executed once for every matching /// object in the model. /// </summary> /// <param name="ruleExecutionContext">The context object contains the TSqlObject being /// analyzed, a TSqlFragment /// that's the AST representation of the object, the current rule's descriptor, and a /// reference to the model being /// analyzed. /// </param> /// <returns>A list of problems should be returned. These will be displayed in the Visual /// Studio error list</returns> public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { IList <SqlRuleProblem> problems = new List <SqlRuleProblem>(); TSqlObject modelElement = ruleExecutionContext.ModelElement; // this rule does not apply to inline table-valued function // we simply do not return any problem in that case. if (RuleUtils.IsInlineTableValuedFunction(modelElement)) { return(problems); } string elementName = RuleUtils.GetElementName(ruleExecutionContext, modelElement); // The rule execution context has all the objects we'll need, including the // fragment representing the object, // and a descriptor that lets us access rule metadata TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; // To process the fragment and identify WAITFOR DELAY statements we will use a // visitor WaitForDelayVisitor visitor = new WaitForDelayVisitor(); fragment.Accept(visitor); IList <WaitForStatement> waitforDelayStatements = visitor.WaitForDelayStatements; // Create problems for each WAITFOR DELAY statement found // When creating a rule problem, always include the TSqlObject being analyzed. This // is used to determine // the name of the source this problem was found in and a best guess as to the // line/column the problem was found at. // // In addition if you have a specific TSqlFragment that is related to the problem //also include this // since the most accurate source position information (start line and column) will // be read from the fragment foreach (WaitForStatement waitForStatement in waitforDelayStatements) { SqlRuleProblem problem = new SqlRuleProblem( String.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement, waitForStatement); problems.Add(problem); } return(problems); }
public RuleOptionsContext(RuleOptionsRequestReason reason, RuleDescriptor descriptor) { Guard.NotNull(descriptor, nameof(descriptor)); Guard.NotNull(reason, nameof(reason)); Descriptor = descriptor; Reason = reason; if (descriptor.SelectList is RemoteRuleValueSelectList list) { DataSource = list.DataSource; } Guard.NotEmpty(DataSource, nameof(DataSource)); }
// This fills in the information in List of RuleSelectors, it is run by pushing // the "Test Control Center". This allows them to be instantiated, and given some time // before being filled in all the way. public void initializeSelectors() { int i = 0; foreach (GameObject selector in RuleSelectors) { Rule rule = RuleDatabase.RDBcontrol.rules[i++]; string newName = "Rule" + rule.ruleID.ToString(); bool isSet = GlobalControl.control.selectedRules.Contains(rule.ruleID); RuleDescriptor RD = selector.GetComponent <RuleDescriptor>(); RD.gameObject.name = newName; RD.SetInfo(RuleDisplayText, isSet, rule.ruleDesc, rule.ruleID, this); } ColorSelected(); }
public override IList <SqlRuleProblem> Analyze( SqlRuleExecutionContext ruleExecutionContext) { TSqlObject modelElement = ruleExecutionContext.ModelElement; TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; string elementName = GetElementName(ruleExecutionContext, modelElement); var rule = new IncompatibleFunctionsSql2012Rule(); IEnumerable <ISqlCodeAnalysisProblem> problems = rule.GetFragmentProblems(fragment); return(problems .Select(problem => new SqlRuleProblem( problem.Description, modelElement, problem.Fragment )).ToList()); }
public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = RuleUtils.GetElementName(ruleExecutionContext, modelElement); CreateTableStatementVisitor visitor = new CreateTableStatementVisitor(); fragment.Accept(visitor); return(( from table in visitor.Nodes where table.SchemaObjectName.BaseIdentifier.Value.ToUpper().Contains("VIEW") select new SqlRuleProblem(String.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement) ).ToList()); }
protected virtual string GetValueTemplateName(RuleDescriptor descriptor) { if (descriptor.Metadata.TryGetValue("ValueTemplateName", out var val) && val is string name && name.HasValue()) { return(name); } string templateName; var type = descriptor.RuleType; if (descriptor.SelectList != null || type == RuleType.IntArray || type == RuleType.FloatArray || type == RuleType.StringArray) { templateName = "Dropdown"; } else if (type == RuleType.Boolean || type == RuleType.NullableBoolean) { templateName = "Boolean"; } else if (type == RuleType.Int || type == RuleType.NullableInt) { templateName = "Int32"; } else if (type == RuleType.Float || type == RuleType.NullableFloat) { templateName = "Float"; } else if (type == RuleType.Money) { templateName = "Decimal"; } else if (type == RuleType.DateTime || type == RuleType.NullableDateTime) { templateName = "DateTime"; } else { // Fallback to simple text-box. templateName = "TextBox"; } return("ValueTemplates/" + templateName); }
/// <summary> /// For element-scoped rules the Analyze method is executed once for every matching object in the model. /// </summary> /// <param name="ruleExecutionContext">The context object contains the TSqlObject being analyzed, a TSqlFragment /// that's the AST representation of the object, the current rule's descriptor, and a reference to the model being /// analyzed. /// </param> /// <returns>A list of problems should be returned. These will be displayed in the Visual Studio error list</returns> public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { IList <SqlRuleProblem> problems = new List <SqlRuleProblem>(); TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = ruleExecutionContext.SchemaModel.DisplayServices.GetElementName(modelElement, ElementNameStyle.EscapedFullyQualifiedName); RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; bool hasDescription = false; // Check if it has columns. Workaround for tables from referenced projects showing up here. // Not interested in those. They should be checked in their own project. List <TSqlObject> columns = modelElement.GetReferenced(Table.Columns).ToList(); if (columns.Count > 0) { // Check if it has an extended property List <TSqlObject> extendedProperties = modelElement.GetReferencing(ExtendedProperty.Host).ToList(); if (extendedProperties.Count > 0) { foreach (TSqlObject prop in extendedProperties) { if (ruleExecutionContext.SchemaModel.DisplayServices.GetElementName(prop, ElementNameStyle.SimpleName) == "MS_Description") { hasDescription = true; break; } } } if (!hasDescription) { SqlRuleProblem problem = new SqlRuleProblem( String.Format( CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement); problems.Add(problem); } } return(problems); }
public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { IList <SqlRuleProblem> problems = new List <SqlRuleProblem>(); TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = ruleExecutionContext.SchemaModel.DisplayServices.GetElementName(modelElement, ElementNameStyle.EscapedFullyQualifiedName); RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; List <TSqlObject> columns = modelElement.GetReferenced(Table.Columns).ToList(); foreach (TSqlObject column in modelElement.GetReferenced(Table.Columns)) { bool hasDescription = false; // Check if it has an extended property List <TSqlObject> extendedProperties = column.GetReferencing(ExtendedProperty.Host).ToList(); if (extendedProperties.Count > 0) { foreach (TSqlObject prop in extendedProperties) { if (ruleExecutionContext.SchemaModel.DisplayServices.GetElementName(prop, ElementNameStyle.SimpleName) == "MS_Description") { hasDescription = true; break; } } } if (!hasDescription) { SqlRuleProblem problem = new SqlRuleProblem( String.Format( CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, ruleExecutionContext.SchemaModel.DisplayServices.GetElementName(column, ElementNameStyle.EscapedFullyQualifiedName)), column); problems.Add(problem); } } return(problems); }
public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = RuleUtils.GetElementName(ruleExecutionContext, modelElement); CreateTableStatementVisitor visitor = new CreateTableStatementVisitor(); fragment.Accept(visitor); // Begin with alpha character Regex regex = new Regex(@"^[A-Z][a-zA-Z0-9]*$"); return(( from table in visitor.Nodes where !regex.IsMatch(table.SchemaObjectName.BaseIdentifier.Value) select new SqlRuleProblem(String.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, table.SchemaObjectName.BaseIdentifier.Value), modelElement) ).ToList()); }
public void WriteRuleInfo(IEnumerable <IRuleDescriptor> ruleDescriptors) { _jsonWriter.WritePropertyName("ruleInfo"); _jsonWriter.WriteStartArray(); foreach (IRuleDescriptor ruleDescriptor in ruleDescriptors) { RuleDescriptor descriptor = new RuleDescriptor(); descriptor.Id = ruleDescriptor.Id; descriptor.Name = ruleDescriptor.Name; descriptor.FullDescription = ruleDescriptor.FullDescription; descriptor.ShortDescription = ruleDescriptor.ShortDescription; descriptor.Options = ruleDescriptor.Options; descriptor.Properties = ruleDescriptor.Properties; descriptor.FormatSpecifiers = ruleDescriptor.FormatSpecifiers; _serializer.Serialize(_jsonWriter, descriptor, typeof(RuleDescriptor)); } _jsonWriter.WriteEndArray(); }
// WHen a Color is chosen, this will ghost rules and unghost them void ColorSelected() { // Grab list of the allowable Rules List <int> KeyRules = RuleDatabase.RDBcontrol.GetColorRules(); if (RuleSelectors == null) { print("RuleSelectors not found!"); } foreach (GameObject selector in RuleSelectors) { RuleDescriptor RD = selector.GetComponent <RuleDescriptor>(); if (!KeyRules.Contains(RD.ID)) { RD.GhostSet(true); } else { RD.GhostSet(false); } } }
/// <summary> /// Ensure Primary Key included for each table /// is created /// </summary> /// <param name="ruleExecutionContext"></param> /// <returns></returns> public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = RuleUtils.GetElementName(ruleExecutionContext, modelElement); CreateTableStatementVisitor visitor = new CreateTableStatementVisitor(); fragment.Accept(visitor); return(( from table in visitor.Nodes let isTemp = table.SchemaObjectName.BaseIdentifier.Value.StartsWith("#") || table.SchemaObjectName.BaseIdentifier.Value.StartsWith("@") where !isTemp && !table.Definition.TableConstraints.OfType <UniqueConstraintDefinition>().Any(x => x.IsPrimaryKey) select new SqlRuleProblem(String.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement) ).ToList()); //List<SqlRuleProblem> problems = new List<SqlRuleProblem>(); //TSqlObject sqlObj = ruleExecutionContext.ModelElement; //if (sqlObj != null) //{ // if (sqlObj.Name != null && sqlObj.Name.Parts != null && sqlObj.Name.Parts.Any(x => x.StartsWith("#") || x.StartsWith("@"))) // { // return problems; // } // var child = sqlObj.GetChildren(DacQueryScopes.All).FirstOrDefault(x => x.ObjectType == PrimaryKeyConstraint.TypeClass); // if (child == null) // { // string msg = string.Format(Message, RuleUtils.GetElementName(ruleExecutionContext, sqlObj)); // problems.Add(new SqlRuleProblem(msg, sqlObj)); // } //} //return problems; }
public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { IList <SqlRuleProblem> problems = new List <SqlRuleProblem>(); TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = RuleUtils.GetElementName(ruleExecutionContext, modelElement); CreateTableStatementVisitor visitor = new CreateTableStatementVisitor(); fragment.Accept(visitor); // Begin with alpha character. Only contain alphanumeric. Regex regex = new Regex(@"^[A-Z][a-zA-Z0-9]*$"); return(( from table in visitor.Nodes where table.Definition.ColumnDefinitions.Any(x => !regex.IsMatch(x.ColumnIdentifier.Value)) select new SqlRuleProblem(String.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement) ).ToList()); }
public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { IList <SqlRuleProblem> problems = new List <SqlRuleProblem>(); TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = GetElementName(ruleExecutionContext, modelElement); TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; var visitor = new SelectStarVisitor(); fragment.Accept(visitor); foreach (var selectStarExpression in visitor.SelectStarExpressions) { var problem = new SqlRuleProblem(string.Format(CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, elementName), modelElement, selectStarExpression); problem.Severity = SqlRuleProblemSeverity.Warning; problems.Add(problem); } return(problems); }
public void RuleDescriptionBuilder_WithSingleRuleValidator_ReturnsSingleRuleDescription() { const string validationErrorMessage = "Mock message"; const CascadeMode cascadeMode = CascadeMode.Continue; var mockValidatorErrorMessageBuilder = new Mock <IValidatorErrorMessageBuilder>(); mockValidatorErrorMessageBuilder.Setup(m => m.GetErrorMessage(It.IsAny <IPropertyValidator>(), It.IsAny <PropertyRule>(), It.IsAny <string>())) .Returns(validationErrorMessage); var validator = new SingleRuleValidator(); var propertyRule = validator.CreateDescriptor().GetRulesForMember("FirstName").First() as PropertyRule; var propertyName = propertyRule.GetDisplayName(); var expectedRuleDescription = new RuleDescriptor { MemberName = "First Name", Rules = new List <RuleDescription> { new RuleDescription { FailureSeverity = "Error", OnFailure = "Continue", ValidationMessage = validationErrorMessage, ValidatorName = "NotEmptyValidator" } } }; var ruleDescriptionBuilder = new RuleDescriptionBuilder(mockValidatorErrorMessageBuilder.Object); var actualRuleDescription = ruleDescriptionBuilder.BuildRuleDescription(propertyRule.Validators, propertyName, cascadeMode, propertyRule); actualRuleDescription.Rules.Should().HaveCount(1); actualRuleDescription.ShouldBeEquivalentTo(expectedRuleDescription); }
public override void MissingNode(RuleDescriptor ruleDescriptor) { if ((Options & PrettyPrintOptions.MissingNodes) == PrettyPrintOptions.MissingNodes) WriteSpan(_missingNodeClass, ruleDescriptor.Name); _lastMissing = _buffer.Length; }
protected override IList <SqlRuleProblem> ElicitProblems(TSqlFragment fragment, RuleDescriptor ruleDescriptor, string elementName, TSqlObject modelElement) { var problems = new List <SqlRuleProblem>(); var visitor = new SchemaVisitor(); fragment.Accept(visitor); visitor.NamedTableReferences .ToList() .ForEach(x => problems.Add(AddProblem(modelElement, ruleDescriptor, x))); visitor.FunctionCalls .ToList() .ForEach(x => problems.Add(AddProblem(modelElement, ruleDescriptor, x))); visitor.ProcedureReferences .ToList() .ForEach(x => problems.Add(AddProblem(modelElement, ruleDescriptor, x))); return(problems); }
protected override IList <SqlRuleProblem> ElicitProblems(TSqlFragment fragment, RuleDescriptor ruleDescriptor, string elementName, TSqlObject modelElement) { var sb = new StringBuilder(); foreach (var scriptTokenStreamFragment in fragment.ScriptTokenStream) { sb.Append(scriptTokenStreamFragment.Text); } var fullScript = sb.ToString(); var isHeaderPresent = true; foreach (var knownHeaderItem in this.KnownHeaderItems) { if (fullScript.IndexOf(knownHeaderItem, StringComparison.OrdinalIgnoreCase) == -1) { isHeaderPresent = false; } } if (!isHeaderPresent) { return(this.CreateProblemsAsError(ruleDescriptor, elementName, modelElement, new List <TSqlFragment> { fragment })); } return(null); }
/// <summary> /// For element-scoped rules the Analyze method is executed once for every matching object in the model. /// </summary> /// <param name="ruleExecutionContext">The context object contains the TSqlObject being analyzed, a TSqlFragment /// that's the AST representation of the object, the current rule's descriptor, and a reference to the model being /// analyzed. /// </param> /// <returns>A list of problems should be returned. These will be displayed in the Visual Studio error list</returns> public override IList <SqlRuleProblem> Analyze(SqlRuleExecutionContext ruleExecutionContext) { IList <SqlRuleProblem> problems = new List <SqlRuleProblem>(); TSqlObject modelElement = ruleExecutionContext.ModelElement; string elementName = ruleExecutionContext.SchemaModel.DisplayServices.GetElementName(modelElement, ElementNameStyle.EscapedFullyQualifiedName); TSqlFragment fragment = ruleExecutionContext.ScriptFragment; RuleDescriptor ruleDescriptor = ruleExecutionContext.RuleDescriptor; // Get schema of the procedure. TSqlObject schema = modelElement.GetReferenced(Procedure.Schema).SingleOrDefault(); if (schema != null && fragment.FragmentLength > 0) { CursorVisitor visitor = new CursorVisitor(true, false); fragment.Accept(visitor); foreach (var element in visitor.DeclareCursorStatementsMissingDeallocate) { string cursorName = element.Name.Value; SqlRuleProblem problem = new SqlRuleProblem( String.Format( CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, "Missing deallocate", cursorName, elementName), modelElement, element.CursorDefinition); problems.Add(problem); } foreach (var element in visitor.IncorrectDeallocateCursorStatements) { string cursorName = element.Cursor?.Name.Value ?? "NULL"; SqlRuleProblem problem = new SqlRuleProblem( String.Format( CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, "Invalid deallocate", cursorName, elementName), modelElement, element); problems.Add(problem); } foreach (var element in visitor.DeclareCursorStatementsMissingOpen) { string cursorName = element.Name.Value; SqlRuleProblem problem = new SqlRuleProblem( String.Format( CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, "Missing open", cursorName, elementName), modelElement, element.CursorDefinition); problems.Add(problem); } foreach (var element in visitor.IncorrectOpenCursorStatements) { string cursorName = element.Cursor?.Name.Value ?? "NULL"; SqlRuleProblem problem = new SqlRuleProblem( String.Format( CultureInfo.CurrentCulture, ruleDescriptor.DisplayDescription, "Invalid open", cursorName, elementName), modelElement, element); problems.Add(problem); } } return(problems); }