private void PropertyAssignmentValidation(SyntaxNodeAnalysisContext context)
{
// Call the abstract method to make it easier to debug.
// You can set a breakpoint in the override method so you know you are debugging the
// analyzer you care about.
this.GetServiceName();
if (_propertyValueRules.Count == 0)
return;
var assignmentExpr = (AssignmentExpressionSyntax)context.Node;
var literal = assignmentExpr.Right as LiteralExpressionSyntax;
if (literal == null)
return;
var literalOpt = context.SemanticModel.GetConstantValue(literal);
if (!literalOpt.HasValue)
return;
var symbol = context.SemanticModel.GetSymbolInfo(assignmentExpr.Left).Symbol;
if (symbol == null)
return;
var memberSymbol = context.SemanticModel.GetSymbolInfo(assignmentExpr.Left).Symbol as Microsoft.CodeAnalysis.IPropertySymbol;
if (memberSymbol == null)
return;
PropertyValueRule propertyValueRule;
if (!_propertyValueRules.TryGetValue(memberSymbol.ToString(), out propertyValueRule))
return;
if (literalOpt.Value is string)
{
var value = literalOpt.Value as string;
if (propertyValueRule.Min.HasValue)
{
if (value.Length < propertyValueRule.Min.Value)
{
var diagnostic =
Diagnostic.Create(MinLengthRule,
literal.GetLocation(),
new object[] { value, memberSymbol.Name, propertyValueRule.Min.Value });
context.ReportDiagnostic(diagnostic);
}
}
if (propertyValueRule.Max.HasValue)
{
if (value.Length > propertyValueRule.Max.Value)
{
var diagnostic =
Diagnostic.Create(MaxLengthRule,
literal.GetLocation(),
new object[] { value, memberSymbol.Name, propertyValueRule.Max.Value });
context.ReportDiagnostic(diagnostic);
}
}
if (propertyValueRule.CompiledExpression != null)
{
var match = propertyValueRule.CompiledExpression.Match(value);
if (!string.Equals(match.Value, value, StringComparison.Ordinal))
{
var diagnostic =
Diagnostic.Create(PatternRule,
literal.GetLocation(),
new object[] { value, propertyValueRule.Pattern, memberSymbol.Name });
context.ReportDiagnostic(diagnostic);
}
}
}
if(literalOpt.Value is int || literalOpt.Value is long)
{
var value = Convert.ToInt64(literalOpt.Value);
if (propertyValueRule.Min.HasValue)
{
if (value < propertyValueRule.Min.Value)
{
var diagnostic =
Diagnostic.Create(MinValueRule,
literal.GetLocation(),
new object[] { value, propertyValueRule.Min.Value, memberSymbol.Name });
context.ReportDiagnostic(diagnostic);
}
}
if (propertyValueRule.Max.HasValue)
{
if (value > propertyValueRule.Max.Value)
{
var diagnostic =
Diagnostic.Create(MaxValueRule,
literal.GetLocation(),
new object[] { value, propertyValueRule.Max.Value, memberSymbol.Name });
context.ReportDiagnostic(diagnostic);
}
}
}
}