kthaulow / codeanalyzer Goto Github PK
View Code? Open in Web Editor NEWCode analyzer for common bugs in C#
License: MIT License
Code analyzer for common bugs in C#
License: MIT License
public static skal være readonly (note: public static readonly valueType kan være const)
The follwoing code is marked as not using InvariantCulture:
double.TryParse(lon.ExceptLast(1), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out longitude)
Ignore loops invoking methods in the statement to check if it should continue
while (iterationChecker.CanIterate())
The following code is marked by AN0001
while (targets.Any()) { iterations++; if (iterations > 100) { break; } }
a = a.orderBy(pred).tolist() => a.sort(pred)
OrderBy().FirstOrDefault() => MinByOrDefault
The analyzers for double
e.g. Parse
and TryParse
using InvariantCulture
should also apply to float
.
For AN0001, only mark the While/For condition part, not the entire body
When formatting a TimeSpan
using one the following is always invalid:
Year and month does not apply TimeSpan
y
Y
yy
yyy
yyyy
M
"Did you mean mm
(minutes)"MM
"Did you mean mm
(minutes)"MMM
MMMM
TimeSpan
doesn't operator with 12 vs 24h clock, so this is invalid:
HH
"Did you mean hh
(hours)"
D
"Did you mean dd
(days)"
DD
"Did you mean dd
(days)"
Special cases:
d
alone doesn't work, use %d
or in a pattern @"d\:h"
h
alone doesn't work, use %h
or in a pattern @"h\:m"
m
alone doesn't work, use %d
or in a pattern @"m\:s"
s
alone doesn't work, use %s
or in a pattern @"s\:f"
f
alone doesn't work, use %f
or in a pattern @"f\:ff"
F
alone doesn't work, use %F
or in a pattern @"F\:ff"
List.Any(e => e == x) => List.Contains(x)
Assume we have a custom attribute e.g. [ThreadUnsafe]
for methods and properties.
Then for unit tests, calling functions/fields/classes decorated with [ThreadUnsafe]
is only allowed, if used in:
[TestMethod]
and method is decorated with [DoNotParallelize]
, or[ClassInitialize]
and class is decorated with [DoNotParallelize]
, or[AssemblyInitialize]
.AN0001 is triggered in this code
`int added = 0;
int loopCount = 0;
while (added< 10 && list.Any())
{
foreach (var sourceGroup in sourceGroups)
{
;
}
}
loopCount++;
if (loopCount > 100)
break;
}`
Logger: typen skal følge className
e.g. ACLogManager.Instance.GetLogger for klasssen NavigationRepository
DateTime.Now
=> DateTimeExt.Now
DateTime.Today
=> DateTimeExt.UtcToday
DateTime.{Parse, ParseExact, TryParse, TryParseExact}
=> DateTimeExt.{Parse, ParseExact, TryParse, TryParseExact}
new DateTime(year, month, day)
=> DateTimeExt.UtcDate(year, month, day)
new DateTime(year, month, day, minute, hour, second)
=> DateTimeExt.UtcDate(year, month, day, hour, minute, second)
new DateTime(year, month, day, hour, minute, 0)
=> DateTimeExt.UtcDate(year, month, day, hour, minute)
new DateTime(year, month, day, hour, 0, 0)
=> DateTimeExt.UtcDate(year, month, day, hour)
new DateTime(year, month, day, 0, 0, 0)
=> DateTimeExt.UtcDate(year, month, day)
When using a datetime format, check that 24 hours format is used. "HH" should be used instead of "hh".
The following patterns (with any separator) should probably have MM
(month) instead of m
(minutes)
when formatting a DateTime
or DateTimeOffset
.
yyyy/mm/dd
mm/dd/yyyy
dd/mm/yyyy
yy/mm/dd
mm/dd/yy
dd/mm/yy
private xxxLock = new object() => private [static] readonly xxxLock = new object()
Singleton-pattern:
ACLogger s_log => private static readonly
dobbelt null check
private ctor
sealed class
TimeFormatAnalyzer
Severity Code Description Project File Line Suppression State Detail Description
Warning AD0001 Analyzer 'CodeAnalyzer.Analyzers.TimeFormatAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'. ConsoleApp44 1 Active Analyzer 'CodeAnalyzer.Analyzers.TimeFormatAnalyzer' threw the following exception:
'Exception occurred with following context:
Compilation: ConsoleApp44
SyntaxTree: C:\Users\jonas\source\repos\ConsoleApp44\ConsoleApp44\Program.cs
SyntaxNode: F(Date) [InvocationExpressionSyntax]@[505..512) (18,12)-(18,19)
System.NullReferenceException: Object reference not set to an instance of an object.
at CodeAnalyzer.Analyzers.TimeFormatAnalyzer.AnalyzeInvocationExpressionSyntax(SyntaxNodeAnalysisContext context, INamedTypeSymbol dateTimeSymbol)
at CodeAnalyzer.Analyzers.TimeFormatAnalyzer.<>c__DisplayClass8_0.<Initialize>b__1(SyntaxNodeAnalysisContext nodeContext)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c__44`1.<ExecuteSyntaxNodeAction>b__44_0(ValueTuple`2 data)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info)
-----
'.
DoubleParseAnalyzer
Severity Code Description Project File Line Suppression State Detail Description
Warning AD0001 Analyzer 'CodeAnalyzer.Analyzers.DoubleParseAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'. ConsoleApp44 1 Active Analyzer 'CodeAnalyzer.Analyzers.DoubleParseAnalyzer' threw the following exception:
'Exception occurred with following context:
Compilation: ConsoleApp44
SyntaxTree: C:\Users\jonas\source\repos\ConsoleApp44\ConsoleApp44\Program.cs
SyntaxNode: F(Date) [InvocationExpressionSyntax]@[505..512) (18,12)-(18,19)
System.NullReferenceException: Object reference not set to an instance of an object.
at CodeAnalyzer.Analyzers.DoubleParseAnalyzer.AnalyzeInvocationExpressionSyntax(SyntaxNodeAnalysisContext context, INamedTypeSymbol doubleSymbol)
at CodeAnalyzer.Analyzers.DoubleParseAnalyzer.<>c__DisplayClass8_0.<Initialize>b__1(SyntaxNodeAnalysisContext nodeContext)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c__44`1.<ExecuteSyntaxNodeAction>b__44_0(ValueTuple`2 data)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info)
-----
'.
DateTimeStringAnalyzer
Severity Code Description Project File Line Suppression State Detail Description
Warning AD0001 Analyzer 'CodeAnalyzer.Analyzers.DateTimeStringAnalyzer' threw an exception of type 'System.NullReferenceException' with message 'Object reference not set to an instance of an object.'. ConsoleApp44 1 Active Analyzer 'CodeAnalyzer.Analyzers.DateTimeStringAnalyzer' threw the following exception:
'Exception occurred with following context:
Compilation: ConsoleApp44
SyntaxTree: C:\Users\jonas\source\repos\ConsoleApp44\ConsoleApp44\Program.cs
SyntaxNode: F(Date) [InvocationExpressionSyntax]@[505..512) (18,12)-(18,19)
System.NullReferenceException: Object reference not set to an instance of an object.
at CodeAnalyzer.Analyzers.DateTimeStringAnalyzer.AnalyzeInvocationExpressionSyntax(SyntaxNodeAnalysisContext context, INamedTypeSymbol doubleSymbol)
at CodeAnalyzer.Analyzers.DateTimeStringAnalyzer.<>c__DisplayClass8_0.<Initialize>b__1(SyntaxNodeAnalysisContext nodeContext)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c__44`1.<ExecuteSyntaxNodeAction>b__44_0(ValueTuple`2 data)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info)
-----
'.
AN0001 should not detect loops without circuit breaker for SqlDataReader:
while (reader.Read()) {}
Instead of e.g.
DateTime.UtcNow.ToString("yyyy/MM/dd");
On my machine gives "2018-08-14"
use
DateTime.UtcNow.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
On my machine gives "2018/08/14"
Reason:
When not using InvariantCuture
the char /
is interpreted as the DateSeparator
and is replaced with the the date separator of the current culture.
The following circuit breaker should be supported
int loopCounter = 0; int something1 = 0; int something2 = 1; while (something1 != something2 && loopCounter < 10) { loopCounter++; }
TimeSpan stayTime;
stayTime.ToString(@"\Dh+mm", CultureInfo.InvariantCulture);
This should not be marked by AN0009
X.Remove(X.LastOrDefault) => X.RemoveLast()
Det første fjerner første element identisk med X.Last(), så hvis der er flere identiske vil den første blive fjernet i stedet for den sidste
Loop body skal indeholde circuit-breaker
Show info about code style for methods having [TestMethod] attribute if the method name is not on the form XXX_YYY_ZZZ. This should represent [Unit to be tested][Scenario][Expected outcome]
Check that Assert or Should() (from FluentAssertions) are being called in every unit test. Check private method calls as the assert could be in a method called.
Linq.Any(e => e == b.ToX()) (ingen grund til at kalde b.ToX() for hver sammenligning)
=> var bb = b.ToX(); Linq.Any(e => bb)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.