SharpSource v1.32.0 — Evaluation Report

Automated analysis across 560 open-source C# repositories · March 2026

560
Repos Analyzed
178
With Findings
219
Clean
126980
Total Diagnostics
53
Unique Rules

Repository Overview (Repos with Findings)

RepositoryDiagnosticsUnique RulesTop Rules
FreeSql16246 20SS019(8454), SS002(2040), SS018(1458)
Facepunch.Steamworks6570 12SS017(5382), SS008(900), SS019(56)
UnityCsReference4864 21SS017(2324), SS008(1190), SS019(300)
ServiceStack4340 28SS066(718), SS008(620), SS019(428)
SqlSugar3788 22SS002(2062), SS049(456), SS034(230)
FastReport3606 17SS003(882), SS058(816), SS019(594)
smtp4dev3332 18SS023(1656), SS066(466), SS051(336)
Masuit.Tools3000 15SS003(1022), SS002(676), SS019(280)
better-genshin-impact2852 22SS003(1834), SS002(484), SS066(124)
TensorFlow.NET2662 14SS013(1816), SS004(464), SS066(104)
ant-design-blazor2544 18SS066(988), SS002(344), SS004(180)
ILRuntime2420 18SS019(596), SS018(564), SS004(364)
OpenRA2320 16SS003(1242), SS066(306), SS004(296)
Lean2106 19SS066(1662), SS019(114), SS018(82)
xdm2068 13SS066(950), SS002(214), SS048(196)
StockSharp2048 18SS066(572), SS017(450), SS019(220)
R32014 13SS066(1406), SS001(208), SS017(104)
LibreHardwareMonitor1974 10SS017(904), SS019(588), SS003(254)
FASTER1924 12SS017(712), SS066(480), SS003(448)
NanUI1914 10SS017(560), SS066(550), SS003(280)
roslynator1720 12SS019(892), SS018(486), SS017(198)
server1624 22SS059(564), SS004(232), SS001(140)
mathnet-numerics1602 12SS003(1064), SS019(170), SS023(96)
WTM1594 20SS033(382), SS034(312), SS058(242)
ModernWpf1576 15SS019(586), SS018(292), SS017(240)
FluentFTP1576 14SS002(280), SS033(262), SS019(252)
opencvsharp1358 14SS008(588), SS066(570), SS017(102)
Eto1344 12SS066(424), SS008(408), SS003(216)
Polly1322 10SS017(422), SS033(318), SS004(136)
AngleSharp1318 14SS019(370), SS008(230), SS018(200)
PicView1296 10SS066(1074), SS003(68), SS019(56)
WPF-Samples1222 12SS049(252), SS019(248), SS011(242)
subtitleedit1112 15SS058(550), SS003(240), SS019(104)
DotNetty1080 12SS003(522), SS034(300), SS035(108)
Power-Fx1014 22SS004(596), SS008(86), SS019(80)
Ocelot978 16SS033(450), SS066(168), SS003(60)
octokit.net954 18SS034(586), SS002(256), SS032(24)
MessagePack-CSharp938 15SS003(284), SS046(240), SS017(212)
NLog910 12SS017(316), SS066(170), SS019(126)
quartznet892 13SS059(532), SS008(148), SS003(64)
ClosedXML858 15SS008(208), SS003(168), SS017(122)
opentk836 13SS008(486), SS017(132), SS003(84)
NAudio736 13SS003(302), SS017(244), SS066(68)
cairoshell724 12SS019(256), SS066(144), SS011(112)
Blog.Core708 17SS002(316), SS033(58), SS034(58)
CsvHelper674 9SS017(310), SS002(76), SS059(62)
btcpayserver662 17SS033(290), SS034(166), SS037(78)
LiteDB646 12SS019(206), SS066(186), SS002(78)
QRCoder602 4SS003(420), SS017(154), SS002(14)
Akka.NET590 16SS017(116), SS008(112), SS019(80)
FastEndpoints588 17SS019(130), SS033(106), SS017(94)
lively586 11SS019(182), SS066(128), SS003(110)
netmq582 14SS004(144), SS008(96), SS019(90)
MassTransit548 12SS017(162), SS048(140), SS003(70)
SharpZipLib544 12SS003(150), SS023(84), SS033(74)
LiteMonitor542 11SS066(256), SS003(102), SS002(98)
libgit2sharp540 10SS017(278), SS008(72), SS041(60)
Jackett540 20SS002(188), SS058(80), SS003(72)
MelonLoader528 14SS003(112), SS017(76), SS019(72)
Ombi520 19SS002(224), SS004(72), SS059(44)
P492 15SS004(248), SS058(58), SS019(50)
puppeteer-sharp484 8SS066(200), SS008(172), SS034(52)
Inveigh472 7SS051(144), SS019(120), SS002(78)
OpenUtau470 17SS003(192), SS017(88), SS051(50)
Bulk-Crap-Uninstaller464 13SS003(142), SS066(92), SS017(74)
UniTask458 10SS017(236), SS051(88), SS066(72)
MQTTnet456 12SS066(228), SS034(64), SS017(40)
SignalR406 11SS034(236), SS066(44), SS003(36)
Dapper400 8SS019(112), SS059(72), SS018(64)
ExcelDataReader400 6SS019(144), SS003(144), SS066(64)
g-helper400 9SS017(132), SS003(92), SS019(62)
git-credential-manager396 10SS033(150), SS066(108), SS017(80)
Util384 19SS033(122), SS019(54), SS049(46)
Il2CppDumper380 7SS004(128), SS003(96), SS019(96)
SwarmUI378 21SS051(150), SS003(50), SS058(44)
cecil376 7SS019(104), SS017(80), SS018(64)
RestSharp340 9SS002(88), SS066(82), SS037(48)
Vue.NetCore334 17SS002(140), SS049(82), SS044(16)
MemoryPack328 12SS017(242), SS066(24), SS003(18)
YamlDotNet326 9SS004(100), SS008(60), SS017(60)
Windows-Auto-Night-Mode284 14SS002(148), SS001(26), SS003(20)
LiteNetLib280 10SS003(108), SS017(60), SS019(36)
TwitchDownloader276 14SS034(68), SS003(64), SS048(50)
commandline276 9SS004(112), SS019(48), SS002(24)
Autofac256 10SS066(104), SS017(52), SS060(32)
LLamaSharp244 12SS017(100), SS066(58), SS003(30)
StableSwarmUI236 19SS051(92), SS033(28), SS058(26)
winsw230 10SS017(108), SS033(30), SS023(24)
XUnity.AutoTranslator224 15SS019(32), SS018(30), SS017(26)
WeiXinMPSDK224 10SS056(112), SS033(54), SS059(16)
VPet222 13SS004(114), SS002(46), SS066(16)
slskd206 11SS033(54), SS059(42), SS004(30)
pythonnet182 18SS017(56), SS003(26), SS023(18)
VFSForGit180 10SS066(40), SS002(34), SS017(28)
Papercut-SMTP174 10SS002(76), SS066(56), SS059(12)
BruteShark172 11SS008(52), SS066(32), SS058(30)
FlaUI170 8SS003(72), SS066(30), SS023(30)
DotnetSpider156 15SS002(52), SS008(18), SS019(12)
openai154 11SS023(54), SS019(36), SS066(18)
luban152 12SS004(62), SS048(22), SS034(16)
netch146 10SS004(40), SS019(40), SS066(28)
NetCoreServer138 4SS003(64), SS034(60), SS066(12)
Serilog134 3SS017(64), SS066(56), SS003(14)
OneOf130 3SS017(120), SS033(8), SS004(2)
Flow.Launcher126 11SS002(26), SS019(24), SS008(22)
Respawn124 3SS058(84), SS066(24), SS059(16)
Translumo122 10SS066(48), SS034(26), SS017(12)
modular-monolith-with-ddd116 7SS059(64), SS002(20), SS017(16)
imewlconverter108 8SS058(28), SS003(26), SS017(20)
C-Sharp-Algorithms108 6SS003(66), SS023(18), SS020(14)
videoduplicatefinder102 12SS001(26), SS059(10), SS033(10)
CAP94 6SS002(52), SS033(24), SS059(8)
ink94 11SS017(26), SS008(20), SS019(12)
AutoMapper90 4SS017(40), SS004(30), SS058(10)
hashids.net90 3SS020(48), SS003(24), SS046(18)
Hearthstone-Deck-Tracker88 6SS001(42), SS011(24), SS002(12)
XboxDownload86 11SS019(38), SS002(12), SS058(8)
FluentAssertions86 9SS005(38), SS004(18), SS003(8)
BepInEx84 9SS017(24), SS002(18), SS066(12)
optick84 7SS008(24), SS051(20), SS002(16)
fluentmigrator78 9SS066(20), SS019(20), SS004(12)
BBDown76 4SS003(34), SS008(30), SS002(10)
RyTuneX76 10SS017(14), SS033(12), SS002(12)
OpenTabletDriver74 6SS017(58), SS044(6), SS019(4)
CSharpRepl72 11SS017(28), SS033(8), SS066(8)
orleans64 6SS019(34), SS008(12), SS017(10)
VsVim64 5SS019(26), SS018(18), SS017(12)
Emby.Plugins.JavScraper64 7SS002(32), SS033(8), SS003(8)
FluentTerminal62 1SS008(62)
YoutubePlaylistDownloader56 4SS059(24), SS066(16), SS003(12)
parsec-vdd54 6SS017(30), SS066(10), SS003(6)
Seq.Api52 5SS017(24), SS033(12), SS034(6)
qmk_toolbox50 6SS019(22), SS066(12), SS001(10)
blazor-starter-kit50 7SS002(24), SS019(10), SS004(6)
GuardClauses44 3SS002(38), SS017(4), SS049(2)
DotNetGuide44 6SS003(20), SS002(10), SS009(4)
Telegram.Bot42 6SS019(12), SS059(10), SS033(8)
opentrace40 4SS066(28), SS034(8), SS001(2)
SymSpell36 5SS003(14), SS017(8), SS008(6)
dotnet-script36 5SS059(12), SS008(10), SS033(8)
RunCat36536 3SS017(16), SS066(14), SS034(6)
Steam-auto-crack34 3SS017(28), SS003(4), SS066(2)
NSubstitute32 3SS017(20), SS004(8), SS015(4)
app32 4SS003(12), SS019(10), SS059(6)
Scrutor32 2SS017(24), SS004(8)
ApiEndpoints30 6SS034(18), SS017(4), SS004(2)
N_m3u8DL-RE30 4SS008(20), SS003(4), SS002(4)
coravel28 6SS066(8), SS059(6), SS033(4)
Entitas28 3SS008(14), SS017(12), SS019(2)
ScreenToGif26 3SS002(12), SS059(8), SS017(6)
AspNetCoreDiagnosticScenarios26 4SS034(12), SS033(8), SS037(4)
maui-samples24 2SS033(12), SS001(12)
SimplCommerce24 3SS002(18), SS059(4), SS033(2)
SteamAchievementManager24 1SS017(24)
querybuilder22 5SS044(6), SS058(4), SS033(4)
keepass2android22 4SS008(12), SS019(6), SS041(2)
eShop20 5SS008(8), SS066(6), SS059(2)
EquinoxProject20 5SS034(6), SS066(6), SS033(4)
repkg20 5SS003(10), SS021(4), SS018(2)
basic-computer-games18 3SS017(14), SS019(2), SS003(2)
PKHeX16 1SS003(16)
MediatR16 4SS051(8), SS034(4), SS044(2)
carter12 2SS033(8), SS059(4)
Flurl12 2SS058(6), SS017(6)
mongo-csharp-driver12 1SS017(12)
sample-dotnet-core-cqrs-api10 4SS002(4), SS017(2), SS033(2)
Stateless10 1SS034(10)
samples8 2SS002(4), SS017(4)
Discord.Net8 2SS059(6), SS034(2)
SteamKit8 1SS004(8)
AspNetCoreRateLimit8 3SS003(4), SS017(2), SS004(2)
jellyfin-plugin-metatube8 2SS019(6), SS037(2)
GoogleTranslateIpCheck6 1SS033(6)
Jellyfin6 3SS017(2), SS003(2), SS019(2)
BenchmarkDotNet4 1SS044(4)
practical-aspnetcore2 1SS033(2)
OFGB2 1SS019(2)
playwright-dotnet2 1SS033(2)

Rule Frequency Across All Repos

RuleDescriptionTotal HitsRepos Affected
SS001Async method with void return type816 44
SS002Use DateTime.UtcNow instead of DateTime.Now10264 102
SS003Integer divided by integer causing implicit rounding14324 125
SS004Elementary methods of type in collection not overridden5450 94
SS005Equals() and GetHashCode() not implemented together252 22
SS006Throwing null will always result in a runtime exception24 1
SS007[Flags] enum values are not powers of two32 3
SS008GetHashCode() refers to mutable or static member7284 76
SS009Random instantiated in a loop32 5
SS011OnPropertyChanged without nameof operator450 5
SS013Rethrow exception without losing stacktrace3108 12
SS015String placeholders in wrong order402 13
SS017Struct without Equals/GetHashCode/ToString overridden17864 130
SS018Switch does not handle all enum options5226 85
SS019Switch is missing default label18710 126
SS020Test method without public modifier128 6
SS021Test method without test attribute178 15
SS022Exception thrown from implicit operator86 6
SS023Exception thrown from property getter2908 64
SS024Exception thrown from static constructor56 9
SS025Exception thrown from finally block2 1
SS026Exception thrown from equality operator4 1
SS027Exception thrown from Dispose80 10
SS028Exception thrown from finalizer2 1
SS029Exception thrown from GetHashCode2 1
SS030Exception thrown from Equals14 4
SS032Thread.Sleep used in async method104 15
SS033Async overload is available4218 87
SS034Accessing Task.Result without await3436 72
SS035Synchronous task wait instead of await294 13
SS037HttpClient instantiated directly326 18
SS038HttpContext stored in a field60 5
SS040Unused result on immutable object32 6
SS041Unnecessary enumerable materialization246 27
SS044Attribute must specify [AttributeUsage]974 44
SS046Unbounded stackalloc318 11
SS047LINQ traversal before filter130 14
SS048Locking on discouraged object (string, Type, this)910 26
SS049Comparing strings without StringComparison2320 41
SS050Parameter assigned in constructor32 7
SS051Locking on mutable reference2426 43
SS052[ThreadStatic] field with initializer8 1
SS053Pointless collection ToString()26 4
SS054Newtonsoft.Json mixed with System.Text.Json90 3
SS055Multiple OrderBy() calls instead of ThenBy()30 2
SS056HttpRequest.Form read synchronously242 9
SS057Collection manipulated during traversal442 35
SS058String concatenated in a loop4210 76
SS059IAsyncDisposable not disposed asynchronously2680 77
SS060ConcurrentDictionary emptiness check without IsEmpty74 9
SS063ValueTask awaited multiple times2 1
SS064Unnecessary ToString() on Span14 3
SS066Disposable field is not disposed15638 119

Detailed Findings by Repository

FreeSql

16246 total diagnostics across 20 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2040 hits
📄 FreeSql\Internal\ObjectPool\Object.cs (line 54)
51 /// <summary>
52 /// 创建时间
53 /// </summary>
54 public DateTime CreateTime { get; internal set; } = DateTime.Now;
55
56 /// <summary>
57 /// 最后获取时的线程id
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 FreeSql\FreeUtil.cs (line 31)
28 /// <returns></returns>
29 public static Guid NewMongodbId()
30 {
31 var now = DateTime.Now;
32 var uninxtime = (int)now.Subtract(dt1970).TotalSeconds;
33 int increment = Interlocked.Increment(ref __staticIncrement) & 0x00ffffff;
34 var rand = rnd.Value.Next(0, int.MaxValue);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 236 hits
📄 FreeSql\Internal\CommonProvider\UpdateProvider.cs (line 342)
339 {
340 var colSum = _table.Columns.Count - _ignore.Count;
341 if (colSum <= 0) colSum = 1;
342 takeMax = parameterLimit / colSum;
343 if (takeMax > valuesLimit) takeMax = valuesLimit;
344 }
345 if (_source.Count <= takeMax) return new[] { _source };
💬 The operands in the divisive expression parameterLimit / colSum are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 FreeSql\Internal\CommonProvider\InsertProvider.cs (line 251)
248 {
249 var colSum = _table.Columns.Count - _ignore.Count;
250 if (colSum <= 0) colSum = 1;
251 takeMax = parameterLimit / colSum;
252 if (takeMax > valuesLimit) takeMax = valuesLimit;
253 }
254 if (_source.Count <= takeMax) return new[] { _source };
💬 The operands in the divisive expression parameterLimit / colSum are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 238 hits
📄 FreeSql\Internal\CommonProvider\SelectProvider\SelectGroupingProvider.cs (line 77)
74 curtables = _select._tables;
75 LocalValueInitData();
76 }
77 if (tempQueryParser._outsideTable.Contains(curtable))
78 {
79 var replaceMember = firstMember.Type == curtable.Parameter.Type ? firstMember : members[0];
80 var replaceVistor = new CommonExpression.ReplaceVisitor();
💬 Type SelectTableInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 FreeSql\Internal\CommonProvider\SelectProvider\SelectGroupingProvider.cs (line 77)
74 curtables = _select._tables;
75 LocalValueInitData();
76 }
77 if (tempQueryParser._outsideTable.Contains(curtable))
78 {
79 var replaceMember = firstMember.Type == curtable.Parameter.Type ? firstMember : members[0];
80 var replaceVistor = new CommonExpression.ReplaceVisitor();
💬 Type SelectTableInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 380 hits
📄 Providers\FreeSql.Provider.MySql\MySqlAdo\MygisTypes.cs (line 155)
152 public override int GetHashCode()
153 {
154 var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently.
155 foreach (var t in _points) ret ^= RotateShift(t.GetHashCode(), ret % sizeof(int));
156 return ret;
157 }
158}
💬 GetHashCode() refers to mutable field _points (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Providers\FreeSql.Provider.MySql\MySqlAdo\MygisTypes.cs (line 198)
195 public override int GetHashCode()
196 {
197 var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently.
198 for (var i = 0; i < _rings.Length; i++)
199 for (var j = 0; j < _rings[i].Length; j++)
200 ret ^= RotateShift(_rings[i][j].GetHashCode(), ret % sizeof(int));
201 return ret;
💬 GetHashCode() refers to mutable field _rings (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 1008 hits
📄 Providers\FreeSql.Provider.Odbc\MySql\Curd\OdbcMySqlInsert.cs (line 73)
70 catch (Exception ex)
71 {
72 exception = ex;
73 throw ex;
74 }
75 finally
76 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 Providers\FreeSql.Provider.Odbc\PostgreSQL\Curd\OdbcPostgreSQLDelete.cs (line 53)
50 catch (Exception ex)
51 {
52 exception = ex;
53 throw ex;
54 }
55 finally
56 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 38 hits
📄 Providers\FreeSql.Provider.MySql\MySqlAdo\MygisTypes.cs (line 8)
5using System.Text.RegularExpressions;
6using FreeSql;
7
8public struct MygisCoordinate2D : IEquatable<MygisCoordinate2D>
9{
10 public double X { get; }
11 public double Y { get; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MygisCoordinate2D. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Providers\FreeSql.Provider.MySql\MySqlAdo\MygisTypes.cs (line 8)
5using System.Text.RegularExpressions;
6using FreeSql;
7
8public struct MygisCoordinate2D : IEquatable<MygisCoordinate2D>
9{
10 public double X { get; }
11 public double Y { get; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MygisCoordinate2D. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 1458 hits
📄 FreeSql\Extensions\LambadaExpressionExtensions.cs (line 318)
315 break;
316 }
317 object firstValue = null;
318 switch (expStack.First().NodeType)
319 {
320 case ExpressionType.Constant:
321 var expStackFirst = expStack.Pop() as ConstantExpression;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 FreeSql\Extensions\LambadaExpressionExtensions.cs (line 335)
332 while (expStack.Any())
333 {
334 var expStackItem = expStack.Pop();
335 switch (expStackItem.NodeType)
336 {
337 case ExpressionType.MemberAccess:
338 var memExp = expStackItem as MemberExpression;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 8454 hits
📄 FreeSql\Extensions\LambadaExpressionExtensions.cs (line 291)
288 var exp2 = exp;
289 while (true)
290 {
291 switch (exp2?.NodeType)
292 {
293 case ExpressionType.Constant:
294 expStack.Push(exp2);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 FreeSql\Extensions\LambadaExpressionExtensions.cs (line 318)
315 break;
316 }
317 object firstValue = null;
318 switch (expStack.First().NodeType)
319 {
320 case ExpressionType.Constant:
321 var expStackFirst = expStack.Pop() as ConstantExpression;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS020 Test method without public modifier 18 hits
📄 FreeSql.Tests\FreeSql.Tests.Provider.TDengine\TDengine\TDengineCrud\TDengineCrudTest.cs (line 12)
9 IFreeSql fsql => g.tdengine;
10
11 [Fact]
12 void CodeFirstTest()
13 {
14 fsql.CodeFirst.SyncStructure<D1001>();
15 fsql.CodeFirst.SyncStructure<D1002>();
💬 Test method "CodeFirstTest" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
📄 FreeSql.Tests\FreeSql.Tests.Provider.TDengine\TDengine\TDengineIssue\TDengineIssueTest.cs (line 24)
21 }
22
23 [Fact]
24 void CodeFirst1977()
25 {
26 _fsql.CodeFirst.SyncStructure(typeof(TDengineProcessMetrics1977));
27 }
💬 Test method "CodeFirst1977" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
SS027 Exception thrown from Dispose 10 hits
📄 FreeSql.DbContext\UnitOfWork\UnitOfWorkManager.cs (line 74)
71 if (exception == null) exception = ex;
72 }
73 }
74 if (exception != null) throw exception;
75 }
76 finally
77 {
💬 An exception is thrown from the Dispose() method in type UnitOfWorkManager (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 FreeSql.DbContext\UnitOfWork\UnitOfWorkManager.cs (line 74)
71 if (exception == null) exception = ex;
72 }
73 }
74 if (exception != null) throw exception;
75 }
76 finally
77 {
💬 An exception is thrown from the Dispose() method in type UnitOfWorkManager (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS033 Async overload is available 284 hits
📄 FreeSql\Extensions\FreeSqlGlobalExtensions.cs (line 768)
765 imsel.SetList(list);
766#else
767 if (isAsync) await imsel.SetListAsync(list);
768 else imsel.SetList(list);
769#endif
770 return list;
771 }
💬 Async overload available for Select1Provider.SetList (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 FreeSql\Extensions\FreeSqlGlobalExtensions.cs (line 799)
796#if net40
797 var reflist = refsel.ToList();
798#else
799 var reflist = isAsync ? await refsel.ToListAsync() : refsel.ToList();
800#endif
801
802 reflist.ForEach(refitem =>
💬 Async overload available for Select0Provider.ToList (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 10 hits
📄 FreeSql\Extensions\FreeSqlGlobalExtensions.cs (line 727)
724#else
725 var task = IncludeByPropertyNameSyncOrAsync<T1>(false, list, orm, property, where, take, select, then);
726 if (task.Exception != null) throw task.Exception.InnerException ?? task.Exception;
727 return task.Result;
728#endif
729 }
730#if net40
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 FreeSql\Extensions\FreeSqlGlobalExtensions.cs (line 727)
724#else
725 var task = IncludeByPropertyNameSyncOrAsync<T1>(false, list, orm, property, where, take, select, then);
726 if (task.Exception != null) throw task.Exception.InnerException ?? task.Exception;
727 return task.Result;
728#endif
729 }
730#if net40
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 30 hits
📄 FreeSql\Internal\CommonProvider\UpdateProvider.cs (line 637)
634 if (tempPrimarys != null)
635 {
636 var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, null, tempPrimarys?.Body, false, null).Distinct().ToDictionary(a => a);
637 _tempPrimarys = cols.Keys.Select(a => _table.Columns.TryGetValue(a, out var col) ? col : null).ToArray().Where(a => a != null).ToArray();
638 }
639 _ignoreVersion = ignoreVersion;
640 _versionColumn = _ignoreVersion ? null : _table?.VersionColumn;
💬 ToArray is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 FreeSql\Internal\CommonProvider\InsertOrUpdateProvider.cs (line 193)
190 if (tempPrimarys != null)
191 {
192 var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, null, tempPrimarys?.Body, false, null).Distinct().ToDictionary(a => a);
193 _tempPrimarys = cols.Keys.Select(a => _table.Columns.TryGetValue(a, out var col) ? col : null).ToArray().Where(a => a != null).ToArray();
194 }
195 return this;
196 }
💬 ToArray is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 16 hits
📄 FreeSql\DataAnnotations\NavigateAttribute.cs (line 14)
11 /// OneToMany:Category.cs 文件 (缺省)Category.Id &lt;-&gt; [Navigate(nameof(Topic.CategoryId))]<para></para>
12 /// _________________public List&lt;Topic&gt; Topics { get; set; }<para></para>
13 /// </summary>
14 public class NavigateAttribute : Attribute
15 {
16
17 /// <summary>
💬 NavigateAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 FreeSql\DataAnnotations\NavigateAttribute.cs (line 14)
11 /// OneToMany:Category.cs 文件 (缺省)Category.Id &lt;-&gt; [Navigate(nameof(Topic.CategoryId))]<para></para>
12 /// _________________public List&lt;Topic&gt; Topics { get; set; }<para></para>
13 /// </summary>
14 public class NavigateAttribute : Attribute
15 {
16
17 /// <summary>
💬 NavigateAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS047 LINQ traversal before filter 40 hits
📄 FreeSql.Tests\FreeSql.Tests.Provider.OracleOledb\OracleOledb\Curd\OracleOledbSelectTest.cs (line 1263)
1260 .ToList();
1261
1262 var t00 = g.oracle.Select<TiOtmModel2>()
1263 .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id))
1264 .Where(a => a.model2id <= model1.id)
1265 .ToList();
1266
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 FreeSql.Tests\FreeSql.Tests.Provider.OracleOledb\OracleOledb\Curd\OracleOledbSelectTest.cs (line 1268)
1265 .ToList();
1266
1267 var t11 = g.oracle.Select<TiOtmModel1>()
1268 .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id))
1269 .Where(a => a.id <= model1.id)
1270 .ToList();
1271
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS049 Comparing strings without StringComparison 352 hits
📄 FreeSql\Extensions\FreeSqlGlobalExpressionCallExtensions.cs (line 397)
394 case DataType.CustomPostgreSQL:
395 case DataType.KingbaseES:
396 case DataType.ShenTong:
397 if (part.ToLower() == "day" || part.ToLower() == "d")
398 up.Result = $"(DATE_PART('day', {dt2} - {dt1}))";
399 else if (part.ToLower() == "second" || part.ToLower() == "s")
400 up.Result = $"(EXTRACT(EPOCH FROM ({dt2} - {dt1})))";
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 FreeSql\Extensions\FreeSqlGlobalExpressionCallExtensions.cs (line 397)
394 case DataType.CustomPostgreSQL:
395 case DataType.KingbaseES:
396 case DataType.ShenTong:
397 if (part.ToLower() == "day" || part.ToLower() == "d")
398 up.Result = $"(DATE_PART('day', {dt2} - {dt1}))";
399 else if (part.ToLower() == "second" || part.ToLower() == "s")
400 up.Result = $"(EXTRACT(EPOCH FROM ({dt2} - {dt1})))";
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 464 hits
📄 FreeSql\Extensions\AdoNetExtensions.cs (line 72)
69 default:
70 throw new Exception(CoreErrorStrings.Not_Implemented);
71 }
72 lock (_dicCurdLock)
73 {
74 if (_dicCurd.TryGetValue(dbconn.ConnectionString, out fsql)) return fsql;
75 lock (_dicCurdLock)
💬 A lock was obtained on _dicCurdLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 FreeSql\Extensions\AdoNetExtensions.cs (line 75)
72 lock (_dicCurdLock)
73 {
74 if (_dicCurd.TryGetValue(dbconn.ConnectionString, out fsql)) return fsql;
75 lock (_dicCurdLock)
76 _dicCurd.Add(dbconn.ConnectionString, fsql = Activator.CreateInstance(providerType, new object[] { null, null, null }) as IFreeSql);
77 }
78 return fsql;
💬 A lock was obtained on _dicCurdLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 810 hits
📄 FreeSql\Internal\CommonExpression.cs (line 261)
258 var memExp = exp as MemberExpression;
259 while (memExp != null)
260 {
261 includeKey = $"{memExp.Member.Name}.{includeKey}";
262 if (memExp.Expression.NodeType == ExpressionType.Parameter) break;
263 memExp = memExp.Expression as MemberExpression;
264 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 FreeSql\Internal\CommonUtils.cs (line 497)
494 foreach (var col in cols)
495 {
496 var colval = Utils.GetDataReaderValue(col.Attribute.MapType, objs[colidx]);
497 filter += $"{(colidx > 0 ? " AND " : "")}{aliasAndDot}{this.QuoteSqlName(col.Attribute.Name)} = ";
498 if (CodeFirst.IsGenerateCommandParameterWithLambda && dbParams != null) //v3.5.100 单条支持参数化
499 {
500 var paramName = $"exp_{dbParams.Count}";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 16 hits
📄 FreeSql\Internal\CommonProvider\AdoProvider\AdoProviderAsync.cs (line 644)
641 };
642 }
643#endif
644 using (var dr = await pc.cmd.ExecuteReaderAsync(cancellationToken))
645 {
646 int resultIndex = 0;
647 var fetch = new FetchCallbackArgs<DbDataReader> { Object = dr };
💬 DbDataReader can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Providers\FreeSql.Provider.PostgreSQL\PostgreSQLExtensions.cs (line 311)
308 copyFromCommand.Append(insert.InternalCommonUtils.QuoteSqlName(col.ColumnName));
309 }
310 copyFromCommand.Append(") FROM STDIN BINARY");
311 using (var writer = conn.BeginBinaryImport(copyFromCommand.ToString()))
312 {
313 foreach (DataRow item in dt.Rows)
314 {
💬 NpgsqlBinaryImporter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 344 hits
📄 FreeSql\Internal\CommonProvider\SelectProvider\Select0Provider.cs (line 33)
30 public Func<Type, string, string> _aliasRule;
31 public string _tosqlAppendContent;
32 public StringBuilder _join = new StringBuilder();
33 public IFreeSql _orm;
34 public CommonUtils _commonUtils;
35 public CommonExpression _commonExpression;
36 public DbTransaction _transaction;
💬 Disposable field _orm in type Select0Provider is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 FreeSql\Internal\CommonProvider\SelectProvider\Select0Provider.cs (line 36)
33 public IFreeSql _orm;
34 public CommonUtils _commonUtils;
35 public CommonExpression _commonExpression;
36 public DbTransaction _transaction;
37 public DbConnection _connection;
38 public int _commandTimeout = 0;
39 public Action<object> _trackToList;
💬 Disposable field _transaction in type Select0Provider is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Facepunch.Steamworks

6570 total diagnostics across 12 rules

SS001 Async method with void return type 36 hits
📄 Facepunch.Steamworks\Classes\Dispatch.cs (line 236)
233 /// have to think about it. This has the advantage that
234 /// you can call .Wait() on async shit and it still works.
235 /// </summary>
236 internal static async void LoopClientAsync()
237 {
238 while ( ClientPipe != 0 )
239 {
💬 Method LoopClientAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Facepunch.Steamworks\Classes\Dispatch.cs (line 250)
247 /// have to think about it. This has the advantage that
248 /// you can call .Wait() on async shit and it still works.
249 /// </summary>
250 internal static async void LoopServerAsync()
251 {
252 while ( ServerPipe != 0 )
253 {
💬 Method LoopServerAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS003 Integer divided by integer causing implicit rounding 36 hits
📄 Facepunch.Steamworks\SteamUtils.cs (line 132)
129 /// <summary>
130 /// Returns battery power [0-1].
131 /// </summary>
132 public static float CurrentBatteryPower => Math.Min( Internal.GetCurrentBatteryPower() / 100, 1.0f );
133
134 static NotificationPosition overlayNotificationPosition = NotificationPosition.BottomRight;
135
💬 The operands in the divisive expression Internal.GetCurrentBatteryPower() / 100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Facepunch.Steamworks\Structs\UgcEditor.cs (line 293)
290 }
291 }
292
293 await Task.Delay( 1000 / 60 );
294 }
295
296 progress?.Report( 1 );
💬 The operands in the divisive expression 1000 / 60 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 900 hits
📄 Facepunch.Steamworks\Structs\InventoryRecipe.cs (line 99)
96 public override bool Equals( object p ) => this.Equals( (InventoryRecipe)p );
97 public override int GetHashCode()
98 {
99 return Source.GetHashCode();
100 }
101
102 public bool Equals( InventoryRecipe p ) => p.GetHashCode() == GetHashCode();
💬 GetHashCode() refers to mutable field Source (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Facepunch.Steamworks\Structs\Controller.cs (line 57)
54 public static bool operator ==( Controller a, Controller b ) => a.Equals( b );
55 public static bool operator !=( Controller a, Controller b ) => !(a == b);
56 public override bool Equals( object p ) => this.Equals( (Controller)p );
57 public override int GetHashCode() => Handle.GetHashCode();
58 public bool Equals( Controller p ) => p.Handle == Handle;
59 }
60
💬 GetHashCode() refers to mutable field Handle (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 5382 hits
📄 Facepunch.Steamworks\Callbacks\CallResult.cs (line 14)
11 /// <summary>
12 /// An awaitable version of a SteamAPICall_t
13 /// </summary>
14 internal struct CallResult<T> : INotifyCompletion where T : struct, ICallbackData
15 {
16 SteamAPICall_t call;
17 ISteamUtils utils;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CallResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Facepunch.Steamworks\Structs\ServerInit.cs (line 14)
11 /// Used to set up the server.
12 /// The variables in here are all required to be set, and can't be changed once the server is created.
13 /// </summary>
14 public struct SteamServerInit
15 {
16 public IPAddress IpAddress;
17 public ushort GamePort;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SteamServerInit. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 54 hits
📄 Facepunch.Steamworks\Structs\UgcEditor.cs (line 261)
258
259 var r = SteamUGC.Internal.GetItemUpdateProgress( handle, ref processed, ref total );
260
261 switch ( r )
262 {
263 case ItemUpdateStatus.PreparingConfig:
264 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Facepunch.Steamworks\Networking\ConnectionManager.cs (line 54)
51 // - Update state before the callbacks, in case an exception is thrown
52 // - ConnectionState.None happens when a connection is destroyed, even if it was already disconnected (ClosedByPeer / ProblemDetectedLocally)
53 //
54 switch ( info.State )
55 {
56 case ConnectionState.Connecting:
57 if ( !Connecting && !Connected )
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 56 hits
📄 Generator\CodeWriter\Utility.cs (line 55)
52
53 type = Cleanup.ConvertType( type );
54
55 switch ( type )
56 {
57 case "uint64": return "ulong";
58 case "uint32": return "uint";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Facepunch.Steamworks\Structs\UgcEditor.cs (line 261)
258
259 var r = SteamUGC.Internal.GetItemUpdateProgress( handle, ref processed, ref total );
260
261 switch ( r )
262 {
263 case ItemUpdateStatus.PreparingConfig:
264 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 8 hits
📄 Facepunch.Steamworks.Test\FriendsTest.cs (line 130)
127 }
128
129
130 public static void DrawImage( Image img )
131 {
132 var grad = " -:+#";
133
💬 Method DrawImage might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 Facepunch.Steamworks.Test\UserStatsTest.cs (line 42)
39 Console.WriteLine( $"players: {players}" );
40 }
41
42 public async Task StoreStats()
43 {
44 var result = Result.NotSettled;
45
💬 Method StoreStats might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS022 Exception thrown from implicit operator 18 hits
📄 Facepunch.Steamworks\Structs\SteamIpAddress.cs (line 23)
20 if ( value.Type == SteamIPType.Type4 )
21 return Utility.Int32ToIp( value.Ip4Address );
22
23 throw new System.Exception( $"Oops - can't convert SteamIPAddress to System.Net.IPAddress because no-one coded support for {value.Type} yet" );
24 }
25 }
26}
💬 An exception is thrown from implicit operator System.Net.IPAddress in type SteamIPAddress (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
📄 Facepunch.Steamworks\Structs\SteamIpAddress.cs (line 23)
20 if ( value.Type == SteamIPType.Type4 )
21 return Utility.Int32ToIp( value.Ip4Address );
22
23 throw new System.Exception( $"Oops - can't convert SteamIPAddress to System.Net.IPAddress because no-one coded support for {value.Type} yet" );
24 }
25 }
26}
💬 An exception is thrown from implicit operator System.Net.IPAddress in type SteamIPAddress (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
SS033 Async overload is available 4 hits
📄 Facepunch.Steamworks.Test\UgcEditor.cs (line 108)
105 var rand = new Random();
106 var testFile = new byte[1024 * 1024 * 32];
107 rand.NextBytes( testFile );
108 System.IO.File.WriteAllBytes( testFolder.FullName + "/testfile1.bin", testFile );
109
110 Console.WriteLine( testFolder.FullName );
111
💬 Async overload available for File.WriteAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Facepunch.Steamworks.Test\UgcEditor.cs (line 108)
105 var rand = new Random();
106 var testFile = new byte[1024 * 1024 * 32];
107 rand.NextBytes( testFile );
108 System.IO.File.WriteAllBytes( testFolder.FullName + "/testfile1.bin", testFile );
109
110 Console.WriteLine( testFolder.FullName );
111
💬 Async overload available for File.WriteAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS044 Attribute must specify [AttributeUsage] 36 hits
📄 Facepunch.Steamworks\Utility\Helpers.cs (line 125)
122 /// Prevent unity from stripping shit we depend on
123 /// https://docs.unity3d.com/Manual/ManagedCodeStripping.html
124 /// </summary>
125 internal class PreserveAttribute : System.Attribute { }
126}
💬 PreserveAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 Facepunch.Steamworks\Utility\Helpers.cs (line 116)
113 }
114 }
115
116 internal class MonoPInvokeCallbackAttribute : Attribute
117 {
118 public MonoPInvokeCallbackAttribute() { }
119 }
💬 MonoPInvokeCallbackAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS051 Locking on mutable reference 18 hits
📄 Facepunch.Steamworks\Utility\Helpers.cs (line 68)
65 /// </summary>
66 public static byte[] TakeBuffer( int minSize )
67 {
68 lock ( BufferPool )
69 {
70 BufferPoolIndex++;
71
💬 A lock was obtained on BufferPool but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Facepunch.Steamworks\Utility\Helpers.cs (line 68)
65 /// </summary>
66 public static byte[] TakeBuffer( int minSize )
67 {
68 lock ( BufferPool )
69 {
70 BufferPoolIndex++;
71
💬 A lock was obtained on BufferPool but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 22 hits
📄 Facepunch.Steamworks\Classes\Dispatch.cs (line 192)
189 var spaces = (columnSize - field.Name.Length);
190 if ( spaces < 0 ) spaces = 0;
191
192 str += $"{new String( ' ', spaces )}{field.Name}: {field.GetValue( strct )}\n";
193 }
194
195 return str.Trim( '\n' );
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Facepunch.Steamworks\Classes\Dispatch.cs (line 192)
189 var spaces = (columnSize - field.Name.Length);
190 if ( spaces < 0 ) spaces = 0;
191
192 str += $"{new String( ' ', spaces )}{field.Name}: {field.GetValue( strct )}\n";
193 }
194
195 return str.Trim( '\n' );
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

UnityCsReference

4864 total diagnostics across 21 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 34 hits
📄 Modules\XR\ScriptBindings\XRInput.bindings.cs (line 640)
637
638 public static DateTime now
639 {
640 get { return DateTime.Now; }
641 }
642
643 public static long LocalDateTimeToUnixTimeMilliseconds(DateTime date)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Modules\GameCenter\Managed\LocalService.cs (line 518)
515 if (progress >= 100.0)
516 achoo.SetCompleted(true);
517 achoo.SetHidden(false);
518 achoo.SetLastReportedDate(DateTime.Now);
519 achoo.percentCompleted = progress;
520 if (callback != null)
521 callback(true);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 180 hits
📄 Runtime\Export\Time\DiscreteTime.cs (line 70)
67
68 public const uint TicksPerSecond = Pow2Tps * NonPow2Tps;
69 public const double Tick = 1.0 / TicksPerSecond;
70 public const long MaxValueSeconds = long.MaxValue / TicksPerSecond;
71 public const long MinValueSeconds = long.MinValue / TicksPerSecond;
72
73 // Constants for supported frame rates
💬 The operands in the divisive expression long.MaxValue / TicksPerSecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Runtime\Export\Time\DiscreteTime.cs (line 71)
68 public const uint TicksPerSecond = Pow2Tps * NonPow2Tps;
69 public const double Tick = 1.0 / TicksPerSecond;
70 public const long MaxValueSeconds = long.MaxValue / TicksPerSecond;
71 public const long MinValueSeconds = long.MinValue / TicksPerSecond;
72
73 // Constants for supported frame rates
74 public const uint Tick5Fps = TicksPerSecond / 5;
💬 The operands in the divisive expression long.MinValue / TicksPerSecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 182 hits
📄 Modules\Accessibility\Managed\Hierarchy\AccessibilityHierarchy.cs (line 249)
246 m_Nodes.Remove(node.id);
247 }
248
249 if (m_RootNodes.Contains(node))
250 {
251 m_RootNodes.Remove(node);
252
💬 Type AccessibilityNode is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Runtime\Export\StaticShim\ShimManager.cs (line 61)
58
59 internal static void RemoveShim(ScreenShimBase shim)
60 {
61 if (s_ActiveScreenShim.Contains(shim))
62 {
63 s_ActiveScreenShim.Remove(shim);
64 ActiveShimChanged?.Invoke();
💬 Type ScreenShimBase is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 2 hits
📄 Modules\Accessibility\Managed\Hierarchy\AccessibilityNode.cs (line 16)
13 /// An instance of a node in the <see cref="AccessibilityHierarchy"/>, representing an element in the UI that the screen reader
14 /// can read, focus, and execute actions on.
15 /// </summary>
16 public class AccessibilityNode
17 {
18 private class ObservableList<T> : IList<T>, IReadOnlyList<T>, IList
19 {
💬 Equals() and GetHashcode() must be implemented together on AccessibilityNode (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 Modules\Accessibility\Managed\Hierarchy\AccessibilityNode.cs (line 16)
13 /// An instance of a node in the <see cref="AccessibilityHierarchy"/>, representing an element in the UI that the screen reader
14 /// can read, focus, and execute actions on.
15 /// </summary>
16 public class AccessibilityNode
17 {
18 private class ObservableList<T> : IList<T>, IReadOnlyList<T>, IList
19 {
💬 Equals() and GetHashcode() must be implemented together on AccessibilityNode (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 1190 hits
📄 Runtime\Jobs\ScriptBindings\JobHandle.bindings.cs (line 128)
125
126 public override int GetHashCode()
127 {
128 return jobGroup.GetHashCode();
129 }
130 }
131}
💬 GetHashCode() refers to mutable field jobGroup (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Modules\DSPGraph\Public\ScriptBindings\AudioHandle.bindings.cs (line 81)
78 {
79 unchecked
80 {
81 return ((int)m_Node * 397) ^ Version;
82 }
83 }
84
💬 GetHashCode() refers to mutable field m_Node (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 4 hits
📄 Modules\AndroidJNI\AndroidJava.cs (line 1763)
1760 IntPtr memberID = AndroidJNISafe.GetMethodID(jclass, "<init>", signature);
1761 if (memberID != IntPtr.Zero)
1762 return memberID;
1763 throw e;
1764 }
1765 finally
1766 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 Modules\AndroidJNI\AndroidJava.cs (line 1785)
1782 IntPtr memberID = GetMethodIDFallback(jclass, methodName, signature, isStatic);
1783 if (memberID != IntPtr.Zero)
1784 return memberID;
1785 throw e;
1786 }
1787 finally
1788 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS015 String placeholders in wrong order 4 hits
📄 Modules\IMGUI\LayoutEntry.cs (line 113)
110 string space = "";
111 for (int i = 0; i < indent; i++)
112 space += " ";
113 return space + string.Format("{1}-{0} (x:{2}-{3}, y:{4}-{5})", style != null ? style.name : "NULL", GetType(), rect.x, rect.xMax, rect.y, rect.yMax) +
114 " - W: " + minWidth + "-" + maxWidth + (stretchWidth != 0 ? "+" : "") + ", H: " + minHeight + "-" + maxHeight + (stretchHeight != 0 ? "+" : "");
115 }
116 }
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 Runtime\Export\Assertions\Assert\AssertionMessageUtil.cs (line 30)
27 public static string GetEqualityMessage(object actual, object expected, bool expectEqual)
28 {
29 return GetMessage(string.Format("Values are {0}equal.", expectEqual ? "not " : ""),
30 string.Format("{0} {2} {1}", actual, expected, expectEqual ? "==" : "!="));
31 }
32
33 public static string NullFailureMessage(object value, bool expectNull)
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2324 hits
📄 Modules\ContentLoad\Public\ContentLoad.bindings.cs (line 30)
27 }
28
29 [StructLayout(LayoutKind.Sequential)]
30 public struct ContentFileUnloadHandle
31 {
32 internal ContentFile Id;
33 public bool IsCompleted { get { return ContentLoadInterface.ContentFile_IsUnloadComplete(Id); } }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ContentFileUnloadHandle. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Modules\Input\Private\Input.cs (line 32)
29
30 // We pass this as a struct to make it less painful to change the OnUpdate() API if need be.
31 [StructLayout(LayoutKind.Explicit, Size = structSize, Pack = 1)]
32 internal unsafe struct NativeInputEventBuffer
33 {
34 public const int structSize = 20;
35 // NOTE: Keep this as the first field in the struct. This avoids alignment/packing issues
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NativeInputEventBuffer. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 116 hits
📄 Modules\Accessibility\Bindings\AccessibilityManager.bindings.cs (line 128)
125
126 foreach (var context in contexts)
127 {
128 switch (context.notification)
129 {
130 case AccessibilityNotification.ScreenReaderStatusChanged:
131 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Runtime\Export\Jobs\AtomicSafetyHandle.bindings.cs (line 280)
277 safety = (allocator == Allocator.Temp) ? GetTempMemoryHandle() : Create();
278 if(!Unity.Jobs.LowLevel.Unsafe.JobsUtility.IsExecutingJob)
279 return;
280 switch(allocator)
281 {
282 case Allocator.TempJob:
283 case Allocator.Persistent:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 300 hits
📄 Modules\Accessibility\Bindings\AccessibilityManager.bindings.cs (line 128)
125
126 foreach (var context in contexts)
127 {
128 switch (context.notification)
129 {
130 case AccessibilityNotification.ScreenReaderStatusChanged:
131 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Modules\XR\ScriptBindings\XRInput.bindings.cs (line 956)
953 [RequiredByNativeCode]
954 private static void InvokeConnectionEvent(UInt64 deviceId, ConnectionChangeType change)
955 {
956 switch (change)
957 {
958 case ConnectionChangeType.Connected:
959 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS022 Exception thrown from implicit operator 2 hits
📄 Modules\UIElements\Core\Renderer\SafeHandleAccess.cs (line 26)
23 public static implicit operator IntPtr(SafeHandleAccess a)
24 {
25 if (a.m_Handle == IntPtr.Zero)
26 throw new ArgumentNullException();
27 return a.m_Handle;
28 }
29 }
💬 An exception is thrown from implicit operator IntPtr in type SafeHandleAccess (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
📄 Modules\UIElements\Core\Renderer\SafeHandleAccess.cs (line 26)
23 public static implicit operator IntPtr(SafeHandleAccess a)
24 {
25 if (a.m_Handle == IntPtr.Zero)
26 throw new ArgumentNullException();
27 return a.m_Handle;
28 }
29 }
💬 An exception is thrown from implicit operator IntPtr in type SafeHandleAccess (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
SS023 Exception thrown from property getter 58 hits
📄 Modules\HierarchyCore\ScriptBindings\HierarchyViewModel.bindings.cs (line 751)
748 get
749 {
750 if (m_Version != m_ViewModel.m_Version)
751 throw new InvalidOperationException("HierarchyViewModel was modified.");
752
753 return ref HierarchyFlattenedNode.GetNodeByRef(in m_HierarchyFlattened[m_NodesPtr[m_Index]]);
754 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Modules\HierarchyCore\ScriptBindings\HierarchyFlattened.bindings.cs (line 281)
278 get
279 {
280 if (m_Version != m_HierarchyFlattened.m_Version)
281 throw new InvalidOperationException("HierarchyFlattened was modified.");
282
283 return ref m_NodesPtr[m_Index];
284 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 6 hits
📄 Modules\Properties\Runtime\Utility\TypeUtility.cs (line 294)
291 }
292
293 if (null == s_CreateTypeConstructor)
294 throw new InvalidProgramException();
295 }
296
297 /// <summary>
💬 An exception is thrown from TypeUtility its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 Modules\Properties\Runtime\PropertyBags\ContainerPropertyBag.cs (line 27)
24 {
25 if (!TypeTraits.IsContainer(typeof(TContainer)))
26 {
27 throw new InvalidOperationException($"Failed to create a property bag for Type=[{typeof(TContainer)}]. The type is not a valid container type.");
28 }
29 }
30
💬 An exception is thrown from ContainerPropertyBag its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS027 Exception thrown from Dispose 26 hits
📄 Runtime\Export\NativeArray\NativeArray.cs (line 215)
212
213 if (m_AllocatorLabel == Allocator.Invalid)
214 {
215 throw new InvalidOperationException("The NativeArray can not be Disposed because it was not allocated with a valid allocator.");
216 }
217
218 if (m_AllocatorLabel >= Allocator.FirstUserIndex)
💬 An exception is thrown from the Dispose() method in type NativeArray (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 Runtime\Export\NativeArray\NativeArray.cs (line 220)
217
218 if (m_AllocatorLabel >= Allocator.FirstUserIndex)
219 {
220 throw new InvalidOperationException("The NativeArray can not be Disposed because it was allocated with a custom allocator, use CollectionHelper.Dispose in com.unity.collections package.");
221 }
222
223 if (m_AllocatorLabel > Allocator.None)
💬 An exception is thrown from the Dispose() method in type NativeArray (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS044 Attribute must specify [AttributeUsage] 28 hits
📄 Runtime\Scripting\Internal\LifecycleManagement\LifecycleAttributeBase.cs (line 7)
4
5namespace Unity.Scripting.LifecycleManagement
6{
7 internal abstract class LifecycleAttributeBase : RequiredMemberAttribute
8 {
9 }
10}
💬 LifecycleAttributeBase should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 Runtime\Scripting\Internal\LifecycleManagement\RequiredMemberAttribute.cs (line 9)
6
7namespace Unity.Scripting
8{
9 internal abstract class RequiredMemberAttribute : Attribute
10 {
11 }
12}
💬 RequiredMemberAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS046 Unbounded stackalloc 14 hits
📄 Modules\TextCoreTextEngine\Managed\TextGenerator\RichTextTagParser.cs (line 419)
416 Debug.Assert(tag.end <= startingPos, "Tag end pass the point where we should start parsing");
417 Debug.Assert(allTags.Contains(tag));
418 }
419 Span<int?> parents = stackalloc int?[allTags.Count];
420 Span<int?> lastTagOfType = stackalloc int?[TagsInfo.Length];
421
422 int i = -1;
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
📄 Modules\TextCoreTextEngine\Managed\TextGenerator\RichTextTagParser.cs (line 420)
417 Debug.Assert(allTags.Contains(tag));
418 }
419 Span<int?> parents = stackalloc int?[allTags.Count];
420 Span<int?> lastTagOfType = stackalloc int?[TagsInfo.Length];
421
422 int i = -1;
423 foreach (var tag in allTags)
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
SS050 Parameter assigned in constructor 8 hits
📄 Modules\IMGUI\GUIStyle.cs (line 89)
86 if (other == null)
87 {
88 Debug.LogError("Copied style is null. Using StyleNotFound instead.");
89 other = GUISkin.error;
90 }
91 m_Ptr = Internal_Copy(this, other);
92 }
💬 Suspicious assignment of parameter other in constructor of GUIStyle (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
📄 Modules\IMGUI\LayoutEntry.cs (line 55)
52 minHeight = _minHeight;
53 maxHeight = _maxHeight;
54 if (_style == null)
55 _style = GUIStyle.none;
56 style = _style;
57 }
58
💬 Suspicious assignment of parameter _style in constructor of GUILayoutEntry (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
SS051 Locking on mutable reference 42 hits
📄 Modules\Accessibility\Bindings\AccessibilityManager.bindings.cs (line 115)
112
113 NotificationContext[] contexts;
114
115 lock (asyncNotificationContexts)
116 {
117 if (asyncNotificationContexts.Count == 0)
118 return;
💬 A lock was obtained on asyncNotificationContexts but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Modules\Accessibility\Bindings\AccessibilityManager.bindings.cs (line 226)
223
224 internal static void QueueNotification(NotificationContext notification)
225 {
226 lock (asyncNotificationContexts)
227 {
228 asyncNotificationContexts.Enqueue(notification);
229 }
💬 A lock was obtained on asyncNotificationContexts but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 30 hits
📄 Modules\InputForUI\Sanitizer\EventSanitizer.cs (line 124)
121 Debug.LogWarning(
122 $"ButtonReleased for not the last pressed button should have click count == 1, but got '{releaseEvent}'");
123 }
124 _activeButtons.RemoveAt(i);
125 return;
126 }
127
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 Runtime\Export\RenderPipeline\RenderPipelineGlobalSettings.cs (line 86)
83 {
84 if (settingsList[i] == null)
85 {
86 settingsList.RemoveAt(i);
87 --i;
88 }
89 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 26 hits
📄 Runtime\Export\Unsafe\UnsafeUtility.cs (line 32)
29 foreach (FieldInfo f in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
30 {
31 if (!IsBlittableValueType(f.FieldType))
32 ret += GetReasonForTypeNonBlittableImpl(f.FieldType, String.Format("{0}.{1}", name, f.Name));
33 }
34 return ret;
35 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Modules\IMGUI\LayoutEntry.cs (line 112)
109 {
110 string space = "";
111 for (int i = 0; i < indent; i++)
112 space += " ";
113 return space + string.Format("{1}-{0} (x:{2}-{3}, y:{4}-{5})", style != null ? style.name : "NULL", GetType(), rect.x, rect.xMax, rect.y, rect.yMax) +
114 " - W: " + minWidth + "-" + maxWidth + (stretchWidth != 0 ? "+" : "") + ", H: " + minHeight + "-" + maxHeight + (stretchHeight != 0 ? "+" : "");
115 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 288 hits
📄 Modules\UIElements\Core\VisualElementHierarchy.cs (line 90)
87
88 // each element has a ref to the root panel for internal bookkeeping
89 // this will be null until a visual tree is added to a panel
90 internal BaseVisualElementPanel elementPanel
91 {
92 [VisibleToOtherModules("UnityEditor.UIBuilderModule")]
93 get;
💬 Disposable field elementPanel in type VisualElement is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Modules\UIElements\Core\Events\MouseEvents.cs (line 1061)
1058 /// <summary>
1059 /// The event that triggered the ContextualMenuPopulateEvent.
1060 /// </summary>
1061 public EventBase triggerEvent { get; private set; }
1062
1063 ContextualMenuManager m_ContextualMenuManager;
1064
💬 Disposable field triggerEvent in type ContextualMenuPopulateEvent is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

ServiceStack

4340 total diagnostics across 28 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 192 hits
📄 ServiceStack\src\ServiceStack.Common\Script\Methods\DefaultScripts.cs (line 68)
65 }
66
67 // methods without arguments can be used in bindings, e.g. {{ now |> dateFormat }}
68 public DateTime now() => DateTime.Now;
69 public DateTime utcNow() => DateTime.UtcNow;
70
71 public DateTimeOffset nowOffset() => DateTimeOffset.Now;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 ServiceStack\src\ServiceStack.Common\Script\Methods\DefaultScripts.cs (line 68)
65 }
66
67 // methods without arguments can be used in bindings, e.g. {{ now |> dateFormat }}
68 public DateTime now() => DateTime.Now;
69 public DateTime utcNow() => DateTime.UtcNow;
70
71 public DateTimeOffset nowOffset() => DateTimeOffset.Now;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 268 hits
📄 ServiceStack\src\ServiceStack.Client\CryptUtils.cs (line 220)
217 public const int KeySize = 256;
218 public const int KeySizeBytes = 256 / 8;
219 public const int BlockSize = 128;
220 public const int BlockSizeBytes = 128 / 8;
221
222 public static SymmetricAlgorithm CreateSymmetricAlgorithm()
223 {
💬 The operands in the divisive expression 128 / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 ServiceStack\src\ServiceStack.Client\CryptUtils.cs (line 218)
215 public static class AesUtils
216 {
217 public const int KeySize = 256;
218 public const int KeySizeBytes = 256 / 8;
219 public const int BlockSize = 128;
220 public const int BlockSizeBytes = 128 / 8;
221
💬 The operands in the divisive expression 256 / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 302 hits
📄 ServiceStack\src\ServiceStack.Common\Script\ScriptLanguage.Lisp.cs (line 3005)
3002
3003 // Mapping from a quote symbol to its string representation
3004 static readonly Dictionary<Sym, string> Quotes = new Dictionary<Sym, string> {
3005 [QUOTE] = "'",
3006 [QUASIQUOTE] = "`",
3007 [UNQUOTE] = ",",
3008 [UNQUOTE_SPLICING] = ",@"
💬 Type Sym is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 ServiceStack\src\ServiceStack.Common\Script\ScriptLanguage.Lisp.cs (line 3006)
3003 // Mapping from a quote symbol to its string representation
3004 static readonly Dictionary<Sym, string> Quotes = new Dictionary<Sym, string> {
3005 [QUOTE] = "'",
3006 [QUASIQUOTE] = "`",
3007 [UNQUOTE] = ",",
3008 [UNQUOTE_SPLICING] = ",@"
3009 };
💬 Type Sym is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 16 hits
📄 ServiceStack\src\ServiceStack.Common\Script\ScriptLanguage.Lisp.cs (line 532)
529 }
530
531 /// <summary>Lisp symbol</summary>
532 public class Sym {
533 /// <summary>The symbol's name</summary>
534 public string Name { get; }
535
💬 Equals() and GetHashcode() must be implemented together on Sym (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 ServiceStack\src\ServiceStack.Common\Script\ScriptLanguage.Lisp.cs (line 532)
529 }
530
531 /// <summary>Lisp symbol</summary>
532 public class Sym {
533 /// <summary>The symbol's name</summary>
534 public string Name { get; }
535
💬 Equals() and GetHashcode() must be implemented together on Sym (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 620 hits
📄 ServiceStack\src\ServiceStack.Interfaces\ValidationRule.cs (line 96)
93 {
94 unchecked
95 {
96 var hashCode = Id;
97 hashCode = (hashCode * 397) ^ (Type != null ? Type.GetHashCode() : 0);
98 hashCode = (hashCode * 397) ^ (Field != null ? Field.GetHashCode() : 0);
99 hashCode = (hashCode * 397) ^ (CreatedBy != null ? CreatedBy.GetHashCode() : 0);
💬 GetHashCode() refers to mutable property Id (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 ServiceStack\src\ServiceStack.Interfaces\ValidationRule.cs (line 97)
94 unchecked
95 {
96 var hashCode = Id;
97 hashCode = (hashCode * 397) ^ (Type != null ? Type.GetHashCode() : 0);
98 hashCode = (hashCode * 397) ^ (Field != null ? Field.GetHashCode() : 0);
99 hashCode = (hashCode * 397) ^ (CreatedBy != null ? CreatedBy.GetHashCode() : 0);
100 hashCode = (hashCode * 397) ^ CreatedDate.GetHashCode();
💬 GetHashCode() refers to mutable property Type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 4 hits
📄 ServiceStack\src\ServiceStack\Host\HttpListener\HttpListenerBase.cs (line 144)
141 }
142 }
143
144 throw ex;
145 }
146
147 ThreadPool.QueueUserWorkItem(listenCallback);
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 ServiceStack\src\ServiceStack.Razor\Support\Markdown\TextBlock.cs (line 188)
185 }
186 catch (Exception ex)
187 {
188 throw ex;
189 }
190 }
191
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS015 String placeholders in wrong order 6 hits
📄 ServiceStack\src\ServiceStack.Razor\Support\Markdown\Markdown.cs (line 1174)
1171 return _horizontalRules.Replace(text, "<hr" + _emptyElementSuffix + "\n");
1172 }
1173
1174 private static string _wholeList = string.Format(@"
1175 ( # $1 = whole list
1176 ( # $2
1177 [ ]{{0,{1}}}
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 ServiceStack\src\ServiceStack.Razor\Support\Markdown\Markdown.cs (line 1138)
1135 {
1136 string header = match.Groups[1].Value;
1137 int level = match.Groups[2].Value.StartsWith("=") ? 1 : 2;
1138 return string.Format("<h{1}>{0}</h{1}>\n\n", RunSpanGamut(header), level);
1139 }
1140
1141 private string AtxHeaderEvaluator(Match match)
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 128 hits
📄 ServiceStack\src\ServiceStack.Interfaces\Jobs\IBackgroundJobs.cs (line 158)
155/// <summary>
156/// Status Update of a Job
157/// </summary>
158public struct BackgroundJobStatusUpdate(BackgroundJob job, double? progress=null, string? status=null, string? log=null)
159{
160 public BackgroundJob Job { get; } = job;
161 public double? Progress { get; } = progress;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BackgroundJobStatusUpdate. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 ServiceStack\src\ServiceStack.Interfaces\ScriptValue.cs (line 32)
29 bool NoCache { get; set; }
30}
31
32public struct ScriptValue : IScriptValue
33{
34 public object? Value { get; set; }
35 public string? Expression { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ScriptValue. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 108 hits
📄 ServiceStack\src\ServiceStack.Common\ExpressionUtils.cs (line 105)
102
103 public static object GetValue(this MemberBinding binding)
104 {
105 switch (binding.BindingType)
106 {
107 case MemberBindingType.Assignment:
108 var assign = (MemberAssignment)binding;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 ServiceStack\src\ServiceStack.Common\ViewUtils.cs (line 668)
665 public static string StyleText(string text, TextStyle textStyle)
666 {
667 if (text == null) return null;
668 switch (textStyle)
669 {
670 case TextStyle.SplitCase:
671 return DefaultScripts.splitCase(text);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 428 hits
📄 ServiceStack\src\ServiceStack.Client\WebRequestUtils.cs (line 99)
96 value = value.Substring(1);
97 if (value.EndsWith("\""))
98 value = value.Substring(0, value.Length - 1);
99 switch (name)
100 {
101 case "qop":
102 qop = value;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 ServiceStack\src\ServiceStack.Client\CachedServiceClient.cs (line 161)
158 var kvp = part.Split('=');
159 var key = kvp[0].Trim().ToLowerInvariant();
160
161 switch (key)
162 {
163 case "max-age":
164 if (kvp.Length == 2 && long.TryParse(kvp[1], out secs))
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 38 hits
📄 ServiceStack\src\ServiceStack.Common\Script\PageResult.cs (line 1186)
1183 catch (AggregateException e)
1184 {
1185 var ex = e.UnwrapIfSingleException();
1186 throw ex;
1187 }
1188 }
1189 }
💬 An exception is thrown from the getter of property Result (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 ServiceStack\src\ServiceStack.Common\Script\PageResult.cs (line 1186)
1183 catch (AggregateException e)
1184 {
1185 var ex = e.UnwrapIfSingleException();
1186 throw ex;
1187 }
1188 }
1189 }
💬 An exception is thrown from the getter of property Result (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 156 hits
📄 ServiceStack\src\ServiceStack.Client\AsyncServiceClient.cs (line 319)
316 if (isBinary)
317 {
318 HttpLog.Append("(base64) ");
319 HttpLog.AppendLine(Convert.ToBase64String(ms.ReadFully()));
320 }
321 else
322 {
💬 Async overload available for StreamExtensions.ReadFully (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 ServiceStack\src\ServiceStack.Client\AsyncServiceClient.cs (line 323)
320 }
321 else
322 {
323 HttpLog.AppendLine(ms.ReadToEnd());
324 }
325 HttpLog.AppendLine().AppendLine();
326 ms.Position = 0;
💬 Async overload available for StreamExtensions.ReadToEnd (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 170 hits
📄 ServiceStack\src\ServiceStack.Client\ServerEventsClient.cs (line 1195)
1192 public static Task<List<ServerEventUser>> GetChannelSubscribersAsync(this ServerEventsClient client)
1193 {
1194 var responseTask = client.ServiceClient.GetAsync(new GetEventSubscribers { Channels = client.Channels });
1195 return responseTask.ContinueWith(task => task.Result.Select(x => x.ToServerEventUser()).ToList());
1196 }
1197
1198 internal static ServerEventUser ToServerEventUser(this Dictionary<string, string> map)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 ServiceStack\src\ServiceStack.Client\ServerEventsClient.cs (line 712)
709
710 Interlocked.Exchange(ref noOfContinuousErrors, 0);
711
712 int len = task.Result;
713 if (len > 0)
714 {
715 var text = overflowText + encoding.GetString(buffer, 0, len);
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 8 hits
📄 ServiceStack\src\ServiceStack\Host\Handlers\SoapHandler.cs (line 127)
124
125 if (hasRequestFilters)
126 {
127 HostContext.ApplyRequestFiltersAsync(httpReq, httpRes, request).Wait();
128 if (httpRes.IsClosed)
129 return EmptyResponse(requestMsg, requestType);
130 }
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 ServiceStack\src\ServiceStack\Host\Handlers\SoapHandler.cs (line 137)
134
135 response = appHost.ApplyResponseConvertersAsync(httpReq, response).Result;
136
137 appHost.ApplyResponseFiltersAsync(httpReq, httpRes, response).Wait();
138 if (httpRes.IsClosed)
139 return EmptyResponse(requestMsg, requestType);
140
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS037 HttpClient instantiated directly 48 hits
📄 ServiceStack\src\ServiceStack.Client\ServiceClientBase.cs (line 84)
81 {
82 var cookies = new CookieContainer();
83#if NET6_0_OR_GREATER
84 this.HttpClient = new System.Net.Http.HttpClient(new System.Net.Http.HttpClientHandler {
85 CookieContainer = cookies,
86 }, disposeHandler: true);
87#endif
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 ServiceStack\src\ServiceStack.Client\ServerEventsClient.cs (line 236)
233 {
234 Interlocked.Increment(ref timesStarted);
235
236 httpClient = new HttpClient(HttpClientHandlerFactory(ServiceClient), disposeHandler:true);
237 httpClient.Timeout = Timeout.InfiniteTimeSpan;
238
239 var httpReq = new HttpRequestMessage(HttpMethod.Get, EventStreamUri)
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS038 HttpContext stored in a field 18 hits
📄 ServiceStack\src\ServiceStack\HttpContextFactory.cs (line 38)
35 Scheme = baseUrl.LeftPart("://");
36 IsHttps = Scheme == "https";
37 }
38 public HttpContext httpContext;
39 public override HttpContext HttpContext => httpContext;
40 public override string Method { get; set; } = "GET";
41 public override string Scheme { get; set; }
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
📄 ServiceStack\src\ServiceStack\HttpContextFactory.cs (line 61)
58
59 public class TestResponse : HttpResponse
60 {
61 public HttpContext httpContext;
62 public override HttpContext HttpContext => httpContext;
63
64 public override int StatusCode { get; set; } = 200;
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
SS041 Unnecessary enumerable materialization 14 hits
📄 ServiceStack\src\ServiceStack\FilesUploadFeature.cs (line 172)
169 var ext = vfsPath.LastRightPart('.');
170 if (!location.AllowExtensions.Contains(ext))
171 throw new ArgumentException(Errors.InvalidFileExtensionFmt.LocalizeFmt(req, string.Join(", ",
172 location.AllowExtensions.Select(x => '.' + x).ToList().OrderBy(x => x))), param);
173 }
174
175 if (location.MinFileBytes != null && file.ContentLength < location.MinFileBytes)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 ServiceStack\src\ServiceStack\FilesUploadFeature.cs (line 172)
169 var ext = vfsPath.LastRightPart('.');
170 if (!location.AllowExtensions.Contains(ext))
171 throw new ArgumentException(Errors.InvalidFileExtensionFmt.LocalizeFmt(req, string.Join(", ",
172 location.AllowExtensions.Select(x => '.' + x).ToList().OrderBy(x => x))), param);
173 }
174
175 if (location.MinFileBytes != null && file.ContentLength < location.MinFileBytes)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 214 hits
📄 ServiceStack\src\ServiceStack.Interfaces\AttributeBase.cs (line 8)
5
6namespace ServiceStack;
7
8public class AttributeBase : Attribute
9{
10 protected readonly Guid typeId = Guid.NewGuid(); //Hack required to give Attributes unique identity
11}
💬 AttributeBase should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 ServiceStack\src\ServiceStack.Interfaces\AttributeBase.cs (line 13)
10 protected readonly Guid typeId = Guid.NewGuid(); //Hack required to give Attributes unique identity
11}
12
13public class MetadataAttributeBase : AttributeBase, IReflectAttributeFilter
14{
15 /// <summary>
16 /// Don't include default bool or nullable int default values
💬 MetadataAttributeBase should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS048 Locking on discouraged object (string, Type, this) 76 hits
📄 ServiceStack\src\ServiceStack.Client\ServerEventsClient.cs (line 1098)
1095
1096 public virtual string GetStatsDescription()
1097 {
1098 lock (this)
1099 {
1100 var sb = StringBuilderCache.Allocate().Append(GetType().Name + " SERVER STATS:\n");
1101 sb.AppendLine("===============");
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 ServiceStack\src\ServiceStack.Client\ServerEventsClient.cs (line 1098)
1095
1096 public virtual string GetStatsDescription()
1097 {
1098 lock (this)
1099 {
1100 var sb = StringBuilderCache.Allocate().Append(GetType().Name + " SERVER STATS:\n");
1101 sb.AppendLine("===============");
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 32 hits
📄 ServiceStack\src\ServiceStack.Server\Auth\OrmLiteAuthRepository.cs (line 338)
335 if (ForceCaseInsensitiveUserNameSearch)
336 {
337 userAuth = isEmail
338 ? db.Select<TUserAuth>(q => q.Email.ToLower() == lowerUserName).FirstOrDefault()
339 : db.Select<TUserAuth>(q => q.UserName.ToLower() == lowerUserName).FirstOrDefault();
340 }
341
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 ServiceStack\src\ServiceStack.Server\Auth\OrmLiteAuthRepository.cs (line 339)
336 {
337 userAuth = isEmail
338 ? db.Select<TUserAuth>(q => q.Email.ToLower() == lowerUserName).FirstOrDefault()
339 : db.Select<TUserAuth>(q => q.UserName.ToLower() == lowerUserName).FirstOrDefault();
340 }
341
342 return userAuth;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS050 Parameter assigned in constructor 8 hits
📄 ServiceStack\src\ServiceStack.Common\MiniProfiler\Data\ProfiledConnection.cs (line 45)
42 public ProfiledConnection(IDbConnection connection, IDbProfiler profiler, bool autoDisposeConnection = true)
43 {
44 var hasConn = connection as IHasDbConnection;
45 if (hasConn != null) connection = hasConn.DbConnection;
46 var dbConn = connection as DbConnection;
47
48 if (dbConn == null)
💬 Suspicious assignment of parameter connection in constructor of ProfiledConnection (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
📄 ServiceStack\src\ServiceStack.Common\MiniProfiler\Data\ProfiledConnection.cs (line 45)
42 public ProfiledConnection(IDbConnection connection, IDbProfiler profiler, bool autoDisposeConnection = true)
43 {
44 var hasConn = connection as IHasDbConnection;
45 if (hasConn != null) connection = hasConn.DbConnection;
46 var dbConn = connection as DbConnection;
47
48 if (dbConn == null)
💬 Suspicious assignment of parameter connection in constructor of ProfiledConnection (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
SS051 Locking on mutable reference 200 hits
📄 ServiceStack\src\ServiceStack\Funq\Container.cs (line 22)
19
20 public int DisposablesCount
21 {
22 get { lock (disposables) return disposables.Count; }
23 }
24
25 // Disposable components include factory-scoped instances that we don't keep
💬 A lock was obtained on disposables but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 ServiceStack\src\ServiceStack\Funq\Container.cs (line 55)
52 public Container CreateChildContainer()
53 {
54 var child = InstantiateChildContainer();
55 lock (childContainers) childContainers.Push(child);
56 return child;
57 }
58
💬 A lock was obtained on childContainers but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS056 HttpRequest.Form read synchronously 24 hits
📄 ServiceStack\src\ServiceStack\Host\NetCore\NetCoreRequest.cs (line 170)
167 var nvc = new NameValueCollection();
168 if (request.HasFormContentType)
169 {
170 foreach (var form in request.Form)
171 {
172 nvc.Add(form.Key, form.Value);
173 }
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
📄 ServiceStack\src\ServiceStack\Host\NetCore\NetCoreRequest.cs (line 242)
239 if (!request.HasFormContentType)
240 return Array.Empty<IHttpFile>();
241
242 var filesCount = request.Form.Files.Count;
243 files = new IHttpFile[filesCount];
244 for (var i=0; i<filesCount; i++)
245 {
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
SS057 Collection manipulated during traversal 64 hits
📄 ServiceStack\src\ServiceStack\Html\MarkdownDeep\BlockProcessor.cs (line 1269)
1266 {
1267 lines[i - 1].contentEnd = lines[i].contentEnd;
1268 FreeBlock(lines[i]);
1269 lines.RemoveAt(i);
1270 i--;
1271 continue;
1272 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 ServiceStack\src\ServiceStack\Html\MarkdownDeep\BlockProcessor.cs (line 1378)
1375 {
1376 lines[i - 1].contentEnd = lines[i].contentEnd;
1377 FreeBlock(lines[i]);
1378 lines.RemoveAt(i);
1379 i--;
1380 continue;
1381 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 148 hits
📄 ServiceStack\src\ServiceStack.Client\WebRequestUtils.cs (line 191)
188 var pad = "";
189 for (var i = 0; i < (8 - ("" + num).Length); i++)
190 {
191 pad += "0";
192 }
193 var ret = pad + num;
194 return ret;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 ServiceStack\src\ServiceStack.Client\WebRequestUtils.cs (line 191)
188 var pad = "";
189 for (var i = 0; i < (8 - ("" + num).Length); i++)
190 {
191 pad += "0";
192 }
193 var ret = pad + num;
194 return ret;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 318 hits
📄 ServiceStack\src\ServiceStack.Client\ServiceClientBase.cs (line 1104)
1101 var webRequest = SendRequest(httpMethod, requestUri, request);
1102 using var response = await webRequest.GetResponseAsync();
1103 ApplyWebResponseFilters(response);
1104 using var stream = response.ResponseStream();
1105 return await stream.ReadFullyAsync();
1106 }
1107
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 ServiceStack\src\ServiceStack.Client\ServiceClientBase.cs (line 1743)
1740
1741 if (requestBody != null)
1742 {
1743 using var reqStream = PclExport.Instance.GetRequestStream(webReq);
1744 using var writer = new StreamWriter(reqStream, HttpUtils.UseEncoding);
1745 await writer.WriteAsync(requestBody).ConfigAwait();
1746 }
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 14 hits
📄 ServiceStack\src\ServiceStack\ServerEventsFeature.cs (line 1474)
1471 return;
1472
1473 var subs = map.TryGet(key);
1474 if (subs == null || subs.Count == 0)
1475 return;
1476
1477 var now = DateTime.UtcNow;
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 ServiceStack\src\ServiceStack\ServerEventsFeature.cs (line 1474)
1471 return;
1472
1473 var subs = map.TryGet(key);
1474 if (subs == null || subs.Count == 0)
1475 return;
1476
1477 var now = DateTime.UtcNow;
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
SS066 Disposable field is not disposed 718 hits
📄 ServiceStack\src\ServiceStack.Client\ServerEventsClient.cs (line 93)
90 byte[] buffer;
91 readonly Encoding encoding = Encoding.UTF8;
92
93 CancellationTokenSource cancel;
94 private ITimer heartbeatTimer;
95
96 public ServerEventConnect ConnectionInfo { get; private set; }
💬 Disposable field cancel in type ServerEventsClient is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 ServiceStack\src\ServiceStack.Client\ServerEventsClient.cs (line 94)
91 readonly Encoding encoding = Encoding.UTF8;
92
93 CancellationTokenSource cancel;
94 private ITimer heartbeatTimer;
95
96 public ServerEventConnect ConnectionInfo { get; private set; }
97
💬 Disposable field heartbeatTimer in type ServerEventsClient is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

SqlSugar

3788 total diagnostics across 22 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2062 hits
📄 Src\Asp.NetCore2\NugetTest\Demo\Demo0_SqlSugarClient.cs (line 44)
41 Console.WriteLine(db.Ado.Connection.ConnectionString);
42 };
43 Console.WriteLine("Master:");
44 db.Insertable(new Order() { Name = "abc", CustomId = 1, CreateTime = DateTime.Now }).ExecuteCommand();
45 Console.WriteLine("Slave:");
46 db.Queryable<Order>().First();
47 Console.WriteLine("#### MasterSlave End ####");
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Src\Asp.NetCore2\NugetTest\Demo\Demo0_SqlSugarClient.cs (line 78)
75
76 //Create tables
77 db.CodeFirst.InitTables(typeof(OrderItem),typeof(Order));
78 var id = db.Insertable(new Order() { Name = "order1", CustomId = 1, Price = 0, CreateTime = DateTime.Now }).ExecuteReturnIdentity();
79
80 //Insert data
81 db.Insertable(new OrderItem() { OrderId = id, Price = 0, CreateTime=DateTime.Now }).ExecuteCommand();
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 90 hits
📄 Src\Asp.NetCore2\TDengine.Ado.Data\SqlSugar.TDengine\Helper.cs (line 50)
47 public static DateTime Long16ToDateTime(long timestampInMicroseconds)
48 {
49 // 计算秒和微秒部分
50 long seconds = timestampInMicroseconds / 1000000;
51 long microseconds = timestampInMicroseconds % 1000000;
52
53 // 创建 DateTimeOffset 对象,设置秒和微秒部分
💬 The operands in the divisive expression timestampInMicroseconds / 1000000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Src\Asp.NetCore2\TDengine.Ado.Data\SqlSugar.TDengine\Helper.cs (line 70)
67 public static DateTime Long19ToDateTime(long timestampInNanoseconds)
68 {
69 // 计算秒和纳秒部分
70 long seconds = timestampInNanoseconds / 1000000000;
71 long nanoseconds = timestampInNanoseconds % 1000000000;
72
73 // 创建 DateTimeOffset 对象,设置秒和纳秒部分
💬 The operands in the divisive expression timestampInNanoseconds / 1000000000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 72 hits
📄 Src\Asp.NetCore2\TDengine.Ado.Data\SqlSugar.TDengine\TdengineParameterCollection.cs (line 49)
46
47 public override bool Contains(object value)
48 {
49 return parameters.Contains((TDengineParameter)value);
50 }
51
52 public override void CopyTo(Array array, int index)
💬 Type TDengineParameter is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Src\Asp.NetCore2\SqlSugar\Utilities\UtilMethods.cs (line 136)
133 DataRow newRow = finalTable.NewRow();
134 foreach (DataColumn column in table.Columns)
135 {
136 var value = row[column];
137 if (value is DateTimeOffset dto)
138 newRow[column.ColumnName] = dto.DateTime;
139 else
💬 Type DataColumn is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 4 hits
📄 Src\Asp.NetCore2\SqlSeverTest\UserTestCases\UnitTest\Unitasf1\ProductProcessUnit.cs (line 99)
96 /// </summary>
97 public override int GetHashCode()
98 {
99 return (Id == null) ? 0 : Id.GetHashCode();
100 }
101
102 /// <summary>
💬 GetHashCode() refers to mutable property Id (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Src\Asp.NetCore2\SqlSeverTest\UserTestCases\UnitTest\Unitasf1\ProductProcessUnit.cs (line 99)
96 /// </summary>
97 public override int GetHashCode()
98 {
99 return (Id == null) ? 0 : Id.GetHashCode();
100 }
101
102 /// <summary>
💬 GetHashCode() refers to mutable property Id (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS009 Random instantiated in a loop 4 hits
📄 Src\Asp.NetCore2\QuestDbTest\Demo\DemoZ_Thread.cs (line 44)
41 {
42 var sw = new Stopwatch();
43 sw.Start();
44 Random random = new Random();
45 while (sw.Elapsed < TimeSpan.FromSeconds(20))
46 {
47 var param = new { userid = random.Next(0, 10000000) };
💬 Variable random of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
📄 Src\Asp.NetCore2\QuestDbTest\Demo\DemoZ_Thread.cs (line 88)
85 {
86 var sw = new Stopwatch();
87 sw.Start();
88 Random random = new Random();
89 while (sw.Elapsed < TimeSpan.FromSeconds(10))
90 {
91 try
💬 Variable random of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
SS013 Rethrow exception without losing stacktrace 174 hits
📄 Src\Asp.NetCore2\SqlSugar\Abstract\CodeFirstProvider\CodeFirstProvider.cs (line 249)
246 }
247 catch (Exception ex)
248 {
249 throw ex;
250 }
251 finally
252 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 Src\Asp.NetCore2\SqlSugar\Abstract\AdoProvider\AdoProvider.cs (line 507)
504 CommandType = CommandType.Text;
505 if (ErrorEvent != null)
506 ExecuteErrorEvent(sql, parameters, ex);
507 throw ex;
508 }
509 finally
510 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS015 String placeholders in wrong order 118 hits
📄 Src\Asp.NetCore2\SqlSugar\ExpressionsToSql\DbMethods\DefaultDbMethod.cs (line 277)
274 var parameter = model.Args[0];
275 var parameter2 = model.Args[1];
276 var parameter3 = model.Args[2];
277 return string.Format(" (DATEDIFF({2},{0},{1})=0) ", parameter.MemberName, parameter2.MemberName, parameter3.MemberValue);
278 }
279
280 public virtual string DateAddByType(MethodCallExpressionModel model)
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 Src\Asp.NetCore2\SqlSugar\ExpressionsToSql\DbMethods\DefaultDbMethod.cs (line 285)
282 var parameter = model.Args[0];
283 var parameter2 = model.Args[1];
284 var parameter3 = model.Args[2];
285 return string.Format(" (DATEADD({2},{1},{0})) ", parameter.MemberName, parameter2.MemberName, parameter3.MemberValue);
286 }
287
288 public virtual string DateAddDay(MethodCallExpressionModel model)
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 Src\Asp.NetCore2\SqlSugar\Interface\IStorageable.cs (line 103)
100 Other=4,
101 Ignore=5,
102 }
103 internal struct KeyValuePair<TKey, TValue,TValue2>
104 {
105 public TKey key;
106 public TValue value1;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct KeyValuePair. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Src\Asp.NetCore2\SqlSugar\Entities\DiscriminatorObject .cs (line 9)
6
7namespace SqlSugar
8{
9 public struct DiscriminatorObject
10 {
11 public string FieldName { get; set; }
12 public string FieldValue { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DiscriminatorObject. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 10 hits
📄 Src\Asp.NetCore2\SqlSugar\ExpressionsToSql\ResolveItems\MemberConstExpressionResolve.cs (line 19)
16 object value = ExpressionTool.GetMemberValue(expression.Member, expression);
17 var baseParameter = parameter.BaseParameter;
18 var isSetTempData = baseParameter.CommonTempData.HasValue() && baseParameter.CommonTempData.Equals(CommonTempDataType.Result);
19 switch (parameter.Context.ResolveType)
20 {
21 case ResolveExpressType.Update:
22 case ResolveExpressType.SelectSingle:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Src\Asp.NetCore2\SqlSugar\Realization\Sqlite\SqlBuilder\SqliteExpressionContext.cs (line 277)
274 var parameter3 = model.Args[2].MemberValue;
275 var type = (DateType)Enum.Parse(typeof(DateType), parameter3.ObjToString(), false);
276 int time = 1;
277 switch (type)
278 {
279 case DateType.Year:
280 time = time * 1 / 365;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 26 hits
📄 Src\Asp.NetCore2\SqlSugar\ExpressionsToSql\ResolveItems\MemberConstExpressionResolve.cs (line 19)
16 object value = ExpressionTool.GetMemberValue(expression.Member, expression);
17 var baseParameter = parameter.BaseParameter;
18 var isSetTempData = baseParameter.CommonTempData.HasValue() && baseParameter.CommonTempData.Equals(CommonTempDataType.Result);
19 switch (parameter.Context.ResolveType)
20 {
21 case ResolveExpressType.Update:
22 case ResolveExpressType.SelectSingle:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Src\Asp.NetCore2\SqlSugar\Realization\Sqlite\SqlBuilder\SqliteExpressionContext.cs (line 277)
274 var parameter3 = model.Args[2].MemberValue;
275 var type = (DateType)Enum.Parse(typeof(DateType), parameter3.ObjToString(), false);
276 int time = 1;
277 switch (type)
278 {
279 case DateType.Year:
280 time = time * 1 / 365;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 26 hits
📄 Src\Asp.NetCore2\SqlSugar\Realization\MySql\MySqlProvider.cs (line 40)
37 {
38 if (ex is SqlSugarException)
39 {
40 throw ex;
41 }
42 else
43 {
💬 An exception is thrown from the getter of property Connection (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Src\Asp.NetCore2\SqlSugar.TDSQLForPGODBC\TDSQLForPG\TDSQLForPGODBCProvider.cs (line 33)
30 }
31 catch (Exception ex)
32 {
33 throw ex;
34 }
35 }
36 return base._DbConnection;
💬 An exception is thrown from the getter of property Connection (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 2 hits
📄 Src\Asp.NetCore2\SqlSeverTest\UserTestCases\UnitTest\UValidateExtensions.cs (line 40)
37
38 if (_validateExtensionsType == null)
39 {
40 throw new Exception("Could not find SqlSugar.ValidateExtensions type");
41 }
42 }
43
💬 An exception is thrown from UValidateExtensions its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 Src\Asp.NetCore2\SqlSeverTest\UserTestCases\UnitTest\UValidateExtensions.cs (line 40)
37
38 if (_validateExtensionsType == null)
39 {
40 throw new Exception("Could not find SqlSugar.ValidateExtensions type");
41 }
42 }
43
💬 An exception is thrown from UValidateExtensions its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS033 Async overload is available 216 hits
📄 Src\Asp.NetCore2\MongoDb.Ado.data\ExecuteNonQueryItemsAsync\NonFindHandlerAsync.cs (line 21)
18 {
19 using (var dr = await new DbDataReaderFactoryAsync().HandleAsync(operation, collection, json,token,context))
20 {
21 if (dr.Read())
22 {
23
24 }
💬 Async overload available for DbDataReader.Read (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Src\Asp.NetCore2\MongoDb.Ado.data\ExecuteScalarItemsAsync\ExecuteScalarHandlerAsync.cs (line 18)
15 {
16 using (var dbReader = await new DbDataReaderFactoryAsync().HandleAsync(operation, collection, json,cancellationToken,context))
17 {
18 if (dbReader.Read())
19 {
20 return dbReader.GetValue(0);
21 }
💬 Async overload available for DbDataReader.Read (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 230 hits
📄 Src\Asp.NetCore2\NugetTest\Demo\Demo0_SqlSugarClient.cs (line 334)
331
332 });
333 result2.Wait();
334 if (result2.Result.IsSuccess == false)
335 {
336 Console.WriteLine("---Roll back");
337 db.ChangeDatabase("1");//use sqlserver
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Src\Asp.NetCore2\OracleTest\UserTestCases\UnitTest\UAdo.cs (line 16)
13
14 var task1 = Db.Ado.GetScalarAsync("select 1");
15 task1.Wait();
16 UValidate.Check(1, task1.Result, "ado");
17
18 var task2 = Db.Ado.GetIntAsync("select 2");
19 task2.Wait();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 Src\Asp.NetCore2\SqlSugar\Entities\MapperCache.cs (line 151)
148 }
149 else
150 {
151 var ids = _list.Select(action).ToList().Distinct().ToList();
152 var result = _context.Queryable<Result>().In(ids).ToList();
153 caches.Add(key, result);
154 return result;
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 Src\Asp.NetCore2\SqlSugar\Entities\MapperCache.cs (line 151)
148 }
149 else
150 {
151 var ids = _list.Select(action).ToList().Distinct().ToList();
152 var result = _context.Queryable<Result>().In(ids).ToList();
153 caches.Add(key, result);
154 return result;
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 2 hits
📄 Src\Asp.NetCore2\SqlSugar.TDengineCore\STableAttribute.cs (line 7)
4
5namespace SqlSugar.TDengine
6{
7 public class STableAttribute:Attribute
8 {
9 public string Tags { get; set; }
10 public string Tag1 { get; set; }
💬 STableAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 Src\Asp.NetCore2\SqlSugar.TDengineCore\STableAttribute.cs (line 7)
4
5namespace SqlSugar.TDengine
6{
7 public class STableAttribute:Attribute
8 {
9 public string Tags { get; set; }
10 public string Tag1 { get; set; }
💬 STableAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS047 LINQ traversal before filter 14 hits
📄 Src\Asp.NetCore2\SqlSugar\Abstract\CodeFirstProvider\CodeFirstProvider.cs (line 405)
402 List<DbColumnInfo> columns = new List<DbColumnInfo>();
403 if (entityInfo.Columns.HasValue())
404 {
405 foreach (var item in entityInfo.Columns.OrderBy(it => it.IsPrimarykey ? 0 : 1).Where(it => it.IsIgnore == false))
406 {
407 DbColumnInfo dbColumnInfo = EntityColumnToDbColumn(entityInfo, tableName, item);
408 columns.Add(dbColumnInfo);
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 Src\Asp.NetCore2\SqlSugar\ExpressionsToSql\ResolveItems\MapperExpressionResolve.cs (line 242)
239
240 private MapperExpression GetMapper(MemberExpression exp)
241 {
242 var mapper = mappers.Where(it => it.Type == MapperExpressionType.oneToOne)
243 .Reverse()
244 .Where(it => (it.FillExpression as LambdaExpression).Body.ToString() == exp.Expression.ToString()).FirstOrDefault();
245 ThrowTrue(mapper == null);
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS049 Comparing strings without StringComparison 456 hits
📄 Src\Asp.NetCore2\TDengine.Ado.Data\SqlSugar.TDengine\TdengineType.cs (line 11)
8
9 public static object GetObjectByType(object dataValue, byte typeValue)
10 {
11 if (dataValue is string &&dataValue?.ToString().ToUpper() == "NULL")
12 {
13 return null;
14 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Src\Asp.NetCore2\SqlSugar\Abstract\DbBindProvider\DbBindProvider.cs (line 24)
21 {
22 if (csharpTypeName == UtilConstants.ByteArrayType.Name)
23 return "varbinary";
24 if (csharpTypeName.ToLower() == "int32")
25 csharpTypeName = "int";
26 if (csharpTypeName.ToLower() == "int16")
27 csharpTypeName = "short";
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 12 hits
📄 Src\Asp.NetCore2\SqlSugar\Abstract\CodeFirstProvider\CodeFirstProvider.cs (line 83)
80 }
81 }
82 //Prevent concurrent requests if used in your program
83 lock (CodeFirstProvider.LockObject)
84 {
85 MappingTableList oldTableList = CopyMappingTalbe();
86 //this.Context.Utilities.RemoveCacheAll();
💬 A lock was obtained on LockObject but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Src\Asp.NetCore2\SqlSugar\DistributedSystem\Snowflake\SnowFlakeSingle.cs (line 26)
23 {
24 if (worker == null)
25 {
26 lock (LockObject)
27 {
28 if (worker == null)
29 {
💬 A lock was obtained on LockObject but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 212 hits
📄 Src\Asp.NetCore2\SqlSugar\Utilities\UtilMethods.cs (line 1348)
1345
1346 for (int i = 0; i < targetData.Length; i++)
1347 {
1348 byte2String += targetData[i].ToString("x");
1349 }
1350
1351 return byte2String;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Src\Asp.NetCore2\SqlSugar\Abstract\SqlBuilderProvider\DeleteBuilder.cs (line 109)
106 foreach (var item in _WhereInfos)
107 {
108 var isFirst = i == 0;
109 whereString += isFirst ? "WHERE " : "AND ";
110 whereString += (item + UtilConstants.Space);
111 ++i;
112 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 28 hits
📄 Src\Asp.NetCore2\MongoDb.Ado.data\ExecuteNonQueryItemsAsync\NonFindHandlerAsync.cs (line 19)
16
17 public async Task<int> HandleAsync(IMongoCollection<BsonDocument> collection, string json)
18 {
19 using (var dr = await new DbDataReaderFactoryAsync().HandleAsync(operation, collection, json,token,context))
20 {
21 if (dr.Read())
22 {
💬 DbDataReader can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Src\Asp.NetCore2\MongoDb.Ado.data\ExecuteScalarItemsAsync\ExecuteScalarHandlerAsync.cs (line 16)
13 {
14 public async Task<object> HandleAsync(string operation, IMongoCollection<BsonDocument> collection, string json,CancellationToken cancellationToken, HandlerContext context)
15 {
16 using (var dbReader = await new DbDataReaderFactoryAsync().HandleAsync(operation, collection, json,cancellationToken,context))
17 {
18 if (dbReader.Read())
19 {
💬 DbDataReader can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 24 hits
📄 Src\Asp.NetCore2\TDengine.Ado.Data\SqlSugar.TDengine\TdengineCommand.cs (line 18)
15 public class TDengineCommand : DbCommand
16 {
17 private string commandText;
18 private TDengineConnection connection;
19 private IntPtr currentRes;
20 public TDengineCommand()
21 {
💬 Disposable field connection in type TDengineCommand is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Src\Asp.NetCore2\TDengine.Ado.Data\SqlSugar.TDengine\TdengineCommand.cs (line 63)
60 }
61 }
62
63 protected override DbTransaction DbTransaction { get; set; }
64
65 public override void Cancel()
66 {
💬 Disposable field DbTransaction in type TDengineCommand is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

FastReport

3606 total diagnostics across 17 rules

SS001 Async method with void return type 6 hits
📄 FastReport.Base\Utils\Config.cs (line 272)
269 /// <remarks>
270 /// Call this method at an application start to warm up the Roslyn compiler (used in NetCore).
271 /// </remarks>
272 public static async void CompilerWarmup()
273 {
274 Report.EnsureInit();
275 await Task.Run(() =>
💬 Method CompilerWarmup is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 FastReport.Base\Utils\Config.cs (line 272)
269 /// <remarks>
270 /// Call this method at an application start to warm up the Roslyn compiler (used in NetCore).
271 /// </remarks>
272 public static async void CompilerWarmup()
273 {
274 Report.EnsureInit();
275 await Task.Run(() =>
💬 Method CompilerWarmup is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 6 hits
📄 FastReport.Base\Fakes.cs (line 19)
16 get
17 {
18#if !USE_FAKES
19 return System.DateTime.Now;
20#else
21 return new System.DateTime(0, System.DateTimeKind.Utc);
22#endif
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 FastReport.Base\Fakes.cs (line 19)
16 get
17 {
18#if !USE_FAKES
19 return System.DateTime.Now;
20#else
21 return new System.DateTime(0, System.DateTimeKind.Utc);
22#endif
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 882 hits
📄 FastReport.Base\CellularTextObject.cs (line 220)
217 if (HorzAlign == HorzAlign.Right)
218 offset = table.ColumnCount - text.Length;
219 else if (HorzAlign == HorzAlign.Center)
220 offset = (table.ColumnCount - text.Length) / 2;
221
222 for (int i = 0; i < text.Length; i++)
223 {
💬 The operands in the divisive expression (table.ColumnCount - text.Length) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 FastReport.Base\Export\Image\ImageExport.cs (line 579)
576 if (image == bigImage)
577 {
578 if (ImageFormat != ImageExportFormat.Metafile)
579 g.TranslateTransform(image.Width / 2 - width / 2 + page.LeftMargin * Units.Millimeters * zoomX,
580 curOriginY + paddingNonSeparatePages + page.TopMargin * Units.Millimeters * zoomY);
581 else
582 g.TranslateTransform(widthK / 2 - width / 2 + page.LeftMargin * Units.Millimeters * zoomX,
💬 The operands in the divisive expression image.Width / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 54 hits
📄 FastReport.Base\Data\Column.cs (line 256)
253 {
254 DataSourceBase dataSource = ParentDataSource;
255 if (dataSource != null)
256 return dataSource[this];
257 }
258 return null;
259 }
💬 Type Column is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 FastReport.Base\Data\JsonConnection\JsonTableDataSource.cs (line 374)
371
372 for (int i = 0; i < table.Columns.Count; i++)
373 {
374 if (!(table.Columns[i].Calculated || saveColumns.Contains(table.Columns[i])))
375 {
376 table.Columns.RemoveAt(i);
377 i--;
💬 Type Column is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 264 hits
📄 FastReport.Base\TextObject.cs (line 195)
192 unchecked
193 {
194 int hashCode = -1051315095;
195 hashCode = hashCode * -1521134295 + firstLineIndent.GetHashCode();
196 hashCode = hashCode * -1521134295 + lineSpacing.GetHashCode();
197 hashCode = hashCode * -1521134295 + lineSpacingType.GetHashCode();
198 hashCode = hashCode * -1521134295 + skipFirstLineIndent.GetHashCode();
💬 GetHashCode() refers to mutable field firstLineIndent (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 FastReport.Base\TextObject.cs (line 196)
193 {
194 int hashCode = -1051315095;
195 hashCode = hashCode * -1521134295 + firstLineIndent.GetHashCode();
196 hashCode = hashCode * -1521134295 + lineSpacing.GetHashCode();
197 hashCode = hashCode * -1521134295 + lineSpacingType.GetHashCode();
198 hashCode = hashCode * -1521134295 + skipFirstLineIndent.GetHashCode();
199 return hashCode;
💬 GetHashCode() refers to mutable field lineSpacing (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 42 hits
📄 FastReport.Base\Data\XmlDataConnection.cs (line 226)
223 }
224 catch (Exception e)
225 {
226 throw e;
227 }
228 }
229
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 FastReport.Base\Data\XmlDataConnection.cs (line 265)
262 }
263 catch (Exception e)
264 {
265 throw e;
266 }
267 }
268
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 120 hits
📄 FastReport.Base\Fakes.cs (line 44)
41 }
42
43
44 internal struct Guid
45 {
46#if NETSTANDARD || NETCOREAPP
47 [MethodImpl(MethodImplOptions.AggressiveInlining)]
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Guid. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 FastReport.Base\Fakes.cs (line 9)
6
7namespace SystemFake
8{
9 internal struct DateTime
10 {
11 internal static System.DateTime Now
12 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DateTime. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 138 hits
📄 FastReport.Base\Export\Image\ImageExport.cs (line 456)
453 else
454 {
455 ImageFormat format = System.Drawing.Imaging.ImageFormat.Bmp;
456 switch (ImageFormat)
457 {
458 case ImageExportFormat.Gif:
459 format = System.Drawing.Imaging.ImageFormat.Gif;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 FastReport.Base\BandBase.cs (line 471)
468 {
469 c.Top += dy / 2;
470 }
471 switch (c.Dock)
472 {
473 case DockStyle.Left:
474 c.Bounds = new RectangleF(remainingBounds.Left, remainingBounds.Top, c.Width, remainingBounds.Height);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 594 hits
📄 FastReport.Base\Code\VbCodeHelper.cs (line 23)
20
21 private string GetEquivalentKeyword1(string s)
22 {
23 switch (s)
24 {
25 case "DateTime":
26 return "Date";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 FastReport.Base\Code\CsCodeHelper.cs (line 34)
31
32 private string GetEquivalentKeyword1(string s)
33 {
34 switch (s)
35 {
36 case "Object":
37 return "object";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 12 hits
📄 FastReport.Base\Barcode\LinearBarcodeBase.cs (line 107)
104 if (pattern == null)
105 {
106 MyRes res = new MyRes("Messages");
107 throw new FormatException(res.Get("BarcodeManyError"));
108 }
109 return pattern;
110 }
💬 An exception is thrown from the getter of property Code (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 FastReport.Base\Barcode\Aztec\BitMatrix.cs (line 72)
69 {
70 if (width != height)
71 {
72 throw new System.ArgumentException("Can't call getDimension() on a non-square matrix");
73 }
74 return width;
75 }
💬 An exception is thrown from the getter of property Dimension (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 6 hits
📄 FastReport.Base\Data\JsonConnection\JsonDataSourceConnection.cs (line 159)
156 jsonDataSource.Name = fixedTableName;
157
158 jsonDataSource.Parent = this;
159 jsonDataSource.InitSchema();
160 jsonDataSource.Enabled = true;
161 }
162
💬 Async overload available for JsonTableDataSource.InitSchema (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 FastReport.Base\Data\JsonConnection\JsonDataSourceConnection.cs (line 159)
156 jsonDataSource.Name = fixedTableName;
157
158 jsonDataSource.Parent = this;
159 jsonDataSource.InitSchema();
160 jsonDataSource.Enabled = true;
161 }
162
💬 Async overload available for JsonTableDataSource.InitSchema (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS048 Locking on discouraged object (string, Type, this) 6 hits
📄 FastReport.Base\Report.cs (line 1163)
1160 {
1161 if (disposing)
1162 {
1163 lock (this)
1164 {
1165 _site?.Container?.Remove(this);
1166 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 FastReport.Base\Report.cs (line 1163)
1160 {
1161 if (disposing)
1162 {
1163 lock (this)
1164 {
1165 _site?.Container?.Remove(this);
1166 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 162 hits
📄 FastReport.Base\ComponentBase.cs (line 511)
508 if (!String.IsNullOrEmpty(VisibleExpression))
509 {
510 string expression = Code.CodeUtils.FixExpressionWithBrackets(VisibleExpression);
511 if (expression.ToLower() == "true" || expression.ToLower() == "false")
512 {
513 expression = expression.ToLower();
514 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 FastReport.Base\ComponentBase.cs (line 511)
508 if (!String.IsNullOrEmpty(VisibleExpression))
509 {
510 string expression = Code.CodeUtils.FixExpressionWithBrackets(VisibleExpression);
511 if (expression.ToLower() == "true" || expression.ToLower() == "false")
512 {
513 expression = expression.ToLower();
514 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS057 Collection manipulated during traversal 70 hits
📄 FastReport.OpenSource\Data\DataConnectionBase.Core.cs (line 20)
17 Config.OnFilterConnectionTables(this, e);
18 if (e.Skip)
19 {
20 tableNames.RemoveAt(i);
21 i--;
22 }
23 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 FastReport.Base\Export\ExportBase.cs (line 278)
275 {
276 if (pages[i] < 0 || pages[i] >= total)
277 {
278 pages.RemoveAt(i);
279 i--;
280 }
281 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 816 hits
📄 FastReport.Base\Code\VbCodeHelper.cs (line 55)
52
53 foreach (Type elementType in type.GetGenericArguments())
54 {
55 result += GetTypeDeclaration(elementType) + ",";
56 }
57
58 result = result.Substring(0, result.Length - 1) + ")";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 FastReport.OpenSource\Utils\NetRepository.Core.cs (line 35)
32 if (node.Attributes != null)
33 {
34 foreach (XmlAttribute attr in node.Attributes)
35 result = result + GetInnerText(attr);
36 }
37
38 // TZ: param name and description was displayed in one word
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 FastReport.Base\Data\XmlDataConnection.cs (line 402)
399 {
400 var encoding = response.CharacterSet.Equals(String.Empty) ? Encoding.UTF8 : Encoding.GetEncoding(response.CharacterSet);
401
402 using (var responseStream = response.GetResponseStream())
403 using (var reader = new System.IO.StreamReader(responseStream, encoding))
404 dataset.ReadXmlSchema(reader);
405 }
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 FastReport.Base\Data\XmlDataConnection.cs (line 402)
399 {
400 var encoding = response.CharacterSet.Equals(String.Empty) ? Encoding.UTF8 : Encoding.GetEncoding(response.CharacterSet);
401
402 using (var responseStream = response.GetResponseStream())
403 using (var reader = new System.IO.StreamReader(responseStream, encoding))
404 dataset.ReadXmlSchema(reader);
405 }
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 424 hits
📄 FastReport.Base\ReportComponentBase.cs (line 133)
130 private string savedBookmark;
131 private Border savedBorder;
132 private FillBase savedFill;
133 private Cursor cursor;
134 private string mouseMoveEvent;
135 private string mouseUpEvent;
136 private string mouseDownEvent;
💬 Disposable field cursor in type ReportComponentBase is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 FastReport.Base\Preview\PreparedPages.cs (line 54)
51 public partial class PreparedPages : IDisposable
52 {
53 #region Fields
54 private SourcePages sourcePages;
55 private List<PreparedPage> preparedPages;
56 private Dictionary dictionary;
57 private Bookmarks bookmarks;
💬 Disposable field sourcePages in type PreparedPages is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

smtp4dev

3332 total diagnostics across 18 rules

SS001 Async method with void return type 4 hits
📄 Rnwood.Smtp4dev\Server\ImapServer.cs (line 62)
59 }
60 }
61
62 public async void TryStart()
63 {
64 this.lastStartOptions = serverOptions.CurrentValue with { };
65
💬 Method TryStart is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Rnwood.Smtp4dev\Server\ImapServer.cs (line 62)
59 }
60 }
61
62 public async void TryStart()
63 {
64 this.lastStartOptions = serverOptions.CurrentValue with { };
65
💬 Method TryStart is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 312 hits
📄 imapserver\New.LumiSoft.Net\AUTH\Auth_HttpDigest_NonceManager.cs (line 174)
171 lock(m_pNonces){
172 for(int i=0;i<m_pNonces.Count;i++){
173 // Nonce expired, remove it.
174 if(m_pNonces[i].CreateTime.AddSeconds(m_ExpireTime) > DateTime.Now){
175 m_pNonces.RemoveAt(i);
176 i--;
177 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 imapserver\New.LumiSoft.Net\IO\SmartStream.cs (line 1051)
1048 m_pReadBuffer = new byte[m_BufferSize];
1049 m_pReadBufferOP = new BufferReadAsyncOP(this);
1050
1051 m_LastActivity = DateTime.Now;
1052 }
1053
1054 #region method Dispose
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 22 hits
📄 imapserver\New.LumiSoft.Net\Net_Utils.cs (line 513)
510 throw new Exception("Illegal hex data, hex data must be in two bytes pairs, for example: 0F,FF,A3,... .");
511 }
512
513 MemoryStream retVal = new MemoryStream(hexData.Length / 2);
514 // Loop hex value pairs
515 for(int i=0;i<hexData.Length;i+=2){
516 byte[] hexPairInDecimal = new byte[2];
💬 The operands in the divisive expression hexData.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 imapserver\New.LumiSoft.Net\Net_Utils.cs (line 824)
821 }
822 //---------------------------------------------//
823
824 byte[] decodedDataBuffer = new byte[((base64Data.Length * 6) / 8) + 4];
825 int decodedBytesCount = 0;
826 int nByteInBase64Block = 0;
827 byte[] decodedBlock = new byte[3];
💬 The operands in the divisive expression (base64Data.Length * 6) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 imapserver\New.LumiSoft.Net\MIME\MIME_h_Collection.cs (line 197)
194 throw new ArgumentNullException("field");
195 }
196
197 return m_pFields.Contains(field);
198 }
199
200 #endregion
💬 Type MIME_h is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 imapserver\New.LumiSoft.Net\MIME\MIME_EntityCollection.cs (line 122)
119 throw new ArgumentNullException("entity");
120 }
121
122 return m_pCollection.Contains(entity);
123 }
124
125 #endregion
💬 Type MIME_Entity is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS013 Rethrow exception without losing stacktrace 18 hits
📄 imapserver\New.LumiSoft.Net\IO\SmartStream.cs (line 3211)
3208 }
3209 catch(LineSizeExceededException lx){
3210 if(m_SizeExceededAction == SizeExceededAction.ThrowException){
3211 throw lx;
3212 }
3213 m_pException = new LineSizeExceededException();
3214 storedCount = 32000 - 2;
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 imapserver\New.LumiSoft.Net\TCP\TCP_Client.cs (line 113)
110 }
111 catch(Exception x){
112 if(this.IsConnected){
113 throw x;
114 }
115 // Connect failed for specified IP address, if there are some more IPs left, try next, otherwise forward exception.
116 else if(i == (ips.Length - 1)){
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 Rnwood.Smtp4dev\WindowsServiceManager.cs (line 72)
69 private const int SERVICE_CONFIG_DESCRIPTION = 1;
70
71 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
72 private struct ServiceDescription
73 {
74 public string lpDescription;
75 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ServiceDescription. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Rnwood.Smtp4dev\WindowsServiceManager.cs (line 72)
69 private const int SERVICE_CONFIG_DESCRIPTION = 1;
70
71 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
72 private struct ServiceDescription
73 {
74 public string lpDescription;
75 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ServiceDescription. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 4 hits
📄 Rnwood.Smtp4dev\Server\Imap\ImapSearchTranslator.cs (line 19)
16
17 public Expression<Func<DbModel.Message, bool>> Translate(IMAP_Search_Key criteria)
18 {
19 return criteria switch
20 {
21 IMAP_Search_Key_Group group => HandleGroup(group),
22 IMAP_Search_Key_Unseen unseen => HandleUnseen(unseen),
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Rnwood.Smtp4dev\Server\Imap\ImapSearchTranslator.cs (line 19)
16
17 public Expression<Func<DbModel.Message, bool>> Translate(IMAP_Search_Key criteria)
18 {
19 return criteria switch
20 {
21 IMAP_Search_Key_Group group => HandleGroup(group),
22 IMAP_Search_Key_Unseen unseen => HandleUnseen(unseen),
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 1656 hits
📄 imapserver\New.LumiSoft.Net\IO\Base64Stream.cs (line 410)
407 {
408 get{
409 if(m_IsDisposed){
410 throw new ObjectDisposedException("SmartStream");
411 }
412
413 return true;
💬 An exception is thrown from the getter of property CanRead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 imapserver\New.LumiSoft.Net\IO\Base64Stream.cs (line 425)
422 {
423 get{
424 if(m_IsDisposed){
425 throw new ObjectDisposedException("SmartStream");
426 }
427
428 return false;
💬 An exception is thrown from the getter of property CanSeek (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 68 hits
📄 smtpserver\Rnwood.SmtpServer\Verbs\DataVerb.cs (line 63)
60 if (!firstLine)
61 {
62 messageSize += CRLF_BYTES.Length;
63 messageStream.Write(CRLF_BYTES, 0, CRLF_BYTES.Length);
64 }
65
66 messageSize += data.Length;
💬 Async overload available for Stream.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 smtpserver\Rnwood.SmtpServer\Verbs\DataVerb.cs (line 67)
64 }
65
66 messageSize += data.Length;
67 messageStream.Write(data, 0, data.Length);
68 }
69 else
70 {
💬 Async overload available for Stream.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 16 hits
📄 Rnwood.Smtp4dev\Server\Smtp4devServer.cs (line 220)
217
218 using var scope = serviceScopeFactory.CreateScope();
219 var mimeProcessingService = scope.ServiceProvider.GetService<MimeProcessingService>();
220 Message message = new MessageConverter(mimeProcessingService).ConvertAsync(await e.Connection.CurrentMessage.ToMessage(), e.Connection.CurrentMessage.Recipients.ToArray()).Result;
221
222 var apiMessage = new ApiModel.Message(message);
223
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Rnwood.Smtp4dev\Server\ImapServer.cs (line 147)
144
145 if (index == 1)
146 {
147 log.Error(errorTask.Result.Exception, "IMAP server failed to start. Port: {port}, BindAddress: {bindAddress}, ExceptionType: {exceptionType}",
148 serverOptions.CurrentValue.ImapPort, serverOptions.CurrentValue.BindAddress ?? "Any",
149 errorTask.Result.Exception.GetType().Name);
150 }
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 Rnwood.Smtp4dev\Controllers\UseEtagFilterAttribute.cs (line 14)
11
12namespace Rnwood.Smtp4dev.Controllers
13{
14 public class UseEtagFilterAttribute : Attribute, IActionFilter
15 {
16 public UseEtagFilterAttribute()
17 {
💬 UseEtagFilterAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 Rnwood.Smtp4dev\Controllers\UseEtagFilterAttribute.cs (line 14)
11
12namespace Rnwood.Smtp4dev.Controllers
13{
14 public class UseEtagFilterAttribute : Attribute, IActionFilter
15 {
16 public UseEtagFilterAttribute()
17 {
💬 UseEtagFilterAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS048 Locking on discouraged object (string, Type, this) 12 hits
📄 imapserver\New.LumiSoft.Net\MIME\MIME_Entity.cs (line 38)
35 /// </summary>
36 public void Dispose()
37 {
38 lock(this){
39 if(m_IsDisposed){
40 return;
41 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 imapserver\New.LumiSoft.Net\TCP\TCP_Client.cs (line 48)
45 /// </summary>
46 public override void Dispose()
47 {
48 lock(this){
49 if(m_IsDisposed){
50 return;
51 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 330 hits
📄 imapserver\New.LumiSoft.Net\AUTH\Auth_HttpDigest.cs (line 111)
108 string name = name_value[0].Trim();
109
110 if(name_value.Length == 2){
111 if(name.ToLower() == "realm"){
112 m_Realm = TextUtils.UnQuoteString(name_value[1]);
113 }
114 else if(name.ToLower() == "nonce"){
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 imapserver\New.LumiSoft.Net\AUTH\Auth_HttpDigest.cs (line 114)
111 if(name.ToLower() == "realm"){
112 m_Realm = TextUtils.UnQuoteString(name_value[1]);
113 }
114 else if(name.ToLower() == "nonce"){
115 m_Nonce = TextUtils.UnQuoteString(name_value[1]);
116 }
117 // RFC bug ?: RFC 2831. digest-uri = "digest-uri" "=" <"> digest-uri-value <">
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 336 hits
📄 imapserver\New.LumiSoft.Net\AUTH\Auth_HttpDigest_NonceManager.cs (line 130)
127 /// <returns>Returns true if nonce exists in active nonces collection, otherwise returns false.</returns>
128 public bool NonceExists(string nonce)
129 {
130 lock(m_pNonces){
131 foreach(NonceEntry e in m_pNonces){
132 if(e.Nonce == nonce){
133 return true;
💬 A lock was obtained on m_pNonces but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 imapserver\New.LumiSoft.Net\AUTH\Auth_HttpDigest_NonceManager.cs (line 151)
148 /// <param name="nonce">Nonce to remove.</param>
149 public void RemoveNonce(string nonce)
150 {
151 lock(m_pNonces){
152 for(int i=0;i<m_pNonces.Count;i++){
153 if(m_pNonces[i].Nonce == nonce){
154 m_pNonces.RemoveAt(i);
💬 A lock was obtained on m_pNonces but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 24 hits
📄 imapserver\New.LumiSoft.Net\AUTH\Auth_HttpDigest_NonceManager.cs (line 154)
151 lock(m_pNonces){
152 for(int i=0;i<m_pNonces.Count;i++){
153 if(m_pNonces[i].Nonce == nonce){
154 m_pNonces.RemoveAt(i);
155 i--;
156 }
157 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 imapserver\New.LumiSoft.Net\AUTH\Auth_HttpDigest_NonceManager.cs (line 175)
172 for(int i=0;i<m_pNonces.Count;i++){
173 // Nonce expired, remove it.
174 if(m_pNonces[i].CreateTime.AddSeconds(m_ExpireTime) > DateTime.Now){
175 m_pNonces.RemoveAt(i);
176 i--;
177 }
178 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 6 hits
📄 imapserver\New.LumiSoft.Net\MIME\MIME_Utils.cs (line 540)
537 // see if multi line value. See commnt above.
538 line = r.ReadLine();
539 while(line != null && (line.StartsWith("\t") || line.StartsWith(" "))){
540 fieldValue += line;
541 line = r.ReadLine();
542 }
543
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 imapserver\New.LumiSoft.Net\MIME\MIME_Utils.cs (line 540)
537 // see if multi line value. See commnt above.
538 line = r.ReadLine();
539 while(line != null && (line.StartsWith("\t") || line.StartsWith(" "))){
540 fieldValue += line;
541 line = r.ReadLine();
542 }
543
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 38 hits
📄 smtpserver\Rnwood.SmtpServer\FileSession.cs (line 40)
37 /// <inheritdoc />
38 public override async Task AppendLineToSessionLog(string text)
39 {
40 using (StreamWriter writer = file.AppendText())
41 {
42 await writer.WriteLineAsync(text).ConfigureAwait(false);
43 }
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 smtpserver\Rnwood.SmtpServer\Verbs\DataVerb.cs (line 41)
38
39 long messageSize = 0;
40
41 using (Stream messageStream = await connection.CurrentMessage.WriteData().ConfigureAwait(false))
42 {
43 bool firstLine = true;
44
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 466 hits
📄 smtpserver\Rnwood.SmtpServer\SmtpStreamReader.cs (line 22)
19 private readonly Encoding fallbackEncoding;
20 private readonly bool leaveOpen;
21 private readonly List<byte> lineBytes = new(32 * 1024);
22 private readonly Stream stream;
23 private readonly UTF8Encoding utf8Encoding = new(false, true);
24 private int bufferLen;
25 private int bufferPos;
💬 Disposable field stream in type SmtpStreamReader is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 smtpserver\Rnwood.SmtpServer\MemoryMessage.cs (line 71)
68 /// <summary>
69 /// Gets the Session message was received on.
70 /// </summary>
71 public ISession Session { get; internal set; }
72
73 /// <summary>
74 /// Gets a value indicating whether the current message contains bare line feeds.
💬 Disposable field Session in type MemoryMessage is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Masuit.Tools

3000 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 676 hits
📄 Masuit.Tools.Abstractions\Extensions\BaseType\StringExtensions.cs (line 68)
65 public static string CreateShortToken(this string str, byte chars = 36)
66 {
67 var nf = new NumberFormater(chars);
68 return nf.ToString((DateTime.Now.Ticks - 630822816000000000) * 100 + Stopwatch.GetTimestamp() % 100);
69 }
70
71 /// <summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Masuit.Tools\Mvc\ActionResults\ResumeFileResult.cs (line 68)
65 {
66 response.AppendHeader(HttpHeaders.Etag, _etag);
67 response.AppendHeader(HttpHeaders.LastModified, _lastModified);
68 response.AppendHeader(HttpHeaders.Expires, DateTime.Now.ToString("R"));
69 response.AppendHeader(HttpHeaders.AccessControlExposeHeaders, HttpHeaders.ContentDisposition);
70
71 if (IsNotModified())
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 1022 hits
📄 Masuit.Tools.DigtalWatermarker\DigitalWatermarker.cs (line 42)
39 Mat y = planes[0];
40
41 // 保障处理区域为8的倍数
42 int w = (y.Cols / BlockSize) * BlockSize;
43 int h = (y.Rows / BlockSize) * BlockSize;
44 var roi = new Rect(0, 0, w, h);
45 Mat yRoi = new(y, roi);
💬 The operands in the divisive expression y.Cols / BlockSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Masuit.Tools.DigtalWatermarker\DigitalWatermarker.cs (line 43)
40
41 // 保障处理区域为8的倍数
42 int w = (y.Cols / BlockSize) * BlockSize;
43 int h = (y.Rows / BlockSize) * BlockSize;
44 var roi = new Rect(0, 0, w, h);
45 Mat yRoi = new(y, roi);
46
💬 The operands in the divisive expression y.Rows / BlockSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 88 hits
📄 Masuit.Tools.Abstractions\Linq\LinqExtension.cs (line 109)
106
107 protected override Expression VisitParameter(ParameterExpression node)
108 {
109 return Sub.TryGetValue(node, out var newValue) ? newValue : node;
110 }
111}
💬 Type Expression is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Masuit.Tools.Abstractions\Linq\LinqExtension.cs (line 94)
91 {
92 Sub =
93 {
94 [right.Parameters[0]] = left.Parameters[0]
95 }
96 };
97
💬 Type Expression is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 46 hits
📄 Masuit.Tools.Abstractions\DateTimeExt\ChineseCalendar.cs (line 13)
10 /// <remarks>
11 /// 本程序使用数据来源于网上的万年历查询,并综合了一些其它数据
12 /// </remarks>
13 public class ChineseCalendar
14 {
15 private class ChineseCalendarException(string msg) : Exception(msg);
16
💬 Equals() and GetHashcode() must be implemented together on ChineseCalendar (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 Masuit.Tools.Abstractions\Models\DateTimeRange.cs (line 11)
8/// <summary>
9/// 时间段
10/// </summary>
11public class DateTimeRange : ITimePeriod
12{
13 public DateTimeRange(DateTime? start, DateTime? end)
14 {
💬 Equals() and GetHashcode() must be implemented together on DateTimeRange (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 116 hits
📄 Masuit.Tools\Mvc\Internal\ByteRange.cs (line 24)
21 {
22 unchecked
23 {
24 return (Start.GetHashCode() * 397) ^ End.GetHashCode();
25 }
26 }
27 }
💬 GetHashCode() refers to mutable property Start (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Masuit.Tools\Mvc\Internal\ByteRange.cs (line 24)
21 {
22 unchecked
23 {
24 return (Start.GetHashCode() * 397) ^ End.GetHashCode();
25 }
26 }
27 }
💬 GetHashCode() refers to mutable property End (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 112 hits
📄 Masuit.Tools.Abstractions\Media\BorderDetectionResult.cs (line 8)
5/// <summary>
6/// 边框检测结果(包含多层边框信息)
7/// </summary>
8public struct BorderDetectionResult
9{
10 private int CroppedBorderCount { get; set; }
11
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BorderDetectionResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Masuit.Tools.Abstractions\Media\CMYColor.cs (line 3)
1namespace Masuit.Tools.Media;
2
3public struct CMYColor
4{
5 public double C { get; }
6 public double M { get; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CMYColor. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 30 hits
📄 Masuit.Tools.Abstractions\Extensions\BaseType\StringExtensions.cs (line 684)
681 public static bool IsExternalAddress(this string url)
682 {
683 var uri = new Uri(url);
684 switch (uri.HostNameType)
685 {
686 case UriHostNameType.Dns:
687 var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Masuit.Tools.Abstractions\Extensions\BaseType\StringExtensions.cs (line 684)
681 public static bool IsExternalAddress(this string url)
682 {
683 var uri = new Uri(url);
684 switch (uri.HostNameType)
685 {
686 case UriHostNameType.Dns:
687 var ipHostEntry = Dns.GetHostEntry(uri.DnsSafeHost);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 280 hits
📄 Masuit.Tools.Net45\Media\ImageUtilities.cs (line 754)
751 int ow = originalImage.Width;
752 int oh = originalImage.Height;
753
754 switch (mode)
755 {
756 case ThumbnailCutMode.Fixed: //指定高宽缩放(可能变形)
757 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Masuit.Tools.Abstractions\Extensions\BaseType\ObjectExtensions.cs (line 437)
434 public static T Merge<T>(this IEnumerable<T> objects) where T : class
435 {
436 var list = objects as List<T> ?? objects.ToList();
437 switch (list.Count)
438 {
439 case 0:
440 return null;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 12 hits
📄 Masuit.Tools.Abstractions\Extensions\BaseType\StreamExtensions.cs (line 251)
248#if NET5_0_OR_GREATER
249 await stream.DisposeAsync().ConfigureAwait(false);
250#else
251 stream.Dispose();
252#endif
253 }
254
💬 Async overload available for Stream.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Masuit.Tools.Abstractions\Extensions\BaseType\StreamExtensions.cs (line 277)
274#if NET5_0_OR_GREATER
275 await stream.DisposeAsync().ConfigureAwait(false);
276#else
277 stream.Dispose();
278#endif
279 }
280
💬 Async overload available for Stream.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 236 hits
📄 Masuit.Tools.Abstractions\Extensions\BaseType\StringExtensions.cs (line 350)
347 };
348 }
349
350 return t.Result;
351 }));
352 isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
353 }
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Masuit.Tools.Abstractions\Extensions\BaseType\StringExtensions.cs (line 352)
349
350 return t.Result;
351 }));
352 isMatch = task.Result.SelectMany(a => a).Any(ip => !ip.IsPrivateIP());
353 }
354
355 return (isMatch, match);
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS044 Attribute must specify [AttributeUsage] 184 hits
📄 Masuit.Tools.Abstractions\Files\IniFile\IniPropertyAttribute.cs (line 5)
2
3namespace Masuit.Tools.Files;
4
5public class IniPropertyAttribute : Attribute
6{
7 public string Name { get; set; }
8
💬 IniPropertyAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 Masuit.Tools.Abstractions\Validator\IsIPAddressAttribute.cs (line 8)
5/// <summary>
6/// 验证IPv4地址是否合法
7/// </summary>
8public class IsIPAddressAttribute : ValidationAttribute
9{
10 /// <summary>
11 /// 验证IPv4地址是否合法
💬 IsIPAddressAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS048 Locking on discouraged object (string, Type, this) 96 hits
📄 Masuit.Tools.Abstractions\Net\MultiThreadDownloader.cs (line 73)
70 {
71 try
72 {
73 lock (this)
74 {
75 return PartialDownloaderList.Where(t => t != null).Sum(t => t.TotalBytesRead);
76 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 Masuit.Tools.Abstractions\Net\MultiThreadDownloader.cs (line 226)
223 var temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, true);
224 temp.DownloadPartCompleted += temp_DownloadPartCompleted;
225 temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
226 lock (this)
227 {
228 PartialDownloaderList.Add(temp);
229 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS058 String concatenated in a loop 48 hits
📄 Masuit.Tools.Abstractions\Strings\NumberFormater.cs (line 298)
295 {
296 if (x[i] == '0')
297 {
298 ret = ToNum(x[i]) + ret;
299 }
300 else
301 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Masuit.Tools.Abstractions\Strings\NumberFormater.cs (line 302)
299 }
300 else
301 {
302 ret = ToNum(x[i]) + strArrayLevelNames[x.Length - 1 - i] + ret;
303 }
304 }
305
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 20 hits
📄 Masuit.Tools.Abstractions\Files\FileExt.cs (line 73)
70 {
71 Directory.CreateDirectory(dir);
72 }
73 using var fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
74 var stream = new BufferedStream(ms, 1048576);
75 await stream.CopyToAsync(fs);
76 ms.Seek(0, SeekOrigin.Begin);
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Masuit.Tools.Abstractions\Files\IniFile\IniFile.cs (line 159)
156 /// <returns></returns>
157 public async Task SaveAsync()
158 {
159 using StreamWriter writer = new(_path, false, Encoding.UTF8);
160 var firstLine = true;
161 foreach (var section in _sections.Values.Where(section => section.Count > 0))
162 {
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 34 hits
📄 Masuit.Tools.Abstractions\Models\Email.cs (line 60)
57 /// </summary>
58 public List<Attachment> Attachments { get; set; } = new List<Attachment>();
59
60 private MailMessage _mailMessage;
61
62 private MailMessage MailMessage => _mailMessage ?? GetClient();
63
💬 Disposable field _mailMessage in type Email is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Masuit.Tools.Abstractions\Files\FileDetector\AbstractCompoundFileDetailDetector.cs (line 893)
890 private readonly int _sectorSize;
891 private long _position;
892 private readonly List<Sector> _sectorChain;
893 private readonly Stream _stream;
894 private readonly bool _isFatStream;
895
896 public StreamView(List<Sector> sectorChain, int sectorSize, Stream stream)
💬 Disposable field _stream in type StreamView is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

better-genshin-impact

2852 total diagnostics across 22 rules

SS001 Async method with void return type 32 hits
📄 BetterGenshinImpact\Core\Script\WebView\RepoWebBridge.cs (line 55)
52 }
53 }
54
55 public async void ImportUri(string url)
56 {
57 try
58 {
💬 Method ImportUri is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 BetterGenshinImpact\ViewModel\Pages\MapPathingViewModel.cs (line 170)
167 }
168
169 [RelayCommand]
170 public async void OnOpenSettings()
171 {
172 // var uiMessageBox = new Wpf.Ui.Controls.MessageBox
173 // {
💬 Method OnOpenSettings is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 484 hits
📄 BetterGenshinImpact\Service\Notification\Model\BaseNotificationData.cs (line 30)
27 /// 事件触发时间
28 /// </summary>
29 [JsonConverter(typeof(DateTimeJsonConverter))]
30 public DateTime Timestamp { get; set; } = DateTime.Now;
31
32 /// <summary>
33 /// 事件触发时的截图
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 BetterGenshinImpact\GameTask\AutoFight\AutoFightTask.cs (line 43)
40
41 private readonly BgiYoloPredictor _predictor;
42
43 private DateTime _lastFightFlagTime = DateTime.Now; // 战斗标志最近一次出现的时间
44
45 private readonly double _dpi = TaskContext.Instance().DpiScale;
46
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 1834 hits
📄 BetterGenshinImpact\GameTask\Common\Map\Camera\CameraOrientationFromLimint.cs (line 20)
17 private float[] alphaParams1 = { 18.632f, 20.157f, 24.093f, 34.617f, 38.566f, 41.94f, 47.654f, 51.087f, 58.561f, 63.925f, 67.759f, 71.77f, 75.214f };
18 private int rLength = 60;
19 private static int thetaLength = 360;
20 private int peakWidth = thetaLength / 4;
21 private int width = tplSize;
22 private int height = tplSize;
23 private Mat rotationRemapDataX;
💬 The operands in the divisive expression thetaLength / 4 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 BetterGenshinImpact\GameTask\Common\Map\MiniMap\CameraOrientationCalculator.cs (line 17)
14 private const int ThetaLength = 360;
15 private const int FLength = 256;
16 private const int Scale = 2;
17 private const int PeakWidth = ThetaLength / 4 * Scale + 1;
18 private readonly Mat _rotationRemapDataX = new Mat();
19 private readonly Mat _rotationRemapDataY = new Mat();
20 private readonly Mat _alphaMask1Remap;
💬 The operands in the divisive expression ThetaLength / 4 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 44 hits
📄 BetterGenshinImpact\View\Behavior\AutoTranslateInterceptor.cs (line 533)
530 }
531
532 var map = GetOriginalValuesMap(obj);
533 if (map == null || !map.TryGetValue(property, out var original))
534 {
535 if (ContainsHan(value))
536 {
💬 Type DependencyProperty is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 BetterGenshinImpact\View\Behavior\AutoTranslateInterceptor.cs (line 538)
535 if (ContainsHan(value))
536 {
537 map = GetOrCreateOriginalValuesMap(obj);
538 map[property] = value;
539 original = value;
540 }
541 else
💬 Type DependencyProperty is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 BetterGenshinImpact\View\Drawable\TextDrawable.cs (line 31)
28
29 public override int GetHashCode()
30 {
31 return Point.GetHashCode();
32 }
33
34 public bool IsEmpty => Point is { X: 0, Y: 0 };
💬 GetHashCode() refers to mutable property Point (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 BetterGenshinImpact\View\Drawable\LineDrawable.cs (line 53)
50
51 public override int GetHashCode()
52 {
53 return P1.GetHashCode() + P2.GetHashCode();
54 }
55}
💬 GetHashCode() refers to mutable property P1 (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 30 hits
📄 Fischless.GameCapture\Graphics\Helpers\WinRT.cs (line 21)
18}
19
20[Guid("00000035-0000-0000-C000-000000000046")]
21internal unsafe struct IActivationFactoryVftbl
22{
23 public readonly IInspectable.Vftbl IInspectableVftbl;
24 private readonly void* _ActivateInstance;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct IActivationFactoryVftbl. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 BetterGenshinImpact\Helpers\DpiHelper.cs (line 60)
57}
58
59[DebuggerDisplay("{ToString()}")]
60public readonly struct DpiScaleF(float x = 1f, float y = 1f)
61{
62 private readonly float x = x;
63 public float X => x;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DpiScaleF. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 6 hits
📄 BetterGenshinImpact\Service\ApplicationHostService.cs (line 68)
65 Task.Run(() => ScriptRepoUpdater.Instance.AutoUpdateSubscribedScripts());
66 }
67
68 switch (cmdOptions.Action)
69 {
70 case CommandLineAction.StartOneDragon:
71 // 通过命令行参数启动「一条龙」 => 跳转到一条龙配置页。
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 BetterGenshinImpact\Service\ApplicationHostService.cs (line 68)
65 Task.Run(() => ScriptRepoUpdater.Instance.AutoUpdateSubscribedScripts());
66 }
67
68 switch (cmdOptions.Action)
69 {
70 case CommandLineAction.StartOneDragon:
71 // 通过命令行参数启动「一条龙」 => 跳转到一条龙配置页。
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 94 hits
📄 BetterGenshinImpact\Core\Recognition\OCR\Paddle\PaddleOcrService.cs (line 73)
70 var result = new List<string>();
71 while (parser.MoveNext())
72 {
73 switch (parser.Current)
74 {
75 case SequenceEnd:
76 return result;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 BetterGenshinImpact\View\Windows\ThemedMessageBox.xaml.cs (line 236)
233
234 private static void SetButtons(ThemedMessageBox messageBox, MessageBoxButton button)
235 {
236 switch (button)
237 {
238 case MessageBoxButton.OK:
239 messageBox.PrimaryButton.Content = "确定";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 8 hits
📄 BetterGenshinImpact\GameTask\TaskTriggerDispatcher.cs (line 87)
84
85 if (_instance.GameCapture == null)
86 {
87 throw new Exception("截图器未初始化!");
88 }
89
90 return _instance.GameCapture;
💬 An exception is thrown from the getter of property GlobalGameCapture (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 BetterGenshinImpact\GameTask\TaskContext.cs (line 65)
62 {
63 if (ConfigService.Config == null)
64 {
65 throw new Exception("Config未初始化");
66 }
67
68 return ConfigService.Config;
💬 An exception is thrown from the getter of property Config (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS032 Thread.Sleep used in async method 24 hits
📄 BetterGenshinImpact\GameTask\AutoDomain\AutoDomainTask.cs (line 290)
287 else if ("无妄引咎密宫".Equals(_taskParam.DomainName))
288 {
289 Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
290 Thread.Sleep(500);
291 Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
292
293 menuFound = await NewRetry.WaitForElementAppear(
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 BetterGenshinImpact\ViewModel\Pages\HotKeyPageViewModel.cs (line 512)
509
510 if (GlobalKeyMouseRecord.Instance.Status == KeyMouseRecorderStatus.Stop)
511 {
512 Thread.Sleep(300); // 防止录进快捷键进去
513 await vm.OnStartRecord();
514 }
515 else
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 48 hits
📄 BetterGenshinImpact\Service\UpdateService.cs (line 314)
311 string md = $"# {name}{new string('\n', 2)}{body}";
312
313 md = WebUtility.HtmlEncode(md);
314 string md2html = File.ReadAllText(Global.Absolute(@"Assets\Strings\md2html.html"), Encoding.UTF8);
315 var html = md2html.Replace("{{content}}", md);
316
317 return html;
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 BetterGenshinImpact\GameTask\AutoLeyLineOutcrop\AutoLeyLineOutcropTask.cs (line 746)
743 throw new FileNotFoundException("LeyLineOutcropData.json 未找到", nodePath);
744 }
745
746 var raw = JsonSerializer.Deserialize<RawNodeData>(File.ReadAllText(nodePath))
747 ?? throw new Exception("节点数据解析失败");
748 _nodeData = AdaptNodeData(raw);
749 return _nodeData;
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 8 hits
📄 BetterGenshinImpact\GameTask\GetGridIcons\GridIconsAccuracyTestTask.cs (line 130)
127 }, ct);
128
129 await Task.WhenAll(task1, task2);
130 (string?, int) result = task2.Result;
131 string? predName = result.Item1;
132 int predStarNum = result.Item2;
133
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 BetterGenshinImpact\GameTask\AutoFight\AutoFightSeek.cs (line 563)
560 Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
561 using (var imageAfterBurst = CaptureToRectArea())
562 {
563 if (AvatarSkillAsync(Logger, guardianAvatar, true, 1, ct).Result
564 || !Bv.IsInMainUi(imageAfterBurst)) //Q技能CD(冷却检测)或者不在主界面(大招动画播放中)
565 {
566 guardianAvatar.IsBurstReady = false;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 4 hits
📄 BetterGenshinImpact\GameTask\AutoFishing\AutoFishingTask.cs (line 189)
186 ? [7]
187 : (param.FishingTimePolicy == FishingTimePolicy.Nighttime ? [19] : new int[] { 7, 19 }))
188 {
189 setTimeTask.Start(hour, 0, ct).Wait(ct);
190 tickARound();
191 }
192 }
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 BetterGenshinImpact\GameTask\AutoFishing\AutoFishingTask.cs (line 189)
186 ? [7]
187 : (param.FishingTimePolicy == FishingTimePolicy.Nighttime ? [19] : new int[] { 7, 19 }))
188 {
189 setTimeTask.Start(hour, 0, ct).Wait(ct);
190 tickARound();
191 }
192 }
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS041 Unnecessary enumerable materialization 8 hits
📄 BetterGenshinImpact\ViewModel\Pages\ScriptControlViewModel.cs (line 1094)
1091 // 如果启用排除已选择过的目录,先过滤掉这些目录
1092 if (excludeSelectedFolder ?? false)
1093 {
1094 List<string> skipFolderNames = SelectedScriptGroup?.Projects.ToList().Select(item => item.FolderName).Distinct().ToList() ?? [];
1095 string jsonString = JsonSerializer.Serialize(nodes);
1096 var copiedNodes = JsonSerializer.Deserialize<ObservableCollection<FileTreeNode<PathingTask>>>(jsonString);
1097 if (copiedNodes != null)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 BetterGenshinImpact\ViewModel\Pages\ScriptControlViewModel.cs (line 2219)
2216 {
2217 //await StartGroups(selectedGroups);
2218 //taskProgress.Next
2219 var sg = ScriptGroups.ToList().Where(sg => taskProgress.ScriptGroupNames.Contains(sg.Name)).ToList();
2220 TaskProgressManager.GenerNextProjectInfo(taskProgress, sg);
2221 if (taskProgress.Next == null)
2222 {
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS046 Unbounded stackalloc 4 hits
📄 BetterGenshinImpact\GameTask\AutoPick\AutoPickTrigger.cs (line 486)
483 return text;
484
485 // 0. 首先替换相似的括号字符并删除换行符、空格,使用Span<char>进行原地替换以获得最佳性能
486 Span<char> chars = stackalloc char[text.Length];
487 text.AsSpan().CopyTo(chars);
488
489 int writeIndex = 0;
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
📄 BetterGenshinImpact\GameTask\AutoPick\AutoPickTrigger.cs (line 486)
483 return text;
484
485 // 0. 首先替换相似的括号字符并删除换行符、空格,使用Span<char>进行原地替换以获得最佳性能
486 Span<char> chars = stackalloc char[text.Length];
487 text.AsSpan().CopyTo(chars);
488
489 int writeIndex = 0;
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
SS048 Locking on discouraged object (string, Type, this) 16 hits
📄 BetterGenshinImpact\Model\MouseHook.cs (line 57)
54 /// <param name="e"></param>
55 private void RunAction(MouseEventExtArgs e)
56 {
57 lock (this)
58 {
59 while (IsPressed)
60 {
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 BetterGenshinImpact\Model\KeyboardHook.cs (line 64)
61 /// <param name="e"></param>
62 private void RunAction(KeyEventArgs e)
63 {
64 lock (this)
65 {
66 while (IsPressed && KeyPressedEvent != null)
67 {
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 4 hits
📄 BetterGenshinImpact\Helpers\MarkdownToFlowDocumentConverter.cs (line 282)
279 indentLevel = indentString.Length / 2;
280
281 // 判断任务是否已完成
282 isCompleted = checkMark.ToLower() == "x";
283
284 return true;
285 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 BetterGenshinImpact\Helpers\MarkdownToFlowDocumentConverter.cs (line 282)
279 indentLevel = indentString.Length / 2;
280
281 // 判断任务是否已完成
282 isCompleted = checkMark.ToLower() == "x";
283
284 return true;
285 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS054 Newtonsoft.Json mixed with System.Text.Json 12 hits
📄 BetterGenshinImpact\Service\UpdateService.cs (line 210)
207 {
208 // 即使是403、400也尝试读取响应体
209 var content = await response.Content.ReadAsStringAsync();
210 result = JsonConvert.DeserializeObject<LatestResponse>(content);
211 }
212
213 if (result != null)
💬 Attempting to deserialize an object annotated with System.Text.Json.Serialization through Newtonsoft.Json (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS054-NewtonsoftMixedWithSystemTextJson.md)
📄 BetterGenshinImpact\Service\UpdateService.cs (line 210)
207 {
208 // 即使是403、400也尝试读取响应体
209 var content = await response.Content.ReadAsStringAsync();
210 result = JsonConvert.DeserializeObject<LatestResponse>(content);
211 }
212
213 if (result != null)
💬 Attempting to deserialize an object annotated with System.Text.Json.Serialization through Newtonsoft.Json (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS054-NewtonsoftMixedWithSystemTextJson.md)
SS057 Collection manipulated during traversal 4 hits
📄 BetterGenshinImpact\ViewModel\Pages\ScriptControlViewModel.cs (line 2103)
2100 {
2101 if (item.Item1 == group.Name)
2102 {
2103 nextScheduledTask.Remove(item);
2104 break;
2105 }
2106 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 BetterGenshinImpact\ViewModel\Pages\ScriptControlViewModel.cs (line 2103)
2100 {
2101 if (item.Item1 == group.Name)
2102 {
2103 nextScheduledTask.Remove(item);
2104 break;
2105 }
2106 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 36 hits
📄 BetterGenshinImpact\Helpers\StringUtils.cs (line 66)
63 {
64 if (str[i] >= 0x4E00 && str[i] <= 0x9FA5) //汉字
65 {
66 chineseString += str[i];
67 }
68 }
69
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 BetterGenshinImpact\GameTask\AutoFight\Script\CombatScriptParser.cs (line 216)
213 // 括号被逗号分隔,需要合并
214 while (j < commandArray.Length)
215 {
216 command += "," + commandArray[j];
217 if (command.Count("(".Contains) > 1)
218 {
219 Logger.LogError("战斗脚本格式错误,指令 {Cmd} 括号无法配对", command);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 16 hits
📄 BetterGenshinImpact\Service\Notifier\TelegramNotifier.cs (line 145)
142 private async Task SendImageMessageAsync(Image<Rgb24> image, string? caption)
143 {
144 var endpoint = $"{TelegramApiBaseUrl}{TelegramBotToken}/sendPhoto";
145 using var memoryStream = new MemoryStream();
146 await image.SaveAsPngAsync(memoryStream);
147 memoryStream.Position = 0;
148
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 BetterGenshinImpact\Service\Notifier\EmailNotifier.cs (line 68)
65 // 添加图片附件(如果存在)
66 if (content.Screenshot != null)
67 {
68 using var memoryStream = new MemoryStream();
69 // 将图片保存到内存流
70 await content.Screenshot.SaveAsJpegAsync(memoryStream);
71 memoryStream.Position = 0; // 重置流位置
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 124 hits
📄 Fischless.HotkeyCapture\HotkeyHook.cs (line 10)
7{
8 public event EventHandler<KeyPressedEventArgs>? KeyPressed = null;
9
10 private readonly Window window = new();
11 private int currentId;
12
13 private class Window : NativeWindow, IDisposable
💬 Disposable field window in type HotkeyHook is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Fischless.GameCapture\Graphics\GraphicsCapture.cs (line 19)
16{
17 private nint _hWnd;
18
19 private Direct3D11CaptureFramePool? _captureFramePool;
20 private GraphicsCaptureItem? _captureItem;
21
22 private GraphicsCaptureSession? _captureSession;
💬 Disposable field _captureFramePool in type GraphicsCapture is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

TensorFlow.NET

2662 total diagnostics across 14 rules

SS003 Integer divided by integer causing implicit rounding 58 hits
📄 tools\Tensorflow.Redist.NativeLibrarySplitter\Program.cs (line 18)
15 using (FileStream input = new FileStream(filename, FileMode.Open, FileAccess.Read))
16 {
17 long filesize = new FileInfo(filename).Length; // 获取文件大小
18 long fragmentSize = (long)(filesize / count + 1); // 计算每个分片的大小
19
20 byte[] buffer = new byte[fragmentSize]; // 设置缓冲区大小
21 int bytesRead; // 存储读取长度
💬 The operands in the divisive expression filesize / count are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\TensorFlowNET.Core\Gradients\math_grad.cs (line 464)
461 {
462 var input_size = np.prod(input_shape);
463 var output_size = np.prod(output_shape);
464 var factor = (int)input_size / Math.Max((int)output_size, 1);
465 factor_tensor = constant_op.constant(factor, dtype: sum_grad.dtype);
466 }
467 else
💬 The operands in the divisive expression (int)input_size / Math.Max((int)output_size, 1) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 464 hits
📄 src\TensorFlowNET.Core\Checkpoint\TrackableView.cs (line 61)
58 Queue<Trackable> to_visit = new();
59 to_visit.Enqueue(Root);
60 Dictionary<Trackable, IEnumerable<TrackableReference>> node_paths = new();
61 node_paths[this.Root] = new List<TrackableReference>();
62 while (!to_visit.empty())
63 {
64 var current_trackable = to_visit.Dequeue();
💬 Type Trackable is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\TensorFlowNET.Core\Checkpoint\TrackableView.cs (line 70)
67 foreach (var name in children_dict.Keys)
68 {
69 var dependency = children_dict[name];
70 if (!node_paths.ContainsKey(dependency))
71 {
72 var list = new List<TrackableReference>(node_paths[current_trackable]);
73 list.Add(new TrackableReference(name, dependency));
💬 Type Trackable is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 12 hits
📄 src\TensorFlowNET.Core\NumPy\NDArray.Creation.cs (line 9)
6
7namespace Tensorflow.NumPy
8{
9 public partial class NDArray
10 {
11 protected NDArray() { }
12 public NDArray(bool value) : base(value) => NewEagerTensorHandle();
💬 Equals() and GetHashcode() must be implemented together on NDArray (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\TensorFlowNET.Core\NumPy\Shape.cs (line 29)
26namespace Tensorflow
27{
28 [JsonConverter(typeof(CustomizedShapeJsonConverter))]
29 public class Shape : INestStructure<long>
30 {
31 public int ndim => _dims == null ? -1 : _dims.Length;
32 long[] _dims;
💬 Equals() and GetHashcode() must be implemented together on Shape (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS013 Rethrow exception without losing stacktrace 1816 hits
📄 src\TensorFlowNET.Core\Operations\gen_resource_variable_ops.cs (line 36)
33 }
34 catch (NotOkStatusException ex)
35 {
36 throw ex;
37 }
38 catch (Exception)
39 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 src\TensorFlowNET.Core\Operations\gen_list_ops.cs (line 41)
38 }
39 catch (NotOkStatusException ex)
40 {
41 throw ex;
42 }
43 catch (Exception)
44 {
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 52 hits
📄 src\TensorFlowNET.Core\Operations\TF_AttrMetadata.cs (line 3)
1namespace Tensorflow
2{
3 public struct TF_AttrMetadata
4 {
5 public byte is_list;
6 public long list_size;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TF_AttrMetadata. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\TensorFlowNET.Core\Operations\TF_Input.cs (line 7)
4namespace Tensorflow
5{
6 [StructLayout(LayoutKind.Sequential)]
7 public struct TF_Input
8 {
9 public TF_Input(IntPtr oper, int index)
10 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TF_Input. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 8 hits
📄 src\TensorFlowNET.Core\Util\ProtoUtils.cs (line 11)
8 {
9 public static object GetSingleAttrValue(AttrValue value, AttrValue.ValueOneofCase valueCase)
10 {
11 return valueCase switch
12 {
13 AttrValue.ValueOneofCase.S => value.S.ToStringUtf8(),
14 AttrValue.ValueOneofCase.I => value.I,
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\TensorFlowNET.Core\Operations\ControlFlows\ControlFlowContext.cs (line 296)
293 /// <returns>A ControlFlowContext subclass</returns>
294 protected ControlFlowContext from_control_flow_context_def(ControlFlowContextDef context_def, string import_scope = "")
295 {
296 switch (context_def.CtxtCase)
297 {
298 case CtxtOneofCase.CondCtxt:
299 return new CondContext().from_proto(context_def.CondCtxt, import_scope: import_scope);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 40 hits
📄 src\TensorFlowNET.Core\Binding.Util.cs (line 144)
141
142 public static int len(object a)
143 {
144 switch (a)
145 {
146 case Tensor tensor:
147 return (int)tensor.shape[0];
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\TensorFlowNET.Core\Variables\RefVariable.cs (line 271)
268 private Operation _safe_initial_value_from_op(string name, Operation op, Dictionary<string, Operation> op_cache)
269 {
270 var op_type = op.node_def.Op;
271 switch (op_type)
272 {
273 case "IsVariableInitialized":
274 case "VarIsInitializedOp":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 36 hits
📄 src\TensorFlowNET.Core\Checkpoint\TrackableView.cs (line 45)
42 }
43 else
44 {
45 throw new InvalidDataException(
46 "Cannot get the object from the weak reference. Please consider if a null reference is passed to the constructor.");
47 }
48 }
💬 An exception is thrown from the getter of property Root (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\TensorFlowNET.Core\Contexts\Context.Device.cs (line 52)
49 {
50 if(_context_devices is null)
51 {
52 throw new AssertionError("Context must be initialized first.");
53 }
54 return _context_devices;
55 }
💬 An exception is thrown from the getter of property Devices (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 32 hits
📄 src\TensorFlowNET.Core\Data\Utils.cs (line 30)
27
28 if (showProgressInConsole)
29 {
30 Binding.tf_output_redirect.WriteLine($"Downloading {fileName}");
31 }
32
33 if (File.Exists(fileSaveTo))
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\TensorFlowNET.Core\Data\Utils.cs (line 37)
34 {
35 if (showProgressInConsole)
36 {
37 Binding.tf_output_redirect.WriteLine($"The file {fileName} already exists");
38 }
39
40 return;
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS044 Attribute must specify [AttributeUsage] 24 hits
📄 src\TensorFlowNET.Core\Tensors\c_api.tensor.cs (line 239)
236 /// internal static void MyFreeFunc (IntPtr data, IntPtr length){..}
237 /// </code>
238 /// </remarks>
239 public sealed class MonoPInvokeCallbackAttribute : Attribute
240 {
241 /// <summary>
242 /// Use this constructor to annotate the type of the callback function that
💬 MonoPInvokeCallbackAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\TensorFlowNET.Core\NumPy\AutoNumPyAttribute.cs (line 11)
8namespace Tensorflow.NumPy
9{
10 [DebuggerStepThrough]
11 public sealed class AutoNumPyAttribute : OnMethodBoundaryAspect
12 {
13 bool _changedMode = false;
14 bool _locked = false;
💬 AutoNumPyAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS047 LINQ traversal before filter 4 hits
📄 src\TensorFlowNET.Core\Functions\monomorphic_function.cs (line 241)
238
239 private (EagerDefinedFunction, ConcreteFunction) _construct_forward_backward(int num_doutputs)
240 {
241 var trainable_outputs = _func_graph.Outputs.Take(num_doutputs).Where(x => backprop_util.IsTrainable(x));
242
243 List<TensorSpec> signature = new();
244 foreach(var t in trainable_outputs)
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 src\TensorFlowNET.Core\Functions\monomorphic_function.cs (line 241)
238
239 private (EagerDefinedFunction, ConcreteFunction) _construct_forward_backward(int num_doutputs)
240 {
241 var trainable_outputs = _func_graph.Outputs.Take(num_doutputs).Where(x => backprop_util.IsTrainable(x));
242
243 List<TensorSpec> signature = new();
244 foreach(var t in trainable_outputs)
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS051 Locking on mutable reference 8 hits
📄 src\TensorFlowNET.Core\Framework\c_api_util.cs (line 60)
57 return;
58 }
59
60 lock (locker)
61 {
62 if (!File.Exists(file))
63 {
💬 A lock was obtained on locker but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\TensorFlowNET.Core\Framework\op_def_registry.py.cs (line 30)
27 {
28 if (_registered_ops.Count == 0)
29 {
30 lock (_registered_ops)
31 {
32 // double validation to avoid multi-thread executing
33 if (_registered_ops.Count > 0)
💬 A lock was obtained on _registered_ops but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 src\TensorFlowNET.Core\Data\Utils.cs (line 75)
72 Binding.tf_output_redirect.WriteLine($"The file {destFileName} already exists");
73 }
74
75 using (GZipStream unzipStream = new GZipStream(File.OpenRead(zipFile), CompressionMode.Decompress))
76 {
77 using (var destStream = File.Create(destFilePath))
78 {
💬 GZipStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\TensorFlowNET.Core\Data\Utils.cs (line 77)
74
75 using (GZipStream unzipStream = new GZipStream(File.OpenRead(zipFile), CompressionMode.Decompress))
76 {
77 using (var destStream = File.Create(destFilePath))
78 {
79 await unzipStream.CopyToAsync(destStream).ConfigureAwait(false);
80 await destStream.FlushAsync().ConfigureAwait(false);
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 104 hits
📄 src\TensorFlowNET.Core\Graphs\FuncGraph.cs (line 23)
20/// </summary>
21public class FuncGraph : Graph, IDisposable
22{
23 internal SafeFuncGraphHandle _func_graph_handle;
24 internal HashSet<Tensor> _resource_tensor_inputs;
25 internal HashSet<WeakReference<IVariableV1>> _watched_variables;
26 internal IEnumerable<WeakReference<IVariableV1>> _weak_variables;
💬 Disposable field _func_graph_handle in type FuncGraph is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\TensorFlowNET.Core\Graphs\FuncGraph.cs (line 31)
28 internal Dictionary<long, string> _output_names;
29 public string FuncName => _graph_key;
30
31 public Tensors Inputs { get; set; } = new Tensors();
32 public Tensors Outputs { get; set; } = new Tensors();
33 public Tensors FlatStructuredOutputs
34 {
💬 Disposable field Inputs in type FuncGraph is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

ant-design-blazor

2544 total diagnostics across 18 rules

SS001 Async method with void return type 48 hits
📄 components\carousel\Carousel.razor.cs (line 284)
281 InvokeStateHasChanged();
282 }
283
284 private async void AutoplaySlick(object state)
285 {
286 var index = IndexOfSlick(ActiveSlick) + 1;
287 if (index == _slicks.Count)
💬 Method AutoplaySlick is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 components\core\JsInterop\DomEventListener.cs (line 257)
254 {
255 AddShared<JsonElement>("window", "resize", AsyncCallback, false);
256
257 async void AsyncCallback(JsonElement _) => await callback.Invoke([new ResizeObserverEntry()]);
258 }
259 else
260 {
💬 Method AsyncCallback is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 344 hits
📄 components\calendar\Calendar.razor.cs (line 24)
21 [Documentation(DocumentationCategory.Components, DocumentationType.DataDisplay, "https://gw.alipayobjects.com/zos/antfincdn/dPQmLq08DI/Calendar.svg", Columns = 1, Title = "Calendar", SubTitle = "日历")]
22 public partial class Calendar : AntDomComponentBase, IDatePicker
23 {
24 DateTime IDatePicker.CurrentDate { get; set; } = DateTime.Now;
25 DateTime? IDatePicker.HoverDateTime { get; set; }
26
27 /// <summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 components\calendar\Calendar.razor.cs (line 32)
29 /// </summary>
30 /// <default value="DateTime.Now"/>
31 [Parameter]
32 public DateTime Value { get; set; } = DateTime.Now;
33
34 private DateTime _defaultValue;
35
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 112 hits
📄 components\statistic\CountDown.razor.cs (line 53)
50 [Parameter]
51 public int RefreshInterval { get; set; } = REFRESH_INTERVAL;
52
53 private const int REFRESH_INTERVAL = 1000 / 10;
54
55 private TimeSpan _countDown = TimeSpan.Zero;
56 private CancellationTokenSource _cts = new();
💬 The operands in the divisive expression 1000 / 10 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 components\carousel\Carousel.razor.cs (line 303)
300
301 if (index == 0 && Effect == CarouselEffect.ScrollX)
302 {
303 await Task.Delay((int)Autoplay.TotalMilliseconds / 2);
304 }
305
306 await InvokeAsync(() => StateHasChanged());
💬 The operands in the divisive expression (int)Autoplay.TotalMilliseconds / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 180 hits
📄 components\auto-complete\AutoComplete.razor.cs (line 360)
357
358 void IAutoCompleteRef.RemoveOption(AutoCompleteOption option)
359 {
360 if (AutoCompleteOptions?.Contains(option) == true)
361 AutoCompleteOptions?.Remove(option);
362 }
363
💬 Type AutoCompleteOption is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 components\breadcrumb\Breadcrumb.razor.cs (line 78)
75
76 internal void AddOption(BreadcrumbOption option)
77 {
78 if (!_existingOptions.Contains(option))
79 {
80 _existingOptions.Add(option);
81 }
💬 Type BreadcrumbOption is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 94 hits
📄 components\core\Helpers\MemberPath\PathHelper.cs (line 670)
667
668 public override int GetHashCode()
669 {
670 return HashCode.Combine(Path, ItemType, ParamType, ValueType);
671 }
672
673 public static bool operator ==(PathSetConfig x, PathSetConfig y)
💬 GetHashCode() refers to mutable field ItemType (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 components\core\Helpers\MemberPath\PathHelper.cs (line 670)
667
668 public override int GetHashCode()
669 {
670 return HashCode.Combine(Path, ItemType, ParamType, ValueType);
671 }
672
673 public static bool operator ==(PathSetConfig x, PathSetConfig y)
💬 GetHashCode() refers to mutable field ParamType (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 126 hits
📄 components\core\Helpers\MemberPath\PathHelper.cs (line 586)
583
584 #endregion
585
586 private readonly struct PathGetConfig
587 {
588 public readonly string Path;
589
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PathGetConfig. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 components\core\Helpers\MemberPath\PathHelper.cs (line 695)
692 public int GetHashCode(PathSetConfig obj) => obj.GetHashCode();
693 }
694
695 public readonly struct PathGetExpression
696 {
697 public readonly Expression Body;
698
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PathGetExpression. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 84 hits
📄 components\core\CssSizeLength.cs (line 121)
118
119 _value = ResolveBySuffix(value, out unit);
120
121 switch (unit)
122 {
123 case CssSizeLengthUnit.NoUnit:
124 _parsed = false;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 components\core\Helpers\DateHelper.cs (line 186)
183
184 public static DateTime FormatDateByPicker(DateTime dateTime, DatePickerType picker)
185 {
186 switch (picker)
187 {
188 case DatePickerType.Date: return dateTime.Date;
189 case DatePickerType.Year: return new DateTime(dateTime.Year, 1, 1);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 160 hits
📄 components\carousel\Carousel.razor.cs (line 121)
118 [JSInvokable]
119 public void HandleSwipe(string direction)
120 {
121 switch (direction)
122 {
123 case "left":
124 if (IsHorizontal) Next();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 components\core\CssSizeLength.cs (line 121)
118
119 _value = ResolveBySuffix(value, out unit);
120
121 switch (unit)
122 {
123 case CssSizeLengthUnit.NoUnit:
124 _parsed = false;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 14 hits
📄 components\slider\Slider.razor.cs (line 217)
214 }
215 else
216 {
217 throw new ArgumentOutOfRangeException($"Type argument of Slider should be one of {doubleType}, {tupleDoubleType}");
218 }
219 }
220 return _range.Value;
💬 An exception is thrown from the getter of property Range (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 components\slider\Slider.razor.cs (line 217)
214 }
215 else
216 {
217 throw new ArgumentOutOfRangeException($"Type argument of Slider should be one of {doubleType}, {tupleDoubleType}");
218 }
219 }
220 return _range.Value;
💬 An exception is thrown from the getter of property Range (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 108 hits
📄 site\AntDesign.Docs.MCP\Cli\DemoCommand.cs (line 66)
63 }
64 catch (Exception ex)
65 {
66 Console.Error.WriteLine($"Failed to load demos: {ex.Message}");
67 return 1;
68 }
69 }
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 site\AntDesign.Docs.MCP\Services\DemoService.cs (line 39)
36 }
37 catch (Exception ex)
38 {
39 Console.Error.WriteLine($"Warning: failed to download demos from {RemoteUrl}: {ex.Message}");
40 }
41 }
42
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 24 hits
📄 components\modal\confirmDialog\ModalServiceForConfirm.cs (line 123)
120 }
121
122 return await confirmRef.TaskCompletionSource.Task
123 .ContinueWith(t => t.Result == ConfirmResult.OK, TaskScheduler.Default);
124 }
125
126 /// <summary>
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 components\modal\confirmDialog\ModalServiceForConfirm.cs (line 123)
120 }
121
122 return await confirmRef.TaskCompletionSource.Task
123 .ContinueWith(t => t.Result == ConfirmResult.OK, TaskScheduler.Default);
124 }
125
126 /// <summary>
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS037 HttpClient instantiated directly 8 hits
📄 site\AntDesign.Docs.Server\Program.cs (line 28)
25 var host = request.Host.ToUriComponent();
26 var scheme = request.Scheme;
27 var baseAddress = $"{scheme}://{host}";
28 return new HttpClient(customHandler) { BaseAddress = new Uri(baseAddress) };
29 }
30 else
31 {
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 site\AntDesign.Docs.Server\Program.cs (line 32)
29 }
30 else
31 {
32 return new HttpClient(customHandler) { BaseAddress = new Uri("http://0.0.0.0:8181") };
33 }
34});
35
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS044 Attribute must specify [AttributeUsage] 164 hits
📄 components\tabs\Reuse\ReuseTabsPageAttribute.cs (line 12)
9 /// <summary>
10 /// Attribute for ReuseTabsPage, used to set the page title and other properties.
11 /// </summary>
12 public class ReuseTabsPageAttribute : Attribute
13 {
14 /// <summary>
15 /// Specifies the title of the tab.
💬 ReuseTabsPageAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 components\tabs\Reuse\ReuseTabsPageTitleAttribute.cs (line 9)
6
7namespace AntDesign
8{
9 public class ReuseTabsPageTitleAttribute : Attribute
10 {
11 public string Title { get; set; }
12
💬 ReuseTabsPageTitleAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 22 hits
📄 site\AntDesign.Docs\Pages\Components.razor.cs (line 124)
121 if (!onInitialize)
122 {
123 var menus = await DemoService.GetMenuAsync();
124 var current = menus.FirstOrDefault(x => x.Url == fullPageName.ToLowerInvariant());
125 var subPath = current.Children[0].Type == "menuItem" ? current.Children[0].Url : current.Children[0].Children[0].Url;
126 if (current != null)
127 {
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 site\AntDesign.Docs\Services\DemoService.cs (line 93)
90 {
91 var items = Array.Empty<DemoMenuItem>();
92
93 if (type.ToLowerInvariant() == "docs")
94 {
95 items = (await _cache.GetDocMenuAsync(CurrentLanguage)).OrderBy(x => x.Order).ToArray();
96 currentTitle = $"docs/{currentTitle}";
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS055 Multiple OrderBy() calls instead of ThenBy() 28 hits
📄 components\select\SelectBase.razor.cs (line 444)
441
442 if (SortByGroup == SortDirection.Ascending && SortByLabel == SortDirection.Descending)
443 {
444 return selectOption.OrderBy(g => g.GroupName).OrderByDescending(l => l.Label);
445 }
446
447 if (SortByGroup == SortDirection.Descending && SortByLabel == SortDirection.Ascending)
💬 Successive OrderBy() calls will maintain only the last specified sort order (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS055-MultipleOrderByCalls.md)
📄 components\select\SelectBase.razor.cs (line 454)
451
452 if (SortByGroup == SortDirection.Descending && SortByLabel == SortDirection.Descending)
453 {
454 return selectOption.OrderByDescending(g => g.GroupName).OrderByDescending(l => l.Label);
455 }
456
457 return selectOption;
💬 Successive OrderBy() calls will maintain only the last specified sort order (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS055-MultipleOrderByCalls.md)
SS058 String concatenated in a loop 26 hits
📄 components\date-picker\locale\FormatAnalyzer.cs (line 99)
96 }
97 else
98 {
99 _separators[^1] += format[i];
100 }
101 isLastSeparator = true;
102 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 components\date-picker\locale\FormatAnalyzer.cs (line 99)
96 }
97 else
98 {
99 _separators[^1] += format[i];
100 }
101 isLastSeparator = true;
102 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 14 hits
📄 site\AntDesign.Docs\Services\CompilerService.cs (line 196)
193 throw new ApplicationException(string.Join(Environment.NewLine, errors.Select(e => e.GetMessage())));
194 }
195
196 using var stream = new MemoryStream();
197
198 var emitResult = _compilation.Emit(stream);
199
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 site\AntDesign.Docs\Services\CompilerService.cs (line 196)
193 throw new ApplicationException(string.Join(Environment.NewLine, errors.Select(e => e.GetMessage())));
194 }
195
196 using var stream = new MemoryStream();
197
198 var emitResult = _compilation.Emit(stream);
199
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 988 hits
📄 components\select\internal\SelectContent.razor.cs (line 90)
87 private int _currentItemCount;
88 private Guid _internalId = Guid.NewGuid();
89 private bool _refocus;
90 private Timer _debounceTimer;
91 private string _inputString;
92 private bool _firstRender;
93
💬 Disposable field _debounceTimer in type SelectContent is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 components\calendar\internal\CalendarPanelChooser.razor.cs (line 13)
10 public partial class CalendarPanelChooser : AntDomComponentBase
11 {
12 [Parameter]
13 public Calendar Calendar { get; set; }
14
15 [Parameter]
16 public Action<DateTime, int> OnSelect { get; set; }
💬 Disposable field Calendar in type CalendarPanelChooser is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

ILRuntime

2420 total diagnostics across 18 rules

SS001 Async method with void return type 12 hits
📄 TestCases\CLRBindingTest.cs (line 135)
132 }
133
134
135 public async void Test4()
136 {
137 await Test.Instance.Test3<Test2>();
138 }
💬 Method Test4 is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 TestCases\AsyncAwaitTest.cs (line 140)
137 return lines;
138 }*/
139
140 public async static void TestRun5()
141 {
142 Console.WriteLine("TestConditionAwait Start ");
143 await DoConditionAwait();
💬 Method TestRun5 is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 8 hits
📄 Debugging\SharedDebuggerCommon\DebuggedProcess.cs (line 83)
80 {
81 socket.Send(DebugMessageType.CSAttach, new byte[0], 0);
82 waitingAttach = true;
83 DateTime now = DateTime.Now;
84 while (waitingAttach)
85 {
86 System.Threading.Thread.Sleep(1);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Debugging\SharedDebuggerCommon\DebuggedProcess.cs (line 87)
84 while (waitingAttach)
85 {
86 System.Threading.Thread.Sleep(1);
87 if ((DateTime.Now - now).TotalSeconds >= 30 || !Connected)
88 {
89 return false;
90 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 102 hits
📄 ILRuntime\Runtime\Intepreter\RegisterVM\JITCompiler.cs (line 1063)
1060 }
1061 else
1062 {
1063 bool codeSizeOK = ilm.IsRegisterBodyReady ? ilm.BodyRegister.Length <= Optimizer.MaximalInlineInstructionCount / 2 : def.Body.Instructions.Count <= Optimizer.MaximalInlineInstructionCount;
1064 if(codeSizeOK)
1065 {
1066 canInline = true;
💬 The operands in the divisive expression Optimizer.MaximalInlineInstructionCount / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 ILRuntime\Runtime\Intepreter\RegisterVM\JITCompiler.cs (line 575)
572 bool needInline = canInline && !hasConstrained;
573 if (needInline)
574 {
575 if (toInline.BodyRegister.Length > Optimizer.MaximalInlineInstructionCount / 2)
576 needInline = false;
577 }
578 if (!needInline)
💬 The operands in the divisive expression Optimizer.MaximalInlineInstructionCount / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 364 hits
📄 ILRuntime\HybridPatch\AssemblyInjector.cs (line 88)
85 InjectPatchType();
86 foreach (var i in asmInfo.Types)
87 {
88 patchingSet.Add(i.Definition);
89 }
90 foreach (var i in asmInfo.Types)
91 {
💬 Type TypeReference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 ILRuntime\HybridPatch\ReflectionReferences.cs (line 259)
256
257 public MethodReference GetReadObjectMethod(TypeReference type)
258 {
259 if (readObjCache.TryGetValue(type, out var res))
260 return res;
261 res = readObjInfo.MakeGenericInstanceMethod(type);
262 readObjCache[type] = res;
💬 Type TypeReference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 18 hits
📄 ILRuntime\CLR\Method\CLRMethod.cs (line 17)
14#endif
15namespace ILRuntime.CLR.Method
16{
17 public sealed class CLRMethod : IMethod
18 {
19 MethodInfo def;
20 ConstructorInfo cDef;
💬 Equals() and GetHashcode() must be implemented together on CLRMethod (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 ILRuntime\CLR\Method\ILMethod.cs (line 19)
16using System.Diagnostics;
17namespace ILRuntime.CLR.Method
18{
19 public sealed class ILMethod : IMethod
20 {
21 OpCode[] body;
22 OpCodeR[] bodyRegister;
💬 Equals() and GetHashcode() must be implemented together on ILMethod (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 98 hits
📄 ILRuntime\Reflection\ILRuntimeWrapperType.cs (line 172)
169
170 public override int GetHashCode()
171 {
172 return type.GetHashCode();
173 }
174
175 public override string ToString()
💬 GetHashCode() refers to mutable field type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 ILRuntime\CLR\Method\CLRMethod.cs (line 461)
458
459 public override int GetHashCode()
460 {
461 if (hashCode == -1)
462 hashCode = System.Threading.Interlocked.Add(ref instance_id, 1);
463 return hashCode;
464 }
💬 GetHashCode() refers to mutable field hashCode (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 16 hits
📄 ILRuntime\Runtime\Debugger\DebugSocket.cs (line 93)
90 catch (Exception ex)
91 {
92 Close();
93 throw ex;
94 }
95 }
96
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 ILRuntime\Runtime\Intepreter\ILIntepreter.cs (line 4746)
4743 }
4744 if (unhandledException)
4745 {
4746 throw ex;
4747 }
4748
4749 unhandledException = true;
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS015 String placeholders in wrong order 168 hits
📄 ILRuntime\Runtime\CLRBinding\MethodBindingGenerator.cs (line 152)
149 {
150 if (i.DeclaringType != type)
151 {
152 sb.AppendLine(string.Format(" method = typeof({1}).GetMethod(\"{0}\", flag, null, args, null);", i.Name, i.DeclaringType.FullName));
153 }
154 else
155 sb.AppendLine(string.Format(" method = type.GetMethod(\"{0}\", flag, null, args, null);", i.Name));
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 ILRuntime\Runtime\CLRBinding\FieldBindingGenerator.cs (line 26)
23 continue;
24 if (i.DeclaringType != type)
25 {
26 sb.AppendLine(string.Format(" field = typeof({1}).GetField(\"{0}\", flag);", i.Name, i.DeclaringType.FullName));
27 }
28 else
29 sb.AppendLine(string.Format(" field = type.GetField(\"{0}\", flag);", i.Name));
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 218 hits
📄 ILRuntime\HybridPatch\InjectionContext.cs (line 8)
5
6namespace ILRuntime.Hybrid
7{
8 internal struct TypeInjectionContext
9 {
10 public bool IsGenericType;
11 public FieldDefinition ExtraFieldILType;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TypeInjectionContext. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 ILRuntime\HybridPatch\InjectionContext.cs (line 26)
23 public List<MethodRedirectionInjectionContext> MethodRedirections;
24 }
25
26 internal struct MethodRedirectionInjectionContext
27 {
28 public FieldDefinition ILMethod;
29 public FieldReference ILMethodGenericInstance;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MethodRedirectionInjectionContext. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 564 hits
📄 ILRuntime\CLR\Method\CLRMethod.cs (line 362)
359 {
360 var p = Minus(esp, i);
361 var val = i <= paramCount ? param[paramCount - i] : instance;
362 switch (p->ObjectType)
363 {
364 case ObjectTypes.StackObjectReference:
365 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 ILRuntime\CLR\Method\ILMethod.cs (line 506)
503
504 foreach (var ins in body)
505 {
506 switch (ins.Code)
507 {
508 case OpCodeEnum.Call:
509 case OpCodeEnum.Newobj:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 596 hits
📄 ILRuntime\CLR\Method\CLRMethod.cs (line 362)
359 {
360 var p = Minus(esp, i);
361 var val = i <= paramCount ? param[paramCount - i] : instance;
362 switch (p->ObjectType)
363 {
364 case ObjectTypes.StackObjectReference:
365 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 ILRuntime\CLR\Method\ILMethod.cs (line 506)
503
504 foreach (var ins in body)
505 {
506 switch (ins.Code)
507 {
508 case OpCodeEnum.Call:
509 case OpCodeEnum.Newobj:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS044 Attribute must specify [AttributeUsage] 42 hits
📄 ILRuntime\Other\NeedAdaptorAttribute.cs (line 6)
3 /// <summary>
4 /// A Class Custom Attr, It tells the CodeGenerationTools :there is a class need to generate an adaptor for ILScript
5 /// </summary>
6 public class NeedAdaptorAttribute : System.Attribute
7 {
8
9 }
💬 NeedAdaptorAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 ILRuntime\HybridPatch\AssemblyPatch.cs (line 492)
489 }
490 }
491
492 public class PatchableAssemblyAttribute : Attribute
493 {
494 public string Name { get; set; }
495 public string AssemblyHash { get; set; }
💬 PatchableAssemblyAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS048 Locking on discouraged object (string, Type, this) 4 hits
📄 ILRuntime\CLR\TypeSystem\CLRType.cs (line 957)
954
955 public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)
956 {
957 lock (this)
958 {
959 if (genericInstances == null)
960 genericInstances = new List<CLRType>();
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 ILRuntime\CLR\TypeSystem\CLRType.cs (line 957)
954
955 public IType MakeGenericInstance(KeyValuePair<string, IType>[] genericArguments)
956 {
957 lock (this)
958 {
959 if (genericInstances == null)
960 genericInstances = new List<CLRType>();
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS051 Locking on mutable reference 156 hits
📄 ILRuntime\Other\ThreadSafeDictionary.cs (line 39)
36 {
37 get
38 {
39 lock(dic)
40 return dic.Count;
41 }
42 }
💬 A lock was obtained on dic but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 ILRuntime\Other\ThreadSafeDictionary.cs (line 30)
27
28 set
29 {
30 lock(dic)
31 dic[key] = value;
32 }
33 }
💬 A lock was obtained on dic but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS053 Pointless collection ToString() 2 hits
📄 TestCases\Test01.cs (line 458)
455 public static void UnitTest_Generics3()
456 {
457 Console.WriteLine("UnitTest_Generics3");
458 Console.WriteLine(new List<NestedTest>().ToString());
459 }
460
461 public static void UnitTest_Generics4()
💬 .ToString() was called on a collection which results in impractical output (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS053-PointlessCollectionToString.md)
📄 TestCases\Test01.cs (line 458)
455 public static void UnitTest_Generics3()
456 {
457 Console.WriteLine("UnitTest_Generics3");
458 Console.WriteLine(new List<NestedTest>().ToString());
459 }
460
461 public static void UnitTest_Generics4()
💬 .ToString() was called on a collection which results in impractical output (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS053-PointlessCollectionToString.md)
SS057 Collection manipulated during traversal 4 hits
📄 LitJson\JsonData.cs (line 502)
499
500 for (int i = 0; i < object_list.Count; i++) {
501 if (object_list[i].Key == (string) key) {
502 object_list.RemoveAt (i);
503 break;
504 }
505 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 LitJson\JsonData.cs (line 502)
499
500 for (int i = 0; i < object_list.Count; i++) {
501 if (object_list[i].Key == (string) key) {
502 object_list.RemoveAt (i);
503 break;
504 }
505 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 32 hits
📄 ILRuntime\CLR\Method\CLRMethod.cs (line 439)
436 string argString = "";
437 for (int i = 0; i < genericArguments.Length; i++)
438 {
439 argString += genericArguments[i].TypeForCLR.FullName + ", ";
440 }
441
442 argString = argString.Substring(0, argString.Length - 2);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 ILRuntime\CLR\TypeSystem\CLRType.cs (line 994)
991 string argString = "";
992 for (int i = 0; i < args.Length; i++)
993 {
994 argString += args[i].FullName + ", ";
995 }
996
997 argString = argString.Substring(0, argString.Length - 2);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 16 hits
📄 ILRuntime\Runtime\Intepreter\RegisterVM\AsyncJITCompileWorker.cs (line 12)
9{
10 class AsyncJITCompileWorker
11 {
12 AutoResetEvent evt = new AutoResetEvent(false);
13 Queue<ILMethod> jobs = new Queue<ILMethod>();
14 bool exit;
15 Thread thread;
💬 Disposable field evt in type AsyncJITCompileWorker is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 ILRuntime\Runtime\Intepreter\RegisterVM\AsyncJITCompileWorker.cs (line 12)
9{
10 class AsyncJITCompileWorker
11 {
12 AutoResetEvent evt = new AutoResetEvent(false);
13 Queue<ILMethod> jobs = new Queue<ILMethod>();
14 bool exit;
15 Thread thread;
💬 Disposable field evt in type AsyncJITCompileWorker is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

OpenRA

2320 total diagnostics across 16 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 32 hits
📄 OpenRA.Game\Map\MapPreview.cs (line 458)
455 using (var dataStream = p.GetStream("map.png"))
456 newData.Preview = new Png(dataStream);
457
458 newData.ModifiedDate = p.Name != null ? File.GetLastWriteTime(p.Name) : DateTime.Now;
459
460 // Assign the new data atomically
461 // Local maps have higher precedence than remote/generated maps,
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 OpenRA.Game\Server\Server.cs (line 306)
303
304 playerDatabase = modData.GetOrCreate<PlayerDatabase>();
305
306 randomSeed = (int)DateTime.Now.ToBinary();
307
308 if (IsMultiplayer && settings.EnableGeoIP)
309 GeoIP.Initialize();
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 1242 hits
📄 OpenRA.Game\CVec.cs (line 33)
30 public static CVec operator -(CVec a, CVec b) { return new CVec(a.X - b.X, a.Y - b.Y); }
31 public static CVec operator *(int a, CVec b) { return new CVec(a * b.X, a * b.Y); }
32 public static CVec operator *(CVec b, int a) { return new CVec(a * b.X, a * b.Y); }
33 public static CVec operator /(CVec a, int b) { return new CVec(a.X / b, a.Y / b); }
34
35 public static CVec operator -(CVec a) { return new CVec(-a.X, -a.Y); }
36
💬 The operands in the divisive expression a.X / b are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 OpenRA.Game\CVec.cs (line 33)
30 public static CVec operator -(CVec a, CVec b) { return new CVec(a.X - b.X, a.Y - b.Y); }
31 public static CVec operator *(int a, CVec b) { return new CVec(a * b.X, a * b.Y); }
32 public static CVec operator *(CVec b, int a) { return new CVec(a * b.X, a * b.Y); }
33 public static CVec operator /(CVec a, int b) { return new CVec(a.X / b, a.Y / b); }
34
35 public static CVec operator -(CVec a) { return new CVec(-a.X, -a.Y); }
36
💬 The operands in the divisive expression a.Y / b are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 296 hits
📄 OpenRA.Game\GameInformation.cs (line 166)
163 /// <summary>Gets the player information for the specified runtime player instance.</summary>
164 public Player GetPlayer(OpenRA.Player runtimePlayer)
165 {
166 playersByRuntime.TryGetValue(runtimePlayer, out var player);
167
168 return player;
169 }
💬 Type Player is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 OpenRA.Game\GameInformation.cs (line 159)
156 Fingerprint = client.Fingerprint
157 };
158
159 playersByRuntime.Add(runtimePlayer, player);
160 Players.Add(player);
161 }
162
💬 Type Player is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 8 hits
📄 OpenRA.Game\World.cs (line 643)
640 public static bool operator ==(TraitPair<T> me, TraitPair<T> other) { return me.Actor == other.Actor && Equals(me.Trait, other.Trait); }
641 public static bool operator !=(TraitPair<T> me, TraitPair<T> other) { return !(me == other); }
642
643 public override int GetHashCode() { return Actor.GetHashCode() ^ Trait.GetHashCode(); }
644
645 public bool Equals(TraitPair<T> other) { return this == other; }
646 public override bool Equals(object obj) { return obj is TraitPair<T> pair && Equals(pair); }
💬 GetHashCode() refers to mutable field Actor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 OpenRA.Game\World.cs (line 643)
640 public static bool operator ==(TraitPair<T> me, TraitPair<T> other) { return me.Actor == other.Actor && Equals(me.Trait, other.Trait); }
641 public static bool operator !=(TraitPair<T> me, TraitPair<T> other) { return !(me == other); }
642
643 public override int GetHashCode() { return Actor.GetHashCode() ^ Trait.GetHashCode(); }
644
645 public bool Equals(TraitPair<T> other) { return this == other; }
646 public override bool Equals(object obj) { return obj is TraitPair<T> pair && Equals(pair); }
💬 GetHashCode() refers to mutable field Trait (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 134 hits
📄 OpenRA.Game\Map\CellCoordsRegion.cs (line 18)
15
16namespace OpenRA
17{
18 public readonly struct CellCoordsRegion : IEnumerable<CPos>
19 {
20 public struct CellCoordsEnumerator : IEnumerator<CPos>
21 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CellCoordsRegion. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 OpenRA.Game\Map\CellCoordsRegion.cs (line 20)
17{
18 public readonly struct CellCoordsRegion : IEnumerable<CPos>
19 {
20 public struct CellCoordsEnumerator : IEnumerator<CPos>
21 {
22 readonly CellCoordsRegion r;
23
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CellCoordsEnumerator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 30 hits
📄 OpenRA.Game\Network\Order.cs (line 118)
115 var target = Target.Invalid;
116 if (flags.HasField(OrderFields.Target))
117 {
118 switch ((TargetType)r.ReadByte())
119 {
120 case TargetType.Actor:
121 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 OpenRA.Game\Network\Order.cs (line 395)
392 if (fields.HasField(OrderFields.Target))
393 {
394 w.Write((byte)targetState.Type);
395 switch (targetState.Type)
396 {
397 case TargetType.Actor:
398 w.Write(UIntFromActor(targetState.Actor));
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 96 hits
📄 OpenRA.Game\GameInformation.cs (line 82)
79 {
80 var keyParts = node.Key.Split('@');
81
82 switch (keyParts[0])
83 {
84 case "Root":
85 FieldLoader.Load(info, node.Value);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 OpenRA.Game\Network\Order.cs (line 118)
115 var target = Target.Invalid;
116 if (flags.HasField(OrderFields.Target))
117 {
118 switch ((TargetType)r.ReadByte())
119 {
120 case TargetType.Actor:
121 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 2 hits
📄 OpenRA.Game\Traits\Target.cs (line 169)
166 return terrainCenterPosition;
167 case TargetType.Invalid:
168 default:
169 throw new InvalidOperationException("Attempting to query the position of an invalid Target");
170 }
171 }
172 }
💬 An exception is thrown from the getter of property CenterPosition (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 OpenRA.Game\Traits\Target.cs (line 169)
166 return terrainCenterPosition;
167 case TargetType.Invalid:
168 default:
169 throw new InvalidOperationException("Attempting to query the position of an invalid Target");
170 }
171 }
172 }
💬 An exception is thrown from the getter of property CenterPosition (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS025 Exception thrown from finally block 2 hits
📄 OpenRA.Game\Sync.cs (line 202)
199 // When the world is disposing all actors and effects have been removed
200 // So do not check the hash for a disposing world since it definitively has changed
201 if (unsyncCount == 0 && checkSyncHash && world != null && !world.Disposing && sync != world.SyncHash())
202 throw new InvalidOperationException("RunUnsynced: sync-changing code may not run here");
203 }
204 }
205
💬 An exception is thrown from a finally block (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS025-ExceptionThrownFromFinallyBlock.md)
📄 OpenRA.Game\Sync.cs (line 202)
199 // When the world is disposing all actors and effects have been removed
200 // So do not check the hash for a disposing world since it definitively has changed
201 if (unsyncCount == 0 && checkSyncHash && world != null && !world.Disposing && sync != world.SyncHash())
202 throw new InvalidOperationException("RunUnsynced: sync-changing code may not run here");
203 }
204 }
205
💬 An exception is thrown from a finally block (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS025-ExceptionThrownFromFinallyBlock.md)
SS041 Unnecessary enumerable materialization 36 hits
📄 OpenRA.Mods.Common\Traits\RevealsShroud.cs (line 47)
44 {
45 base.Created(self);
46
47 rangeModifiers = self.TraitsImplementing<IRevealsShroudModifier>().ToArray().Select(x => x.GetRevealsShroudModifier());
48 }
49
50 protected override void AddCellsToPlayerShroud(Actor self, Player p, PPos[] uv)
💬 ToArray is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 OpenRA.Mods.Common\Activities\Attack.cs (line 56)
53 this.forceAttack = forceAttack;
54 ChildHasPriority = false;
55
56 attackTraits = self.TraitsImplementing<AttackFrontal>().ToArray().Where(t => !t.IsTraitDisabled);
57 revealsShroud = self.TraitsImplementing<RevealsShroud>().ToArray();
58 facing = self.Trait<IFacing>();
59 positionable = self.Trait<IPositionable>();
💬 ToArray is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS046 Unbounded stackalloc 6 hits
📄 OpenRA.Game\CryptoUtil.cs (line 272)
269 return string.Empty;
270
271 // excessively avoid stack overflow if source is too large (considering that we're allocating a new string)
272 var buffer = source.Length <= 256 ? stackalloc char[source.Length * 2] : new char[source.Length * 2];
273 return ToHexInternal(source, buffer, lowerCase);
274 }
275
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
📄 OpenRA.Mods.Common\FileFormats\WavReader.cs (line 145)
142 Span<int> predictor = stackalloc int[channels];
143 Span<int> index = stackalloc int[channels];
144
145 Span<byte> channelData = stackalloc byte[channels * 4];
146 baseStream.ReadBytes(channelData);
147 var cd = 0;
148 for (var c = 0; c < channels; c++)
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
SS051 Locking on mutable reference 86 hits
📄 OpenRA.Game\Server\Server.cs (line 229)
226
227 void MapStatusChanged(string uid, Session.MapStatus status)
228 {
229 lock (LobbyInfo)
230 {
231 if (LobbyInfo.GlobalSettings.Map == uid)
232 LobbyInfo.GlobalSettings.MapStatus = status;
💬 A lock was obtained on LobbyInfo but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 OpenRA.Game\Server\Server.cs (line 1277)
1274
1275 public void SyncLobbyInfo()
1276 {
1277 lock (LobbyInfo)
1278 {
1279 if (State == ServerState.WaitingPlayers) // Don't do this while the game is running, it breaks things!
1280 DispatchServerOrdersToClients(Order.FromTargetString("SyncInfo", LobbyInfo.Serialize(), true));
💬 A lock was obtained on LobbyInfo but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS055 Multiple OrderBy() calls instead of ThenBy() 2 hits
📄 OpenRA.Mods.Common\Traits\Player\BulkProductionQueue.cs (line 145)
142 // Some units may request a specific production type, which is ignored if the AllTech cheat is enabled
143 var type = developerMode.AllTech ? Info.Type : (bi.BuildAtProductionType ?? Info.Type);
144
145 var producers = self.World.ActorsWithTrait<Production>()
146 .Where(x => x.Actor.Owner == self.Owner
147 && !x.Trait.IsTraitDisabled
148 && x.Trait.Info.Produces.Contains(type))
💬 Successive OrderBy() calls will maintain only the last specified sort order (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS055-MultipleOrderByCalls.md)
📄 OpenRA.Mods.Common\Traits\Player\BulkProductionQueue.cs (line 145)
142 // Some units may request a specific production type, which is ignored if the AllTech cheat is enabled
143 var type = developerMode.AllTech ? Info.Type : (bi.BuildAtProductionType ?? Info.Type);
144
145 var producers = self.World.ActorsWithTrait<Production>()
146 .Where(x => x.Actor.Owner == self.Owner
147 && !x.Trait.IsTraitDisabled
148 && x.Trait.Info.Produces.Contains(type))
💬 Successive OrderBy() calls will maintain only the last specified sort order (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS055-MultipleOrderByCalls.md)
SS057 Collection manipulated during traversal 10 hits
📄 OpenRA.Game\Scripting\ScriptObjectWrapper.cs (line 69)
66 // NOTE: In newer versions of .NET modifying the collection by calling Remove while iterating over it is valid
67 foreach (var m in members)
68 if (targetType == m.Value.Target.GetType())
69 members.Remove(m.Key);
70 }
71
72 public bool ContainsKey(string key) { return members.ContainsKey(key); }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 OpenRA.Game\Server\Server.cs (line 1097)
1094 foreach (var c in LobbyInfo.Clients)
1095 {
1096 if (c.Bot != null)
1097 LobbyInfo.Clients.Remove(c);
1098 else
1099 c.Slot = null;
1100 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 32 hits
📄 OpenRA.Game\GameRules\ActorInfo.cs (line 151)
148
149 exceptionString += "Missing:\n";
150 foreach (var m in missing)
151 exceptionString += m + " \n";
152
153 exceptionString += "Unresolved:\n";
154 foreach (var u in unresolved)
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 OpenRA.Game\GameRules\ActorInfo.cs (line 159)
156 var deps = u.Dependencies.Where(d => !resolved.Exists(r => r.Type == d));
157 var optDeps = u.OptionalDependencies.Where(d => !resolved.Exists(r => r.Type == d));
158 var allDeps = string.Join(", ", deps.Select(o => o.ToString()).Concat(optDeps.Select(o => $"[{o}]")));
159 exceptionString += $"{u.Type}: {{ {allDeps} }}\n";
160 }
161
162 throw new YamlException(exceptionString);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 306 hits
📄 OpenRA.Game\World.cs (line 37)
34 readonly List<IEffect> effects = [];
35 readonly List<IEffect> unpartitionedEffects = [];
36 readonly List<ISync> syncedEffects = [];
37 readonly ModData modData;
38 readonly GameSettings gameSettings;
39
40 readonly Queue<Action<World>> frameEndActions = [];
💬 Disposable field modData in type World is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 OpenRA.Game\World.cs (line 137)
134 renderPlayer = LocalPlayer;
135 }
136
137 public readonly Actor WorldActor;
138
139 public readonly Map Map;
140
💬 Disposable field WorldActor in type World is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Lean

2106 total diagnostics across 19 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 22 hits
📄 Logging\QueueLogHandler.cs (line 72)
69 OnLogEvent(log);
70
71 Console.ForegroundColor = ConsoleColor.Red;
72 _error.WriteLine(DateTime.Now.ToString(DateFormat, CultureInfo.InvariantCulture) + " Error:: " + text);
73 Console.ResetColor();
74 }
75
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Logging\FunctionalLogHandler.cs (line 61)
58 {
59 if (_error != null)
60 {
61 _error(DateTime.Now.ToString(DateFormat, CultureInfo.InvariantCulture) + " ERROR " + text);
62 }
63 }
64
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 52 hits
📄 Common\Algorithm\Framework\Alphas\Insight.cs (line 556)
553 barSize = barSize == Resolution.Tick ? Resolution.Second : barSize;
554 // remap hours to minutes to avoid complications w/ stepping through, for example 9->10 is an hour step but market opens at 9:30
555 barSize = barSize == Resolution.Hour ? Resolution.Minute : barSize;
556 var barCount = (int)(period.Ticks / barSize.ToTimeSpan().Ticks);
557 var closeTimeUtc = ComputeCloseTime(exchangeHours, generatedTimeUtc, barSize, barCount);
558 if (closeTimeUtc == generatedTimeUtc)
559 {
💬 The operands in the divisive expression period.Ticks / barSize.ToTimeSpan().Ticks are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Common\Algorithm\Framework\Alphas\Insight.cs (line 578)
575 if (delta != TimeSpan.Zero)
576 {
577 // continue stepping forward using minute resolution for the remainder
578 barCount = (int) (delta.Ticks / Time.OneMinute.Ticks);
579 if (barCount > 0)
580 {
581 closeTimeUtc = ComputeCloseTime(exchangeHours, closeTimeUtc, Resolution.Minute, barCount);
💬 The operands in the divisive expression delta.Ticks / Time.OneMinute.Ticks are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 28 hits
📄 Common\Algorithm\Framework\Alphas\InsightCollection.cs (line 103)
100 lock(_insights)
101 {
102 return _insights.TryGetValue(item.Symbol, out var symbolInsights)
103 && symbolInsights.Contains(item);
104 }
105 }
106
💬 Type Insight is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Common\CapacityEstimate.cs (line 106)
103 }
104
105 symbolCapacity.OnOrderEvent(orderEvent);
106 if (_monitoredSymbolCapacitySet.Contains(symbolCapacity))
107 {
108 return;
109 }
💬 Type SymbolCapacity is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 22 hits
📄 Common\Data\Channel.cs (line 100)
97 unchecked
98 {
99 int hash = (int)2166136261;
100 hash = (hash * 16777619) ^ Name.GetHashCode();
101 hash = (hash * 16777619) ^ Symbol.GetHashCode();
102 return hash;
103 }
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Common\Data\Channel.cs (line 101)
98 {
99 int hash = (int)2166136261;
100 hash = (hash * 16777619) ^ Name.GetHashCode();
101 hash = (hash * 16777619) ^ Symbol.GetHashCode();
102 return hash;
103 }
104 }
💬 GetHashCode() refers to mutable property Symbol (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 8 hits
📄 Common\Data\Auxiliary\SymbolDateRange.cs (line 24)
21 /// Represents security identifier within a date range.
22 /// </summary>
23#pragma warning disable CA1815 // Override equals and operator equals on value types
24 public readonly struct SymbolDateRange
25 {
26 /// <summary>
27 /// Represents a unique security identifier.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SymbolDateRange. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Common\Data\Auxiliary\TickerDateRange.cs (line 25)
22 /// Represents stock data for a specific ticker within a date range.
23 /// </summary>
24#pragma warning disable CA1815 // Override equals and operator equals on value types
25 public readonly struct TickerDateRange
26 {
27 /// <summary>
28 /// Ticker simple name of stock
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TickerDateRange. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 82 hits
📄 Common\Brokerages\FTXBrokerageModel.cs (line 138)
135 stopPrice = (order as StopLimitOrder)?.StopPrice;
136 }
137
138 switch (order.Direction)
139 {
140 case OrderDirection.Sell:
141 if (stopPrice > security.BidPrice)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Common\Brokerages\DefaultBrokerageModel.cs (line 295)
292 {
293 if (AccountType == AccountType.Cash)
294 {
295 switch (security.Type)
296 {
297 case SecurityType.Equity:
298 return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 114 hits
📄 Common\Api\Nodes.cs (line 214)
211 {
212 string result = "";
213
214 switch (Target)
215 {
216 case NodeType.Backtest:
217 result += "B";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Common\Algorithm\Framework\Portfolio\SignalExports\Collective2SignalExport.cs (line 486)
483 {
484 if (symbol.SecurityType.IsOption())
485 {
486 switch (symbol.ID.OptionRight)
487 {
488 case OptionRight.Put:
489 return 0;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 24 hits
📄 Common\Indicators\RollingWindow.cs (line 150)
147
148 if (_samples <= _size)
149 {
150 throw new InvalidOperationException(Messages.RollingWindow.NoItemsRemovedYet);
151 }
152 return _mostRecentlyRemoved;
153 }
💬 An exception is thrown from the getter of property MostRecentlyRemoved (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Common\SecurityIdentifier.cs (line 145)
142 {
143 if (_underlying == null)
144 {
145 throw new InvalidOperationException(Messages.SecurityIdentifier.NoUnderlyingForIdentifier);
146 }
147 return _underlying;
148 }
💬 An exception is thrown from the getter of property Underlying (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 4 hits
📄 Compression\Compression.cs (line 335)
332 foreach (var kvp in data)
333 {
334 var entry = archive.CreateEntry(kvp.Value, compressionLevel.Value);
335 using var entryStream = entry.Open();
336 await entryStream.WriteAsync(kvp.Key).ConfigureAwait(false);
337 }
338 }
💬 Async overload available for ZipArchiveEntry.Open (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Compression\Compression.cs (line 379)
376 existingEntry?.Delete();
377 }
378 var entry = archive.CreateEntry(kvp.Key, compressionLevel.Value);
379 using var entryStream = entry.Open();
380 await kvp.Value.CopyToAsync(entryStream).ConfigureAwait(false);
381 }
382 }
💬 Async overload available for ZipArchiveEntry.Open (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 40 hits
📄 Common\Algorithm\Framework\Portfolio\SignalExports\VBaseSignalExport.cs (line 159)
156 };
157 request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
158
159 using var response = HttpClient.SendAsync(request).Result;
160 var body = response.Content.ReadAsStringAsync().Result;
161 if (!response.IsSuccessStatusCode)
162 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Common\Algorithm\Framework\Portfolio\SignalExports\VBaseSignalExport.cs (line 160)
157 request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
158
159 using var response = HttpClient.SendAsync(request).Result;
160 var body = response.Content.ReadAsStringAsync().Result;
161 if (!response.IsSuccessStatusCode)
162 {
163 algorithm.Error($"vBase API returned {response.StatusCode}. Body: {body}");
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 Common\Scheduling\CompositeTimeRule.cs (line 72)
69 {
70 // make unqiue times and order the events before yielding
71 var enumerable = new[] {date};
72 var times = Rules.SelectMany(time => time.CreateUtcEventTimes(enumerable)).ToHashSet().OrderBy(x => x);
73 foreach (var time in times)
74 {
75 yield return time;
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 Common\Scheduling\CompositeTimeRule.cs (line 72)
69 {
70 // make unqiue times and order the events before yielding
71 var enumerable = new[] {date};
72 var times = Rules.SelectMany(time => time.CreateUtcEventTimes(enumerable)).ToHashSet().OrderBy(x => x);
73 foreach (var time in times)
74 {
75 yield return time;
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS047 LINQ traversal before filter 2 hits
📄 Common\Securities\Future\FuturesExpiryUtilityFunctions.cs (line 268)
265 {
266
267 var daysInMonth = DateTime.DaysInMonth(time.Year, time.Month);
268 return (from day in Enumerable.Range(1, daysInMonth).Reverse()
269 where new DateTime(time.Year, time.Month, day).DayOfWeek == dayOfWeek
270 select new DateTime(time.Year, time.Month, day)).First();
271 }
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 Common\Securities\Future\FuturesExpiryUtilityFunctions.cs (line 268)
265 {
266
267 var daysInMonth = DateTime.DaysInMonth(time.Year, time.Month);
268 return (from day in Enumerable.Range(1, daysInMonth).Reverse()
269 where new DateTime(time.Year, time.Month, day).DayOfWeek == dayOfWeek
270 select new DateTime(time.Year, time.Month, day)).First();
271 }
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS048 Locking on discouraged object (string, Type, this) 4 hits
📄 Common\Util\KeyStringSynchronizer.cs (line 58)
55
56 private void ExecuteImplementation(string key, bool singleExecution, Action action)
57 {
58 lock (key)
59 {
60 while (true)
61 {
💬 A lock was used on an object of type string which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 Common\Util\KeyStringSynchronizer.cs (line 102)
99 }
100 }
101
102 lock (existingKey)
103 {
104 // if we are here the thread that had the lock finished
105 if (!singleExecution)
💬 A lock was used on an object of type string which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 2 hits
📄 Common\SymbolRepresentation.cs (line 441)
438
439 optionTicker = match.Groups[1].Value;
440 expiry = DateTime.ParseExact(match.Groups[2].Value, DateFormat.SixCharacter, null);
441 right = match.Groups[3].Value.ToUpperInvariant() == "C" ? OptionRight.Call : OptionRight.Put;
442 strike = Parse.Decimal(match.Groups[4].Value) / 1000m;
443
444 return true;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Common\SymbolRepresentation.cs (line 441)
438
439 optionTicker = match.Groups[1].Value;
440 expiry = DateTime.ParseExact(match.Groups[2].Value, DateFormat.SixCharacter, null);
441 right = match.Groups[3].Value.ToUpperInvariant() == "C" ? OptionRight.Call : OptionRight.Put;
442 strike = Parse.Decimal(match.Groups[4].Value) / 1000m;
443
444 return true;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS050 Parameter assigned in constructor 4 hits
📄 Common\Algorithm\Framework\Alphas\Insight.cs (line 629)
626 {
627 if (period == TimeSpan.Zero)
628 {
629 period = Time.OneSecond;
630 }
631
632 Period = period;
💬 Suspicious assignment of parameter period in constructor of TimeSpanPeriodSpecification (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
📄 Common\Securities\Option\StrategyMatcher\OptionStrategyMatcherOptions.cs (line 85)
82 {
83 if (maximumDuration == default(TimeSpan))
84 {
85 maximumDuration = Time.OneMinute;
86 }
87
88 if (definitionEnumerator == null)
💬 Suspicious assignment of parameter maximumDuration in constructor of OptionStrategyMatcherOptions (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
SS051 Locking on mutable reference 10 hits
📄 Common\Util\MemoizingEnumerable.cs (line 83)
80 while (i <= _buffer.Count)
81 {
82 // sync for multiple threads access to _enumerator and _buffer
83 lock (_buffer)
84 {
85 // check to see if we need to move next
86 if (_enumerator != null && i >= _buffer.Count)
💬 A lock was obtained on _buffer but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Common\Data\Auxiliary\LocalZipMapFileProvider.cs (line 86)
83 MapFileResolver result;
84 // we use a lock so that only 1 thread loads the map file resolver while the rest wait
85 // else we could have multiple threads loading the map file resolver at the same time!
86 lock (_lock)
87 {
88 if (!_cache.TryGetValue(auxiliaryDataKey, out result))
89 {
💬 A lock was obtained on _lock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 12 hits
📄 Common\Algorithm\Framework\Portfolio\SignalExports\VBaseSignalExport.cs (line 132)
129
130 foreach (var target in parameters.Targets)
131 {
132 csv += $"{target.Symbol.Value},{target.Quantity.ToStringInvariant()}\n";
133 }
134 return csv;
135 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Common\Algorithm\Framework\Portfolio\SignalExports\NumeraiSignalExport.cs (line 156)
153 return false;
154 }
155
156 positions += $"{parameters.Algorithm.Ticker(holding.Symbol)} {_numeraiMarketFormat[holding.Symbol.ID.Market]},{holding.Quantity.ToStringInvariant()}\n";
157 }
158
159 return true;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 12 hits
📄 Compression\Compression.cs (line 351)
348 public static async Task ZipStreamsAsync(string target, IEnumerable<KeyValuePair<string, Stream>> data, ZipArchiveMode? mode = null,
349 CompressionLevel? compressionLevel = null)
350 {
351 using var fileStream = mode == ZipArchiveMode.Update
352 ? new FileStream(target, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)
353 : new FileStream(target, FileMode.Create, FileAccess.Write, FileShare.None);
354 await ZipStreamsAsync(fileStream, data, mode, compressionLevel).ConfigureAwait(false);
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Compression\Compression.cs (line 259)
256 try
257 {
258 //Read out the zipped data into a string, save in array:
259 using (var zipStream = new ZipInputStream(stream))
260 {
261 while (true)
262 {
💬 ZipInputStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 1662 hits
📄 Logging\QueueLogHandler.cs (line 30)
27 {
28 private readonly ConcurrentQueue<LogEntry> _logs;
29 private const string DateFormat = "yyyyMMdd HH:mm:ss";
30 private readonly TextWriter _trace;
31 private readonly TextWriter _error;
32
33 /// <summary>
💬 Disposable field _trace in type QueueLogHandler is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Logging\QueueLogHandler.cs (line 31)
28 private readonly ConcurrentQueue<LogEntry> _logs;
29 private const string DateFormat = "yyyyMMdd HH:mm:ss";
30 private readonly TextWriter _trace;
31 private readonly TextWriter _error;
32
33 /// <summary>
34 /// Public access to the queue for log processing.
💬 Disposable field _error in type QueueLogHandler is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

xdm

2068 total diagnostics across 13 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 214 hits
📄 app\XDM\XDM.Core\Clients\Http\WinHttpSession.cs (line 27)
24 private string? transferEncoding;
25 private string? contentEncoding;
26 private string? contentDispositionFileName;
27 private DateTime lastModified = DateTime.Now;
28 private long rangeStart = -1, rangeEnd = -1;
29 private Dictionary<string, List<string>>? headers = null;
30 private string? cookies = null;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 app\XDM\XDM.Core\TraceLog\Log.cs (line 26)
23
24 public static void Debug(object obj, string message)
25 {
26 Trace.WriteLine($"[xdm-{DateTime.Now.ToLongTimeString()}] {message} : {obj}");
27 //Trace.Flush();
28 }
29
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 122 hits
📄 app\XDM\XDM.Core\Util\FormattingHelper.cs (line 14)
11 public static string ToHMS(long sec)
12 {
13 long hrs = 0, min = 0;
14 hrs = sec / 3600;
15 min = (sec % 3600) / 60;
16 sec = sec % 60;
17 var str = hrs.ToString().PadLeft(2, '0') + ":" + min.ToString().PadLeft(2, '0') + ":" + sec.ToString().PadLeft(2, '0');
💬 The operands in the divisive expression sec / 3600 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 app\XDM\XDM.Core\Util\FormattingHelper.cs (line 15)
12 {
13 long hrs = 0, min = 0;
14 hrs = sec / 3600;
15 min = (sec % 3600) / 60;
16 sec = sec % 60;
17 var str = hrs.ToString().PadLeft(2, '0') + ":" + min.ToString().PadLeft(2, '0') + ":" + sec.ToString().PadLeft(2, '0');
18 return str;
💬 The operands in the divisive expression (sec % 3600) / 60 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 app\XDM\XDM.Core\Clients\Http\NetFxHttpClient.cs (line 48)
45 {
46 if (sp != null)
47 {
48 servicePoints.Add(sp);
49 }
50 }
51 return http;
💬 Type ServicePoint is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 app\XDM\XDM.Core\Clients\Http\NetFxHttpClient.cs (line 148)
145 var servicePoint = r.ServicePoint;
146 if (servicePoint != null)
147 {
148 servicePoints.Add(servicePoint);
149 }
150 session.Response = response;
151 return new HttpResponse { Session = session };
💬 Type ServicePoint is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS011 OnPropertyChanged without nameof operator 68 hits
📄 app\XDM\XDM.Wpf.UI\MainWindow\FinishedDownloadEntryWrapper.cs (line 25)
22 set
23 {
24 entry.Name = value;
25 OnPropertyChanged("Name");
26 }
27 }
28
💬 OnPropertyChanged(Name) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
📄 app\XDM\XDM.Wpf.UI\MainWindow\FinishedDownloadEntryWrapper.cs (line 35)
32 set
33 {
34 entry.Size = value;
35 OnPropertyChanged("Size");
36 }
37 }
38
💬 OnPropertyChanged(Size) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 172 hits
📄 app\XDM\XDM.Core\YDLWrapper\YtBinary.cs (line 7)
4
5namespace YDLWrapper
6{
7 public struct YtBinary
8 {
9 public YtBinaryType BinaryType { get; set; }
10 public string Path { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct YtBinary. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 app\XDM\XDM.Core\YDLWrapper\Structs.cs (line 75)
72 }
73 }
74
75 public struct YDLPlaylist
76 {
77 public YDLFormatList[] Entries { get; set; }
78 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct YDLPlaylist. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 54 hits
📄 app\XDM\XDM.Core\Util\BrowserLauncher.cs (line 46)
43
44 public static bool LaunchBrowser(Browser browser, string args, string? executableLocation)
45 {
46 switch (browser)
47 {
48 case Browser.Chrome:
49 return LaunchGoogleChrome(args, executableLocation);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 app\XDM\XDM.Core\Util\PlatformHelper.cs (line 90)
87 public static void OpenBrowser(string url)
88 {
89 var os = Environment.OSVersion.Platform;
90 switch (os)
91 {
92 case PlatformID.Win32NT:
93 var psiShellEx = new ProcessStartInfo
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 90 hits
📄 app\XDM\XDM.Core\Util\BrowserLauncher.cs (line 46)
43
44 public static bool LaunchBrowser(Browser browser, string args, string? executableLocation)
45 {
46 switch (browser)
47 {
48 case Browser.Chrome:
49 return LaunchGoogleChrome(args, executableLocation);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 app\XDM\XDM.Core\ApplicationCore.cs (line 656)
653 public string? GetPrimaryUrl(DownloadItemBase entry)
654 {
655 if (entry == null) return null;
656 switch (entry.DownloadType)
657 {
658 case "Http":
659 var h1 = RequestDataIO.LoadSingleSourceHTTPDownloadInfo(entry.Id);// LoadInfo<SingleSourceHTTPDownloadInfo>(entry.Id);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 42 hits
📄 app\XDM\XDM.Core\ApplicationContext.cs (line 31)
28 {
29 if (!s_Init)
30 {
31 throw new Exception("ApplicationContext is not initialized...");
32 }
33 return s_ApplicationCore!;
34 }
💬 An exception is thrown from the getter of property CoreService (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 app\XDM\XDM.Core\ApplicationContext.cs (line 43)
40 {
41 if (!s_Init)
42 {
43 throw new Exception("ApplicationContext is not initialized...");
44 }
45 return s_IApplication!;
46 }
💬 An exception is thrown from the getter of property Application (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS034 Accessing Task.Result without await 4 hits
📄 app\XDM\XDM.Core\Clients\Http\DotNetHttpSession.cs (line 68)
65
66 public Stream GetResponseStream()
67 {
68 return Response!.Content.ReadAsStreamAsync(this.CancellationToken).Result;
69 }
70
71 public string? ReadAsString(CancelFlag cancellationToken)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 app\XDM\XDM.Core\Clients\Http\DotNetHttpSession.cs (line 73)
70
71 public string? ReadAsString(CancelFlag cancellationToken)
72 {
73 return Response?.Content.ReadAsStringAsync(this.CancellationToken).Result;
74 }
75
76 public void EnsureSuccessStatusCode()
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS048 Locking on discouraged object (string, Type, this) 196 hits
📄 app\XDM\XDM.Core\Clients\Http\WinHttpSession.cs (line 130)
127
128 public void Close()
129 {
130 lock (this)
131 {
132 this.RequestHandle.Close();
133 this.ConnectHandle.Close();
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 app\XDM\XDM.Core\BrowserMonitoring\VideoTracker.cs (line 132)
129
130 public List<MediaInfo> GetVideoList()
131 {
132 lock (this)
133 {
134 var list = new List<MediaInfo>();
135 foreach (var e in ytVideoList)
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 12 hits
📄 app\XDM\XDM.Core\UI\LinkRefreshDialogUIController.cs (line 79)
76 private static string GetReferer(Dictionary<string, List<string>> headers)
77 {
78 return headers?.Where(
79 header => header.Key.ToLowerInvariant() == "referer")
80 .FirstOrDefault().Value?.FirstOrDefault();
81 }
82
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 app\XDM\XDM.Core\BrowserMonitoring\VideoUrlHelper.cs (line 838)
835 foreach (var header in message.RequestHeaders)
836 {
837 headers[header.Key] = header.Value;
838 if (header.Key.ToLowerInvariant() == "accept")
839 {
840 acceptHeaderAdded = true;
841 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 132 hits
📄 app\XDM\XDM.Core\Clients\Http\NetFxHttpClient.cs (line 44)
41
42 http.ConnectionGroupName = this.connectionGroupName;
43 var sp = http.ServicePoint;
44 lock (servicePoints)
45 {
46 if (sp != null)
47 {
💬 A lock was obtained on servicePoints but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 app\XDM\XDM.Core\Clients\Http\WinHttpResponseStream.cs (line 37)
34
35 public override int Read(byte[] buffer, int offset, int count)
36 {
37 lock (hRequest)
38 {
39 var pData = Marshal.AllocHGlobal(count);
40 try
💬 A lock was obtained on hRequest but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS066 Disposable field is not disposed 950 hits
📄 app\XDM\XDM.WinForms.IntegrationUI\Form1.cs (line 17)
14{
15 public partial class Form1 : Form
16 {
17 private PrivateFontCollection fc;
18 private string folderPath;
19 private int index;
20 private string browser;
💬 Disposable field fc in type Form1 is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 app\XDM\XDM.Core\Scheduler.cs (line 12)
9{
10 public class Scheduler : IDisposable
11 {
12 private Timer? timer;
13 private HashSet<string> activeSchedules;
14 //private Action callback;
15
💬 Disposable field timer in type Scheduler is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

StockSharp

2048 total diagnostics across 18 rules

SS001 Async method with void return type 2 hits
📄 Connectors\Bittrex\Native\PusherClient.cs (line 83)
80 await handler(true, cancellationToken);
81 }
82
83 private async void Invoke(Channels channel, string tzip)
84 {
85 try
86 {
💬 Method Invoke is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Connectors\Bittrex\Native\PusherClient.cs (line 83)
80 await handler(true, cancellationToken);
81 }
82
83 private async void Invoke(Channels channel, string tzip)
84 {
85 try
86 {
💬 Method Invoke is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 52 hits
📄 Reporting\ExcelReportGenerator.cs (line 345)
342 worker
343 .SetCell(0, 4, LocalizedStrings.StartTime)
344 .SetCellColor(0, 4, labelBg, null)
345 .SetCell(1, 4, DateTime.Now)
346 .SetCellFormat(1, 4, "yyyy-MM-dd HH:mm:ss");
347
348 // Row 5: Net PnL
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Reporting\ExcelReportGenerator.cs (line 207)
204 worker
205 .SetCell(0, 2, LocalizedStrings.StartTime)
206 .SetCellColor(0, 2, labelBg, null)
207 .SetCell(1, 2, DateTime.Now)
208 .SetCellFormat(1, 2, "yyyy-MM-dd HH:mm:ss");
209
210 // Row 3: Symbol
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 74 hits
📄 Messages\Extensions.cs (line 4400)
4397
4398 if (period == null || period.Times.IsEmpty())
4399 {
4400 return (to - from).Ticks / timeFrame.Ticks;
4401 }
4402
4403 if (days == 0)
💬 The operands in the divisive expression (to - from).Ticks / timeFrame.Ticks are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Messages\Extensions.cs (line 4415)
4412 return totalCount;
4413
4414 var fullDayLength = period.Times.Sum(r => r.Length.Ticks);
4415 totalCount += TimeSpan.FromTicks((days - 1) * fullDayLength).Ticks / timeFrame.Ticks;
4416
4417 return totalCount;
4418 }
💬 The operands in the divisive expression TimeSpan.FromTicks((days - 1) * fullDayLength).Ticks / timeFrame.Ticks are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 114 hits
📄 BusinessEntities\EntitiesExtensions.cs (line 2123)
2120 return [.. securities.TryLimitByCount(criteria)];
2121
2122 var dict = securities.ToDictionary(s => s.ToMessage(), s => s);
2123 return [.. dict.Keys.Filter(criteria).TryLimitByCount(criteria).Select(m => dict[m])];
2124 }
2125
2126 /// <summary>
💬 Type SecurityMessage is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Algo\CollectionSecurityProvider.cs (line 117)
114 continue;
115
116 added ??= [];
117 added.Add(security);
118 }
119
120 if (added is { Count: > 0 })
💬 Type Security is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 14 hits
📄 Messages\MessageTypes.cs (line 452)
449/// <summary>
450/// Extended info for <see cref="MessageTypes"/>.
451/// </summary>
452public class MessageTypeInfo : Equatable<MessageTypeInfo>
453{
454 /// <summary>
455 /// Message type.
💬 Equals() and GetHashcode() must be implemented together on MessageTypeInfo (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 Messages\DataType.cs (line 8)
5/// </summary>
6[DataContract]
7[Serializable]
8public class DataType : Equatable<DataType>, IPersistable
9{
10 /// <summary>
11 /// Initializes a new instance of the <see cref="DataType"/>.
💬 Equals() and GetHashcode() must be implemented together on DataType (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 24 hits
📄 Messages\CandleMessage.cs (line 584)
581 /// <returns>A hash code.</returns>
582 public override int GetHashCode()
583 {
584 return BoxSize.GetHashCode() ^ ReversalAmount.GetHashCode();
585 }
586}
587
💬 GetHashCode() refers to mutable property BoxSize (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Messages\CandleMessage.cs (line 584)
581 /// <returns>A hash code.</returns>
582 public override int GetHashCode()
583 {
584 return BoxSize.GetHashCode() ^ ReversalAmount.GetHashCode();
585 }
586}
587
💬 GetHashCode() refers to mutable property ReversalAmount (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 450 hits
📄 Messages\QuoteChange.cs (line 63)
60/// <param name="condition">Quote condition.</param>
61[DataContract]
62[Serializable]
63public struct QuoteChange(decimal price, decimal volume, int? ordersCount = null, QuoteConditions condition = default)
64{
65
66 /// <summary>
💬 Implement Equals(), GetHashCode() and ToString() methods on struct QuoteChange. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Messages\CandlePriceLevel.cs (line 8)
5/// </summary>
6[DataContract]
7[Serializable]
8public struct CandlePriceLevel// : ICloneable<CandlePriceLevel>
9{
10 /// <summary>
11 /// Price.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CandlePriceLevel. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 130 hits
📄 Messages\MessageAdapter.cs (line 394)
391
392 if (IsAutoReplyOnTransactonalUnsubscription)
393 {
394 switch (message.Type)
395 {
396 case MessageTypes.PortfolioLookup:
397 case MessageTypes.OrderStatus:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 BusinessEntities\EntitiesExtensions.cs (line 1374)
1371 {
1372 try
1373 {
1374 switch (change.Key)
1375 {
1376 case PositionChangeTypes.BeginValue:
1377 position.BeginValue = (decimal)change.Value;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 220 hits
📄 Messages\SubscriptionBase.cs (line 125)
122 if (security == null)
123 return;
124
125 switch (subscriptionMessage)
126 {
127 case MarketDataMessage mdMsg:
128 security.CopyTo(mdMsg, false);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Messages\OrderBookIncrementBuilder.cs (line 70)
67
68 bool CheckSwitch()
69 {
70 switch (currState)
71 {
72 case _none:
73 case QuoteChangeStates.SnapshotStarted:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 10 hits
📄 Algo\Derivatives\BasketBlackScholes.cs (line 102)
99 var model = _innerModels.SyncGet(c => c.FirstOrDefault());
100
101 if (model == null)
102 throw new InvalidOperationException(LocalizedStrings.ModelNoOptions);
103
104 base.UnderlyingAsset = model.UnderlyingAsset;
105 }
💬 An exception is thrown from the getter of property UnderlyingAsset (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Algo.Testing\Generation\MarketDataGenerator.cs (line 172)
169 get
170 {
171 if (_volumes == null)
172 throw new InvalidOperationException(LocalizedStrings.GeneratorNotInitialized);
173
174 return _volumes;
175 }
💬 An exception is thrown from the getter of property Volumes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 180 hits
📄 Messages\AsyncMessageChannel.cs (line 316)
313 if (_subscriptionItems.TryGetAndRemove(subMsg.OriginalTransactionId, out var subItem))
314 {
315 subItem.UnsubscribeRequest = subMsg.TransactionId;
316 subItem.Cts.Cancel();
317
318 done();
319 return;
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Messages\AsyncMessageChannel.cs (line 517)
514 {
515 var item = kv.Value;
516
517 item.Cts.Cancel();
518 item.Cts.Dispose();
519 }
520
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 2 hits
📄 Tests\CompilationTests.cs (line 90)
87 {
88 var context = compiler.CreateContext();
89
90 var res = compiler.Compile(
91 scriptName,
92 sources,
93 refs,
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Tests\CompilationTests.cs (line 90)
87 {
88 var context = compiler.CreateContext();
89
90 var res = compiler.Compile(
91 scriptName,
92 sources,
93 refs,
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 2 hits
📄 Tests\CompilationTests.cs (line 109)
106 script.AssertNotNull();
107
108 // Test script execution with mock data
109 RunAnalyticsScript(script, securities, from, to, storageRegistry, storageRegistry.DefaultDrive, format, timeFrame, token).Wait();
110 }
111 }
112 catch (Exception ex)
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 Tests\CompilationTests.cs (line 109)
106 script.AssertNotNull();
107
108 // Test script execution with mock data
109 RunAnalyticsScript(script, securities, from, to, storageRegistry, storageRegistry.DefaultDrive, format, timeFrame, token).Wait();
110 }
111 }
112 catch (Exception ex)
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS041 Unnecessary enumerable materialization 4 hits
📄 Algo\Candles\BiggerTimeFrameCandleCompressor.cs (line 98)
95 {
96 TimeFrameCandleMessage lastCandle = null;
97
98 foreach (var candle in _processParts.SelectMany(p => ProcessCandlePart(p, message)).ToArray().Cast<TimeFrameCandleMessage>())
99 {
100 if (candle != lastCandle)
101 {
💬 ToArray is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 Diagram.Core\Elements\LogicalConditionDiagramElement.cs (line 138)
135 minSockets = minSockets.Max(_loadedSockets.Count);
136
137 if (_loadedSockets.Count > 0)
138 InputSockets.ToArray().Where(s => !_loadedSockets.Contains(s.Id) && GetNumConnections(s) == 0).ForEach(RemoveSocket);
139
140 while (InputSockets.Count > maxSockets)
141 {
💬 ToArray is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 8 hits
📄 Localization\MediaIconAttribute.cs (line 8)
5/// <summary>
6/// Specify icon, located in S#.Media library.
7/// </summary>
8public class MediaIconAttribute : IconAttribute
9{
10 /// <summary>
11 /// Create <see cref="MediaIconAttribute"/>.
💬 MediaIconAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 Messages\XamlIconAttribute.cs (line 10)
7/// Initializes a new instance of the <see cref="XamlIconAttribute"/>.
8/// </remarks>
9/// <param name="icon">Icon.</param>
10public class XamlIconAttribute(string icon) : IconAttribute($"/StockSharp.Xaml;component/IconsSvg/{icon}.svg", true)
11{
12}
💬 XamlIconAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 2 hits
📄 Samples\10_CrossPlatform\01_ConsoleApp\Program.cs (line 102)
99 Console.Write("Do you want to buy 1? (Y/N)");
100
101 var str = Console.ReadLine();
102 if (str != null && str.ToUpper() != "Y") return;
103
104 var bestBidPrice = lastDepth?.GetBestBid()?.Price;
105
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Samples\10_CrossPlatform\01_ConsoleApp\Program.cs (line 102)
99 Console.Write("Do you want to buy 1? (Y/N)");
100
101 var str = Console.ReadLine();
102 if (str != null && str.ToUpper() != "Y") return;
103
104 var bestBidPrice = lastDepth?.GetBestBid()?.Price;
105
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS059 IAsyncDisposable not disposed asynchronously 188 hits
📄 Messages\IMessageAdapterAsyncExtensions.cs (line 24)
21 throw new ArgumentNullException(nameof(adapter));
22
23 var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
24 using var ctr = cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken));
25
26 ValueTask OnOut(Message msg, CancellationToken ct)
27 {
💬 CancellationTokenRegistration can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Messages\IMessageAdapterAsyncExtensions.cs (line 64)
61 throw new ArgumentNullException(nameof(adapter));
62
63 var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
64 using var ctr = cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken));
65
66 ValueTask OnOut(Message msg, CancellationToken ct)
67 {
💬 CancellationTokenRegistration can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 572 hits
📄 Messages\InMemoryMessageChannel.cs (line 11)
8 private readonly IMessageQueue _queue;
9 private readonly Action<Exception> _errorHandler;
10
11 private CancellationTokenSource _cancellationTokenSource;
12 private Task _processingTask;
13
14 /// <summary>
💬 Disposable field _cancellationTokenSource in type InMemoryMessageChannel is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Messages\InMemoryMessageChannel.cs (line 12)
9 private readonly Action<Exception> _errorHandler;
10
11 private CancellationTokenSource _cancellationTokenSource;
12 private Task _processingTask;
13
14 /// <summary>
15 /// Initializes a new instance of the <see cref="InMemoryMessageChannel"/>.
💬 Disposable field _processingTask in type InMemoryMessageChannel is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

R3

2014 total diagnostics across 13 rules

SS001 Async method with void return type 208 hits
📄 src\R3\AwaitOperation.cs (line 71)
68 protected abstract ValueTask OnNextAsync(T value, CancellationToken cancellationToken, bool configureAwait);
69 protected abstract void PublishOnCompleted(Result result);
70
71 async void RunQueueWorker() // don't(can't) wait so use async void
72 {
73 var reader = channel.Reader;
74 var token = cancellationTokenSource.Token;
💬 Method RunQueueWorker is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\R3\AwaitOperation.cs (line 161)
158 protected abstract ValueTask OnNextAsync(T value, CancellationToken cancellationToken, bool configureAwait);
159 protected abstract void PublishOnCompleted(Result result);
160
161 async void StartAsync(T value)
162 {
163 try
164 {
💬 Method StartAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 8 hits
📄 src\R3\ObservableTracker.cs (line 62)
59
60 var id = Interlocked.Increment(ref trackingIdCounter);
61 trackableDisposable = new TrackableDisposable(subscription, id);
62 tracking.TryAdd(trackableDisposable, new TrackingState(id, typeName, DateTime.Now, stackTrace)); // use local now.
63
64 return true;
65 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\R3\ObservableTracker.cs (line 62)
59
60 var id = Interlocked.Increment(ref trackingIdCounter);
61 trackableDisposable = new TrackableDisposable(subscription, id);
62 tracking.TryAdd(trackableDisposable, new TrackingState(id, typeName, DateTime.Now, stackTrace)); // use local now.
63
64 return true;
65 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 26 hits
📄 src\R3\CompositeDisposable.cs (line 90)
87 current[index] = null;
88
89 // Do shrink
90 if (current.Capacity > ShrinkThreshold && count < current.Capacity / 2)
91 {
92 var fresh = new List<IDisposable?>(current.Capacity / 2);
93
💬 The operands in the divisive expression current.Capacity / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\R3\CompositeDisposable.cs (line 92)
89 // Do shrink
90 if (current.Capacity > ShrinkThreshold && count < current.Capacity / 2)
91 {
92 var fresh = new List<IDisposable?>(current.Capacity / 2);
93
94 foreach (var d in current)
95 {
💬 The operands in the divisive expression current.Capacity / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 104 hits
📄 src\R3\Disposable.cs (line 418)
415 }
416}
417
418public ref struct DisposableBuilder()
419{
420 IDisposable? disposable1;
421 IDisposable? disposable2;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DisposableBuilder. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\R3\DisposableBag.cs (line 3)
1namespace R3;
2
3public struct DisposableBag : IDisposable
4{
5 IDisposable[]? items;
6 bool isDisposed;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DisposableBag. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 40 hits
📄 src\R3\Subject.cs (line 36)
33 Volatile.Write(ref error, result.Exception); // set failure immmediately(but not locked).
34 }
35
36 switch (field)
37 {
38 case NotCompleted:
39 return ResultStatus.Done;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\R3\Subject.cs (line 55)
52 public bool TrySetDisposed(out bool alreadyCompleted)
53 {
54 var field = Interlocked.Exchange(ref completeState, Disposed);
55 switch (field)
56 {
57 case NotCompleted:
58 alreadyCompleted = false;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS020 Test method without public modifier 4 hits
📄 tests\R3.Tests\OperatorTests\ToAsyncEnumerableTest.cs (line 6)
3public class ToAsyncEnumerableTest
4{
5 [Fact]
6 async Task Test()
7 {
8 var publisher = new Subject<int>();
9 var cts = new CancellationTokenSource();
💬 Test method "Test" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
📄 tests\R3.Tests\OperatorTests\ToAsyncEnumerableTest.cs (line 27)
24 }
25
26 [Fact]
27 async Task Cancel()
28 {
29 var publisher = new Subject<int>();
30 var cts = new CancellationTokenSource();
💬 Test method "Cancel" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
SS023 Exception thrown from property getter 8 hits
📄 src\R3\Collections\LiveList.cs (line 39)
36 {
37 lock (list)
38 {
39 if (!isCompleted) throw new InvalidOperationException("LiveList is not completed, you should check IsCompleted.");
40 return completedValue;
41 }
42 }
💬 An exception is thrown from the getter of property Result (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\R3\Collections\LiveList.cs (line 39)
36 {
37 lock (list)
38 {
39 if (!isCompleted) throw new InvalidOperationException("LiveList is not completed, you should check IsCompleted.");
40 return completedValue;
41 }
42 }
💬 An exception is thrown from the getter of property Result (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS032 Thread.Sleep used in async method 4 hits
📄 tests\R3.Tests\OperatorTests\SelectAwaitTest.cs (line 174)
171 liveList.AssertEqual([]);
172
173 timeProvider.Advance(1);
174 Thread.Sleep(100);
175 liveList.AssertEqual([100]);
176
177 timeProvider.Advance(2);
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 tests\R3.Tests\OperatorTests\SelectAwaitTest.cs (line 178)
175 liveList.AssertEqual([100]);
176
177 timeProvider.Advance(2);
178 Thread.Sleep(100);
179 liveList.AssertEqual([100]);
180
181 subject.OnNext(3);
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 18 hits
📄 sandbox\ReferenceBuilder\Program.cs (line 10)
7// Get absolute path of bin/Debug/TargetFramework/ReferenceBuilder.dll
8// Location = /Foo/Bar/R3/sandbox/ReferenceBuilder/bin/Debug/net8.0/ReferenceBuilder.dll
9var basePath = Assembly.GetAssembly(typeof(Program))!.Location;
10File.WriteAllText(Path.Combine(basePath, "../../../../../../docs/reference_factory.md"), f);
11File.WriteAllText(Path.Combine(basePath, "../../../../../../docs/reference_operator.md"), o);
12
13// replace readme
💬 Async overload available for File.WriteAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 sandbox\ReferenceBuilder\Program.cs (line 11)
8// Location = /Foo/Bar/R3/sandbox/ReferenceBuilder/bin/Debug/net8.0/ReferenceBuilder.dll
9var basePath = Assembly.GetAssembly(typeof(Program))!.Location;
10File.WriteAllText(Path.Combine(basePath, "../../../../../../docs/reference_factory.md"), f);
11File.WriteAllText(Path.Combine(basePath, "../../../../../../docs/reference_operator.md"), o);
12
13// replace readme
14var text = File.ReadAllLines(Path.Combine(basePath, "../../../../../../README.md"));
💬 Async overload available for File.WriteAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 4 hits
📄 src\R3\Internal\Shims\TaskExtensions.cs (line 25)
22 }
23 else
24 {
25 tcs.TrySetResult(t.Result);
26 }
27 }, TaskScheduler.Default);
28
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\R3\Internal\Shims\TaskExtensions.cs (line 25)
22 }
23 else
24 {
25 tcs.TrySetResult(t.Result);
26 }
27 }, TaskScheduler.Default);
28
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS048 Locking on discouraged object (string, Type, this) 104 hits
📄 src\R3\SynchronizedReactiveProperty.cs (line 24)
21 {
22 get
23 {
24 lock (this)
25 {
26 return base.Value;
27 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 src\R3\SynchronizedReactiveProperty.cs (line 31)
28 }
29 set
30 {
31 lock (this)
32 {
33 base.Value = value;
34 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS051 Locking on mutable reference 80 hits
📄 src\R3\Operators\TakeLast.cs (line 50)
47
48 protected override void OnNextCore(T value)
49 {
50 lock (queue)
51 {
52 if (takeCompleted) return;
53
💬 A lock was obtained on queue but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\R3\Operators\TakeLast.cs (line 75)
72 return;
73 }
74
75 lock (queue)
76 {
77 takeCompleted = true;
78
💬 A lock was obtained on queue but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS066 Disposable field is not disposed 1406 hits
📄 src\R3\Operators\ZipLatest.cs (line 366)
363
364 sealed class _ZipLatest : IDisposable
365 {
366 readonly Observer<TResult> observer;
367 readonly Observable<T1> source1;
368 readonly Observable<T2> source2;
369 readonly Observable<T3> source3;
💬 Disposable field observer in type _ZipLatest is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\R3\Operators\ZipLatest.cs (line 236)
233
234 sealed class _ZipLatest : IDisposable
235 {
236 readonly Observer<TResult> observer;
237 readonly Observable<T1> source1;
238 readonly Observable<T2> source2;
239 readonly Func<T1, T2, TResult> resultSelector;
💬 Disposable field observer in type _ZipLatest is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

LibreHardwareMonitor

1974 total diagnostics across 10 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 44 hits
📄 Aga.Controls\Tree\IncrementalSearch.cs (line 18)
15 private TreeViewAdv _tree;
16 private TreeNodeAdv _currentNode;
17 private string _searchString = "";
18 private DateTime _lastKeyPressed = DateTime.Now;
19
20 public IncrementalSearch(TreeViewAdv tree)
21 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Aga.Controls\Tree\IncrementalSearch.cs (line 30)
27 if (!Char.IsControl(value))
28 {
29 Char ch = Char.ToLowerInvariant(value);
30 DateTime dt = DateTime.Now;
31 TimeSpan ts = dt - _lastKeyPressed;
32 _lastKeyPressed = dt;
33 if (ts.TotalMilliseconds < SearchTimeout)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 254 hits
📄 Aga.Controls\Tree\FixedRowHeightLayout.cs (line 34)
31 {
32 get
33 {
34 return Math.Max((_treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight) / _rowHeight, 0);
35 }
36 }
37
💬 The operands in the divisive expression (_treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight) / _rowHeight are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Aga.Controls\Tree\FixedRowHeightLayout.cs (line 49)
46 public int GetRowAt(Point point)
47 {
48 point = new Point(point.X, point.Y + (_treeView.FirstVisibleRow * _rowHeight) - _treeView.ColumnHeaderHeight);
49 return point.Y / _rowHeight;
50 }
51
52 public int GetFirstRow(int lastPageRow)
💬 The operands in the divisive expression point.Y / _rowHeight are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 8 hits
📄 Aga.Controls\Threading\AbortableThreadPool.cs (line 48)
45 }
46 if (item == null)
47 return;
48 _threads.Add(item, Thread.CurrentThread);
49
50 }
51 ExecutionContext.Run(item.Context,
💬 Type WorkItem is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Aga.Controls\Threading\AbortableThreadPool.cs (line 89)
86 _callbacks.Remove(node);
87 return WorkItemStatus.Queued;
88 }
89 else if (_threads.ContainsKey(item))
90 {
91 if (allowAbort)
92 {
💬 Type WorkItem is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 904 hits
📄 Aga.Controls\BitmapHelper.cs (line 13)
10 public static class BitmapHelper
11 {
12 [StructLayout(LayoutKind.Sequential)]
13 private struct PixelData
14 {
15 public byte B;
16 public byte G;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PixelData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Aga.Controls\Tree\DropPosition.cs (line 7)
4
5namespace Aga.Controls.Tree
6{
7 public struct DropPosition
8 {
9 private TreeNodeAdv _node;
10 public TreeNodeAdv Node
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DropPosition. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 94 hits
📄 Aga.Controls\Tree\Input\NormalInputState.cs (line 23)
20
21 if (Tree.CurrentNode != null)
22 {
23 switch (args.KeyCode)
24 {
25 case Keys.Right:
26 if (!Tree.CurrentNode.IsExpanded)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Aga.Controls\Tree\TreeViewAdv.cs (line 562)
559 get
560 {
561 CreateParams res = base.CreateParams;
562 switch (BorderStyle)
563 {
564 case BorderStyle.FixedSingle:
565 res.Style |= 0x800000;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 588 hits
📄 Aga.Controls\NumericTextBox.cs (line 100)
97 protected override void WndProc(ref Message m)
98 {
99 // Switch to handle message...
100 switch (m.Msg)
101 {
102 case WM_PASTE:
103 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Aga.Controls\GifDecoder.cs (line 265)
262 if (iline >= ih)
263 {
264 pass++;
265 switch (pass)
266 {
267 case 2 :
268 iline = 4;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 10 hits
📄 LibreHardwareMonitorLib\Hardware\Computer.cs (line 321)
318 get
319 {
320 if (!_open)
321 throw new InvalidOperationException("SMBIOS cannot be accessed before opening.");
322
323 return _smbios;
324 }
💬 An exception is thrown from the getter of property SMBios (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 LibreHardwareMonitorLib\Hardware\Computer.cs (line 321)
318 get
319 {
320 if (!_open)
321 throw new InvalidOperationException("SMBIOS cannot be accessed before opening.");
322
323 return _smbios;
324 }
💬 An exception is thrown from the getter of property SMBios (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS051 Locking on mutable reference 20 hits
📄 Aga.Controls\PerformanceAnalyzer.cs (line 80)
77 [Conditional("DEBUG")]
78 public static void Finish(string pieceOfCode)
79 {
80 lock (_performances)
81 {
82 if (_performances.ContainsKey(pieceOfCode))
83 {
💬 A lock was obtained on _performances but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Aga.Controls\PerformanceAnalyzer.cs (line 62)
59 public static void Start(string pieceOfCode)
60 {
61 PerformanceInfo info = null;
62 lock(_performances)
63 {
64 if (_performances.ContainsKey(pieceOfCode))
65 info = _performances[pieceOfCode];
💬 A lock was obtained on _performances but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 14 hits
📄 Aga.Controls\GifDecoder.cs (line 652)
649 String app = "";
650 for (int i = 0; i < 11; i++)
651 {
652 app += (char) block[i];
653 }
654 if (app.Equals("NETSCAPE2.0"))
655 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Aga.Controls\GifDecoder.cs (line 708)
705 String id = "";
706 for (int i = 0; i < 6; i++)
707 {
708 id += (char) Read();
709 }
710 if (!id.StartsWith("GIF"))
711 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 38 hits
📄 Aga.Controls\Tree\TreeViewAdv.cs (line 45)
42 private bool _suspendUpdate;
43 private bool _needFullUpdate;
44 private bool _fireSelectionEvent;
45 private NodePlusMinus _plusMinus;
46 private ToolTip _toolTip;
47 private DrawContext _measureContext;
48 private TreeColumn _hotColumn;
💬 Disposable field _plusMinus in type TreeViewAdv is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Aga.Controls\Tree\TreeViewAdv.cs (line 46)
43 private bool _needFullUpdate;
44 private bool _fireSelectionEvent;
45 private NodePlusMinus _plusMinus;
46 private ToolTip _toolTip;
47 private DrawContext _measureContext;
48 private TreeColumn _hotColumn;
49 private IncrementalSearch _search;
💬 Disposable field _toolTip in type TreeViewAdv is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

FASTER

1924 total diagnostics across 12 rules

SS003 Integer divided by integer causing implicit rounding 448 hits
📄 cs\src\core\Index\Common\AddressInfo.cs (line 19)
16 {
17 private const int kMultiplierBits = 1;
18 private static readonly int kTotalBits = sizeof(IntPtr) * 8;
19 private static readonly int kAddressBits = 42*kTotalBits/64;
20 private static readonly int kSizeBits = kTotalBits - kAddressBits - kMultiplierBits;
21 private static readonly long kSizeMaskInWord = ((1L << kSizeBits) - 1) << kAddressBits;
22 private static readonly long kSizeMaskInInteger = (1L << kSizeBits) - 1;
💬 The operands in the divisive expression 42*kTotalBits/64 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 cs\src\core\Allocator\GenericFrame.cs (line 29)
26 {
27 Record<Key, Value>[] tmp;
28 if (pageSize % recordSize == 0)
29 tmp = new Record<Key, Value>[pageSize / recordSize];
30 else
31 tmp = new Record<Key, Value>[1 + (pageSize / recordSize)];
32 Array.Clear(tmp, 0, tmp.Length);
💬 The operands in the divisive expression pageSize / recordSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 16 hits
📄 cs\src\core\Epochs\EpochProtectedVersionScheme.cs (line 125)
122 /// <inheritdoc/>
123 public override int GetHashCode()
124 {
125 return Word.GetHashCode();
126 }
127
128 /// <summary>
💬 GetHashCode() refers to mutable field Word (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 cs\src\core\Index\Synchronization\StateTransitions.cs (line 184)
181 /// <inheritdoc/>
182 public override int GetHashCode()
183 {
184 return Word.GetHashCode();
185 }
186
187 /// <summary>
💬 GetHashCode() refers to mutable field Word (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 712 hits
📄 cs\src\core\Compaction\ICompactionFunctions.cs (line 28)
25 bool IsDeleted(ref Key key, ref Value value);
26 }
27
28 internal struct DefaultCompactionFunctions<Key, Value> : ICompactionFunctions<Key, Value>
29 {
30 public bool IsDeleted(ref Key key, ref Value value) => false;
31 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DefaultCompactionFunctions. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 cs\src\core\Allocator\AllocatorBase.cs (line 21)
18 internal enum PMMCloseStatus : int { Closed, Open };
19
20 [StructLayout(LayoutKind.Explicit)]
21 internal struct FullPageStatus
22 {
23 [FieldOffset(0)]
24 public long LastFlushedUntilAddress;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FullPageStatus. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 48 hits
📄 cs\src\core\Index\Synchronization\VersionChangeStateMachine.cs (line 41)
38 CancellationToken token = default)
39 where FasterSession : IFasterSession
40 {
41 switch (current.Phase)
42 {
43 case Phase.PREPARE:
44 if (ctx is not null)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 cs\src\core\Index\Synchronization\IndexSnapshotStateMachine.cs (line 21)
18 SystemState next,
19 FasterKV<Key, Value> faster)
20 {
21 switch (next.Phase)
22 {
23 case Phase.PREP_INDEX_CHECKPOINT:
24 if (faster._indexCheckpoint.IsDefault())
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 48 hits
📄 cs\src\core\Index\Synchronization\VersionChangeStateMachine.cs (line 41)
38 CancellationToken token = default)
39 where FasterSession : IFasterSession
40 {
41 switch (current.Phase)
42 {
43 case Phase.PREPARE:
44 if (ctx is not null)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 cs\src\core\Index\Synchronization\IndexSnapshotStateMachine.cs (line 21)
18 SystemState next,
19 FasterKV<Key, Value> faster)
20 {
21 switch (next.Phase)
22 {
23 case Phase.PREP_INDEX_CHECKPOINT:
24 if (faster._indexCheckpoint.IsDefault())
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 16 hits
📄 cs\src\core\ClientSession\ClientSession.cs (line 257)
254 get
255 {
256 if (!this.fht.LockTable.IsEnabled)
257 throw new FasterException($"LockableContext requires {nameof(ConcurrencyControlMode.LockTable)}");
258 return lContext;
259 }
260 }
💬 An exception is thrown from the getter of property LockableContext (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 cs\src\core\ClientSession\ClientSession.cs (line 244)
241 get
242 {
243 if (!this.fht.LockTable.IsEnabled)
244 throw new FasterException($"LockableUnsafeContext requires {nameof(ConcurrencyControlMode.LockTable)}");
245 return luContext;
246 }
247 }
💬 An exception is thrown from the getter of property LockableUnsafeContext (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS048 Locking on discouraged object (string, Type, this) 40 hits
📄 cs\src\core\Allocator\AllocatorBase.cs (line 1221)
1218 if (value < 0) return;
1219
1220 int oldEPC;
1221 lock (this) // linearize all setters of EmptyPageCount
1222 {
1223 oldEPC = emptyPageCount;
1224 emptyPageCount = value;
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 cs\src\core\Device\ManagedLocalStorageDevice.cs (line 163)
160 }
161
162 // FileStream.ReadAsync is not thread-safe hence need a lock here
163 lock (this)
164 {
165 readTask = logReadHandle.ReadAsync(umm.Memory).AsTask();
166 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS051 Locking on mutable reference 72 hits
📄 cs\src\core\Allocator\ErrorList.cs (line 18)
15
16 public void Add(CommitInfo info)
17 {
18 lock (errorList)
19 errorList.Add(info);
20 }
21
💬 A lock was obtained on errorList but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 cs\src\core\Allocator\ErrorList.cs (line 24)
21
22 public CommitInfo GetEarliestError()
23 {
24 lock (errorList)
25 {
26 var result = new CommitInfo {FromAddress = long.MaxValue};
27 var index = -1;
💬 A lock was obtained on errorList but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 24 hits
📄 cs\src\core\Index\FASTER\FASTER.cs (line 911)
908
909 foreach (var kvp in histogram.OrderBy(e => e.Key))
910 {
911 distribution += $" {kvp.Key} : {kvp.Value}\n";
912 }
913
914 return distribution;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 cs\src\core\Index\Recovery\DirectoryConfiguration.cs (line 129)
126 {
127 if (i == paths.Length - 1 && paths[i].Contains("."))
128 {
129 fullPath += paths[i];
130 }
131 else
132 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 12 hits
📄 cs\src\core\Allocator\MallocFixedPageSize.cs (line 42)
39 internal void Wait() => this.syncEvent.Wait();
40 internal async ValueTask WaitAsync(CancellationToken cancellationToken)
41 {
42 using var reg = cancellationToken.Register(() => this.asyncTcs.TrySetCanceled());
43 await this.asyncTcs.Task.ConfigureAwait(false);
44 }
45
💬 CancellationTokenRegistration can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 cs\src\core\Utilities\AsyncCountDown.cs (line 66)
63 if (counter == 0 || !GetOrCreateTaskCompletionSource(out var tcsOut))
64 return;
65
66 using var reg = cancellationToken.Register(() => tcsOut.TrySetCanceled());
67 await tcsOut.Task.WithCancellationAsync(cancellationToken).ConfigureAwait(false);
68 }
69
💬 CancellationTokenRegistration can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 8 hits
📄 cs\src\core\FasterLog\FasterLogRecoveryInfo.cs (line 228)
225 {
226 Iterators = new Dictionary<string, long>();
227
228 if (persistedIterators.Count > 0)
229 {
230 foreach (var kvp in persistedIterators)
231 {
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 cs\src\core\FasterLog\FasterLogRecoveryInfo.cs (line 228)
225 {
226 Iterators = new Dictionary<string, long>();
227
228 if (persistedIterators.Count > 0)
229 {
230 foreach (var kvp in persistedIterators)
231 {
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
SS066 Disposable field is not disposed 480 hits
📄 cs\src\core\FasterLog\FasterLogIterator.cs (line 22)
19 public sealed class FasterLogScanIterator : ScanIteratorBase, IDisposable
20 {
21 private readonly string name;
22 private readonly FasterLog fasterLog;
23 private readonly BlittableAllocator<Empty, byte> allocator;
24 private readonly BlittableFrame frame;
25 private readonly GetMemory getMemory;
💬 Disposable field fasterLog in type FasterLogScanIterator is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 cs\src\core\FasterLog\FasterLogIterator.cs (line 23)
20 {
21 private readonly string name;
22 private readonly FasterLog fasterLog;
23 private readonly BlittableAllocator<Empty, byte> allocator;
24 private readonly BlittableFrame frame;
25 private readonly GetMemory getMemory;
26 private readonly int headerSize;
💬 Disposable field allocator in type FasterLogScanIterator is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

NanUI

1914 total diagnostics across 10 rules

SS001 Async method with void return type 20 hits
📄 src\Sources\Browser\WebView\Components\ContextMenu\AnimatedContextMenuStrip.cs (line 51)
48 }
49
50
51 async void FadeOut()
52 {
53 if (InvokeRequired)
54 {
💬 Method FadeOut is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Sources\Formium\Formium.Members.cs (line 521)
518 OnClosed();
519 }
520
521 private async void CreateBrowserMessageInterceptor()
522 {
523 var retval = await BrowserRenderWidgetHostMessageInterceptor.Setup(_browserRenderWidgetMessageInterceptor, this, BrowserWndProcCore);
524
💬 Method CreateBrowserMessageInterceptor is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 70 hits
📄 src\Sources\Logging\NanUILogger.cs (line 139)
136 Directory.CreateDirectory(backupPath);
137 }
138
139 string? backupFile = $"{_backupFilename}_{DateTime.Now:yyyyMMdd}_{i}.backup";
140 var possibleFilePath = Path.Combine(backupPath, backupFile);
141 if (!File.Exists(possibleFilePath))
142 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Sources\Logging\LogEntry.cs (line 81)
78 _ => "[UNKNOWN LEVEL]",
79 };
80 string datetimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
81 return $"{DateTime.Now.ToString(datetimeFormat)} {levelText} {formattedMessage}";
82 }
83}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 280 hits
📄 src\Sources\Logging\NanUILogger.cs (line 116)
113 }
114
115 var fileInfo = new FileInfo(_filename);
116 if (fileInfo.Exists && ((fileInfo.Length / 1024) >= _maxSizeInKiloBytes))
117 {
118 CreateCopyOfCurrentLogFile(_filename);
119 }
💬 The operands in the divisive expression fileInfo.Length / 1024 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Sources\Formium\OffscreenImeHandler.cs (line 241)
238 {
239 var clauseSize = ImeNative.ImmGetCompositionString(imc, ImeNative.GCS_COMPCLAUSE, null, 0);
240
241 var clauseLength = (int)clauseSize / sizeof(int);
242
243 var result = new List<CefCompositionUnderline>();
244
💬 The operands in the divisive expression (int)clauseSize / sizeof(int) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 40 hits
📄 src\Sources\JavaScript\JavaScriptEngine\JavaScriptValue.cs (line 169)
166 break;
167 case JavaScriptValueType.Function:
168 ValueType = JavaScriptValueType.Function;
169 JAVASCRIPT_VALUE_COLLECTION.Add(this);
170 break;
171 case JavaScriptValueType.Property:
172 ValueType = JavaScriptValueType.Property;
💬 Type JavaScriptValue is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Sources\JavaScript\JavaScriptEngine\JavaScriptValue.cs (line 173)
170 break;
171 case JavaScriptValueType.Property:
172 ValueType = JavaScriptValueType.Property;
173 JAVASCRIPT_VALUE_COLLECTION.Add(this);
174 break;
175 }
176
💬 Type JavaScriptValue is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 560 hits
📄 src\Sources\Formium\OffscreenImeHandler.cs (line 49)
46 internal const uint IACE_IGNORENOCONTEXT = 0x0020;
47
48 [StructLayout(LayoutKind.Sequential)]
49 public struct POINT
50 {
51 public int X;
52 public int Y;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct POINT. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Sources\Formium\Forms\base\Forms\WindowBase\FramelessWindowBase.cs (line 14)
11
12namespace NetDimension.NanUI.Forms;
13[StructLayout(LayoutKind.Sequential)]
14internal struct NCCALCSIZE_PARAMS
15{
16 public RECT rgrc0, rgrc1, rgrc2;
17 public WINDOWPOS lppos;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NCCALCSIZE_PARAMS. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 140 hits
📄 src\Sources\WebResource\base\ResourceHandler.cs (line 176)
173
174 //var size = (int)item.BytesCount;
175
176 switch (item.ElementType)
177 {
178 case CefPostDataElementType.Bytes:
179 postData.AddRange(buffer);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Sources\Formium\Forms\TransparencyForm\LayeredWindow.cs (line 99)
96 {
97 var msg = (WindowMessage)m.Msg;
98
99 switch (msg)
100 {
101 case WindowMessage.WM_MOUSEMOVE:
102 return BrowserWmMouseMove(ref m);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 230 hits
📄 src\Sources\WebResource\base\ResourceHandler.cs (line 176)
173
174 //var size = (int)item.BytesCount;
175
176 switch (item.ElementType)
177 {
178 case CefPostDataElementType.Bytes:
179 postData.AddRange(buffer);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Sources\Formium\Forms\TransparencyForm\LayeredWindow.cs (line 99)
96 {
97 var msg = (WindowMessage)m.Msg;
98
99 switch (msg)
100 {
101 case WindowMessage.WM_MOUSEMOVE:
102 return BrowserWmMouseMove(ref m);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 4 hits
📄 src\Sources\Browser\WebView\Components\ContextMenu\AnimatedContextMenuStrip.cs (line 55)
52 {
53 if (InvokeRequired)
54 {
55 Invoke(new Action(FadeOut));
56 return;
57 }
58
💬 Async overload available for Control.Invoke (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Sources\Browser\WebView\Components\ContextMenu\AnimatedContextMenuStrip.cs (line 55)
52 {
53 if (InvokeRequired)
54 {
55 Invoke(new Action(FadeOut));
56 return;
57 }
58
💬 Async overload available for Control.Invoke (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS059 IAsyncDisposable not disposed asynchronously 20 hits
📄 src\Sources\Browser\WebView\BrowserProcess\WindowBindingObjectServiceServer.cs (line 32)
29 {
30 try
31 {
32 using var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
33
34 await server.WaitForConnectionAsync(_cancellationTokenSource.Token);
35 AcceptClient(server);
💬 NamedPipeServerStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Sources\Browser\WebView\BrowserProcess\WindowBindingObjectServiceServer.cs (line 32)
29 {
30 try
31 {
32 using var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
33
34 await server.WaitForConnectionAsync(_cancellationTokenSource.Token);
35 AcceptClient(server);
💬 NamedPipeServerStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 550 hits
📄 src\Sources\Browser\WebView\Components\DevTools\DevToolsWindow.cs (line 11)
8namespace NetDimension.NanUI.Browser.DevTools;
9internal class DevToolsWindow : StandardWindowForm
10{
11 public WebView WebView { get; }
12 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
13 public IntPtr? BrowserWindowHandle { get; internal set; }
14
💬 Disposable field WebView in type DevToolsWindow is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Sources\Browser\WebView\Components\PopupBrowser\EmbeddedBrowserWindow.cs (line 16)
13 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
14 public nint? BrowserWindowHandle { get; internal set; }
15 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
16 public CefBrowser? Browser { get; internal set; }
17
18 public EmbeddedBrowserWindow()
19 : base(false, false)
💬 Disposable field Browser in type EmbeddedBrowserWindow is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

roslynator

1720 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 16 hits
📄 src\Common\RuleSetLoader.cs (line 62)
59 {
60 //sw = File.CreateText(path + ".log");
61
62 sw?.WriteLine($"{DateTime.Now.ToString()} loading rule set from {path}");
63 sw?.WriteLine($"{DateTime.Now.ToString()} base directory {AppContext.BaseDirectory}");
64 sw?.WriteLine($"{DateTime.Now.ToString()} current directory {Environment.CurrentDirectory}");
65
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Common\RuleSetLoader.cs (line 63)
60 //sw = File.CreateText(path + ".log");
61
62 sw?.WriteLine($"{DateTime.Now.ToString()} loading rule set from {path}");
63 sw?.WriteLine($"{DateTime.Now.ToString()} base directory {AppContext.BaseDirectory}");
64 sw?.WriteLine($"{DateTime.Now.ToString()} current directory {Environment.CurrentDirectory}");
65
66 if (File.Exists(path))
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 10 hits
📄 src\Core\EnumUtility.cs (line 133)
130
131 while (start <= end)
132 {
133 int i = (end + start) / 2;
134
135 long order = unchecked((long)value - (long)fields[i].Value);
136
💬 The operands in the divisive expression (end + start) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Workspaces.Core\Spelling\Core\Spellchecker.cs (line 330)
327 && value.Length % i == 0)
328 {
329 int length = i;
330 int count = value.Length / i;
331
332 for (int j = 0; j < count - 1; j++)
333 {
💬 The operands in the divisive expression value.Length / i are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 58 hits
📄 src\Workspaces.Core\AnalyzerAssembly.cs (line 57)
54
55 internal IEnumerable<CodeFixProvider> GetFixers()
56 {
57 return FixersByLanguage
58 .SelectMany(f => f.Value)
59 .Distinct();
60 }
💬 Type CodeFixProvider is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Workspaces.Core\AnalyzerLoader.cs (line 103)
100
101 if (!Options.IgnoreAnalyzerReferences)
102 {
103 foreach (Assembly assembly in project.AnalyzerReferences
104 .Distinct()
105 .OfType<AnalyzerFileReference>()
106 .Select(f => f.GetAssembly())
💬 Type AnalyzerReference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 16 hits
📄 src\Core\ExtensionMethodSymbolInfo.cs (line 71)
68
69 public override int GetHashCode()
70 {
71 return SymbolEqualityComparer.Default.GetHashCode(Symbol);
72 }
73
74 public static bool operator ==(in ExtensionMethodSymbolInfo info1, in ExtensionMethodSymbolInfo info2)
💬 GetHashCode() refers to mutable field Default (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Core\TypeAnalysis.cs (line 49)
46
47 public override int GetHashCode()
48 {
49 return SymbolEqualityComparer.Default.GetHashCode(Symbol);
50 }
51
52 public static bool operator ==(in TypeAnalysis analysis1, in TypeAnalysis analysis2)
💬 GetHashCode() refers to mutable field Default (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 198 hits
📄 src\Core\EnumFieldSymbolInfo.cs (line 9)
6
7namespace Roslynator;
8
9internal readonly struct EnumFieldSymbolInfo
10{
11 public EnumFieldSymbolInfo(IFieldSymbol symbol, ulong value)
12 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EnumFieldSymbolInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Core\EnumSymbolInfo.cs (line 11)
8
9namespace Roslynator;
10
11internal readonly struct EnumSymbolInfo
12{
13 private EnumSymbolInfo(ImmutableArray<EnumFieldSymbolInfo> fields)
14 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EnumSymbolInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 486 hits
📄 src\Core\CreateNameFromTypeSymbolHelper.cs (line 79)
76
77 private static ITypeSymbol ExtractFromArrayOrGenericCollection(ITypeSymbol typeSymbol)
78 {
79 switch (typeSymbol.Kind)
80 {
81 case SymbolKind.ArrayType:
82 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Core\CreateNameFromTypeSymbolHelper.cs (line 163)
160 return null;
161 }
162
163 switch (typeSymbol.SpecialType)
164 {
165 case SpecialType.System_Object:
166 case SpecialType.System_Boolean:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 892 hits
📄 src\Core\CreateNameFromTypeSymbolHelper.cs (line 79)
76
77 private static ITypeSymbol ExtractFromArrayOrGenericCollection(ITypeSymbol typeSymbol)
78 {
79 switch (typeSymbol.Kind)
80 {
81 case SymbolKind.ArrayType:
82 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Core\CreateNameFromTypeSymbolHelper.cs (line 163)
160 return null;
161 }
162
163 switch (typeSymbol.SpecialType)
164 {
165 case SpecialType.System_Object:
166 case SpecialType.System_Boolean:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 12 hits
📄 src\Tests\CodeFixes.Tests\CS0177OutParameterMustBeAssignedToBeforeControlLeavesCurrentMethodTests.cs (line 168)
165 // Flow analysis APIs do not work with local functions: https://github.com/dotnet/roslyn/issues/14214
166#pragma warning disable xUnit1013
167 //[Fact, Trait(Traits.CodeFix, CompilerDiagnosticIdentifiers.OutParameterMustBeAssignedToBeforeControlLeavesCurrentMethod)]
168 public async Task Test_VoidLocalFunctionWithTwoOutParameters()
169 {
170 await VerifyFixAsync(@"
171class C
💬 Method Test_VoidLocalFunctionWithTwoOutParameters might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 src\Tests\CodeFixes.Tests\CS0177OutParameterMustBeAssignedToBeforeControlLeavesCurrentMethodTests.cs (line 196)
193 }
194
195 //[Fact, Trait(Traits.CodeFix, CompilerDiagnosticIdentifiers.OutParameterMustBeAssignedToBeforeControlLeavesCurrentMethod)]
196 public async Task Test_VoidLocalFunctionWithStatement()
197 {
198 await VerifyFixAsync(@"
199class C
💬 Method Test_VoidLocalFunctionWithStatement might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS023 Exception thrown from property getter 6 hits
📄 src\Core\Collections\Enumerator.cs (line 18)
15
16 public object Current
17 {
18 get { throw new InvalidOperationException(); }
19 }
20
21 public bool MoveNext()
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Core\Collections\Enumerator`1.cs (line 18)
15
16 new public T Current
17 {
18 get { throw new InvalidOperationException(); }
19 }
20
21 public void Dispose()
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS030 Exception thrown from Equals 2 hits
📄 src\Core\OneOrMany`1.cs (line 120)
117 }
118 }
119
120 throw new InvalidOperationException();
121 }
122
123 public override int GetHashCode()
💬 An exception is thrown from the Equals(OneOrMany<T>) method in type OneOrMany (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
📄 src\Core\OneOrMany`1.cs (line 120)
117 }
118 }
119
120 throw new InvalidOperationException();
121 }
122
123 public override int GetHashCode()
💬 An exception is thrown from the Equals(OneOrMany<T>) method in type OneOrMany (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
SS033 Async overload is available 10 hits
📄 src\Workspaces.Common\CSharp\Refactorings\ChangeAccessibilityRefactoring.cs (line 104)
101 ISymbol symbol = semanticModel.GetDeclaredSymbol(member, cancellationToken);
102
103 foreach (SyntaxReference reference in symbol.DeclaringSyntaxReferences)
104 members.Add((MemberDeclarationSyntax)reference.GetSyntax(cancellationToken));
105 }
106 else if (filter.HasAnyFlag(ModifierFilter.AbstractVirtualOverride))
107 {
💬 Async overload available for SyntaxReference.GetSyntax (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\CodeFixes\CSharp\CodeFixes\ArgumentCodeFixProvider.cs (line 124)
121 if (fieldSymbol.DeclaredAccessibility != Accessibility.Private)
122 return;
123
124 if (fieldSymbol.GetSyntax().Parent.Parent is not FieldDeclarationSyntax fieldDeclaration)
125 return;
126
127 TypeDeclarationSyntax containingTypeDeclaration = fieldDeclaration.FirstAncestor<TypeDeclarationSyntax>();
💬 Async overload available for SymbolExtensions.GetSyntax (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS058 String concatenated in a loop 14 hits
📄 src\Core\UnderscoreSuffixNameGenerator.cs (line 19)
16
17 while (!IsUniqueName(name, reservedNames, isCaseSensitive))
18 {
19 suffix += "_";
20 name = baseName + suffix;
21 }
22
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Core\UnderscoreSuffixNameGenerator.cs (line 34)
31
32 while (!IsUniqueName(name, symbols, isCaseSensitive))
33 {
34 suffix += "_";
35 name = baseName + suffix;
36 }
37
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

server

1624 total diagnostics across 22 rules

SS001 Async method with void return type 140 hits
📄 test\Core.Test\Auth\Services\DuoUniversalTokenServiceTests.cs (line 16)
13 [BitAutoData("", "ClientId", "ClientSecret")]
14 [BitAutoData("api-valid.duosecurity.com", "", "ClientSecret")]
15 [BitAutoData("api-valid.duosecurity.com", "ClientId", "")]
16 public async void ValidateDuoConfiguration_InvalidConfig_ReturnsFalse(
17 string host, string clientId, string clientSecret, SutProvider<DuoUniversalTokenService> sutProvider)
18 {
19 // Arrange
💬 Method ValidateDuoConfiguration_InvalidConfig_ReturnsFalse is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 test\Core.Test\Platform\Push\NotificationHub\NotificationHubProxyTests.cs (line 28)
25
26 [Theory]
27 [MemberData(nameof(ClientMethods))]
28 public async void CallsAllClients(Func<NotificationHubClientProxy, Task> proxyMethod, Func<INotificationHubClient, Task> clientMethod)
29 {
30 var clients = _clients.ToArray();
31 var proxy = new NotificationHubClientProxy(clients);
💬 Method CallsAllClients is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 52 hits
📄 src\Core\Auth\UserFeatures\TwoFactorAuth\Implementations\CompleteTwoFactorWebAuthnRegistrationCommand.cs (line 74)
71 UserHandle = success.Result.User.Id,
72 SignatureCounter = success.Result.Counter,
73 CredType = success.Result.CredType,
74 RegDate = DateTime.Now,
75 AaGuid = success.Result.Aaguid
76 };
77
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 test\Core.Test\AdminConsole\Models\Data\SelfHostedOrganizationDetailsTests.cs (line 379)
376 license.UsersGetPremium = true;
377 license.UseCustomPermissions = true;
378 license.Version = 11;
379 license.Issued = DateTime.Now;
380 license.Expires = DateTime.Now.AddYears(1);
381
382 return (organization, license);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 18 hits
📄 src\Core\Repositories\TableStorage\InstallationDeviceRepository.cs (line 52)
49 }
50
51 // A batch insert can only contain 100 entities at a time
52 var iterations = groupEntities.Count / 100;
53 for (var i = 0; i <= iterations; i++)
54 {
55 var batch = new List<TableTransactionAction>();
💬 The operands in the divisive expression groupEntities.Count / 100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Core\Dirt\Repositories\TableStorage\EventRepository.cs (line 129)
126 }
127
128 // A batch insert can only contain 100 entities at a time
129 var iterations = groupEntities.Count / 100;
130 for (var i = 0; i <= iterations; i++)
131 {
132 var batch = new List<TableTransactionAction>();
💬 The operands in the divisive expression groupEntities.Count / 100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 232 hits
📄 src\Infrastructure.Dapper\AdminConsole\Helpers\BulkResourceCreationService.cs (line 102)
99 {
100 var row = table.NewRow();
101
102 row[collectionIdColumn] = collectionUserRecord.CollectionId;
103 row[orgUserIdColumn] = collectionUserRecord.OrganizationUserId;
104 row[readOnlyColumn] = collectionUserRecord.ReadOnly;
105 row[hidePasswordsColumn] = collectionUserRecord.HidePasswords;
💬 Type DataColumn is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Infrastructure.Dapper\AdminConsole\Helpers\BulkResourceCreationService.cs (line 103)
100 var row = table.NewRow();
101
102 row[collectionIdColumn] = collectionUserRecord.CollectionId;
103 row[orgUserIdColumn] = collectionUserRecord.OrganizationUserId;
104 row[readOnlyColumn] = collectionUserRecord.ReadOnly;
105 row[hidePasswordsColumn] = collectionUserRecord.HidePasswords;
106 row[manageColumn] = collectionUserRecord.Manage;
💬 Type DataColumn is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS009 Random instantiated in a loop 2 hits
📄 src\Core\Jobs\BaseJobsHostedService.cs (line 110)
107 }
108
109 _logger.LogWarning(e, "Exception while trying to schedule job: {JobName}", job.FullName);
110 var random = new Random();
111 await Task.Delay(random.Next(50, 250));
112 }
113 }
💬 Variable random of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
📄 src\Core\Jobs\BaseJobsHostedService.cs (line 110)
107 }
108
109 _logger.LogWarning(e, "Exception while trying to schedule job: {JobName}", job.FullName);
110 var random = new Random();
111 await Task.Delay(random.Next(50, 250));
112 }
113 }
💬 Variable random of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 util\Seeder\Scenes\SingleUserScene.cs (line 10)
7
8namespace Bit.Seeder.Scenes;
9
10public struct SingleUserSceneResult
11{
12 public Guid UserId { get; init; }
13 public string Kdf { get; init; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SingleUserSceneResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 util\Seeder\Scenes\SingleUserScene.cs (line 10)
7
8namespace Bit.Seeder.Scenes;
9
10public struct SingleUserSceneResult
11{
12 public Guid UserId { get; init; }
13 public string Kdf { get; init; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SingleUserSceneResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 24 hits
📄 src\Core\AdminConsole\Utilities\PolicyDataValidator.cs (line 31)
28 {
29 var json = JsonSerializer.Serialize(data);
30
31 switch (policyType)
32 {
33 case PolicyType.MasterPassword:
34 var masterPasswordData = CoreHelpers.LoadClassFromJsonData<MasterPasswordPolicyData>(json);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Core\Services\Implementations\UserService.cs (line 598)
595
596 // Calling User must be of higher/equal user type to reset user's password
597 var canAdjustPassword = false;
598 switch (callingUserType)
599 {
600 case OrganizationUserType.Owner:
601 canAdjustPassword = true;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 108 hits
📄 src\Core\AdminConsole\Enums\PolicyType.cs (line 35)
32 /// </summary>
33 public static string GetName(this PolicyType type)
34 {
35 return type switch
36 {
37 PolicyType.TwoFactorAuthentication => "Require two-step login",
38 PolicyType.MasterPassword => "Master password requirements",
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Core\AdminConsole\Utilities\PolicyDataValidator.cs (line 31)
28 {
29 var json = JsonSerializer.Serialize(data);
30
31 switch (policyType)
32 {
33 case PolicyType.MasterPassword:
34 var masterPasswordData = CoreHelpers.LoadClassFromJsonData<MasterPasswordPolicyData>(json);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS020 Test method without public modifier 38 hits
📄 test\Core.Test\KeyManagement\SendPasswordHasherTests.cs (line 16)
13 [Theory]
14 [BitAutoData(PasswordVerificationResult.Success)]
15 [BitAutoData(PasswordVerificationResult.SuccessRehashNeeded)]
16 void VerifyPasswordHash_WithValidMatching_ReturnsTrue(
17 PasswordVerificationResult passwordVerificationResult,
18 SutProvider<SendPasswordHasher> sutProvider,
19 string sendPasswordHash,
💬 Test method "VerifyPasswordHash_WithValidMatching_ReturnsTrue" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
📄 test\Core.Test\KeyManagement\SendPasswordHasherTests.cs (line 38)
35 }
36
37 [Theory, BitAutoData]
38 void VerifyPasswordHash_WithNonMatchingPasswords_ReturnsFalse(
39 SutProvider<SendPasswordHasher> sutProvider,
40 string sendPasswordHash,
41 string inputPasswordHash)
💬 Test method "VerifyPasswordHash_WithNonMatchingPasswords_ReturnsFalse" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
SS023 Exception thrown from property getter 6 hits
📄 src\Core\Platform\Push\NotificationHub\NotificationHubConnection.cs (line 36)
33 {
34 if (!IsValid)
35 {
36 throw new Exception("Invalid notification hub settings");
37 }
38 Init();
39 }
💬 An exception is thrown from the getter of property HubClient (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Api\Billing\Models\Requests\PreviewInvoice\PreviewPremiumUpgradeProrationRequest.cs (line 24)
21 {
22 if (TargetProductTierType is not (ProductTierType.Families or ProductTierType.Teams or ProductTierType.Enterprise))
23 {
24 throw new InvalidOperationException($"Cannot upgrade Premium subscription to {TargetProductTierType} plan.");
25 }
26
27 return TargetProductTierType switch
💬 An exception is thrown from the getter of property PlanType (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 114 hits
📄 src\Core\HostedServices\ApplicationCacheHostedService.cs (line 72)
69 public virtual async Task StopAsync(CancellationToken cancellationToken)
70 {
71 // Step 1: Signal ExecuteAsync to stop gracefully
72 _cts?.Cancel();
73
74 // Step 2: Wait for ExecuteAsync to finish cleanly
75 if (_executingTask != null)
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Core\Billing\Services\Implementations\StripePaymentService.cs (line 313)
310 {
311 var transactionRequest = new Braintree.TransactionSearchRequest()
312 .CustomerId.Is(customer.Metadata["btCustomerId"]);
313 var transactions = _btGateway.Transaction.Search(transactionRequest);
314
315 if ((transactions?.MaximumCount ?? 0) > 0)
316 {
💬 Async overload available for ITransactionGateway.Search (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 18 hits
📄 src\Core\AdminConsole\OrganizationFeatures\OrganizationUsers\OrganizationUserUserDetailsQuery.cs (line 70)
67
68 await Task.WhenAll(twoFactorTask, claimedStatusTask);
69
70 var organizationUsersTwoFactorEnabled = twoFactorTask.Result.ToDictionary(u => u.user.Id, u => u.twoFactorIsEnabled);
71 var organizationUsersClaimedStatus = claimedStatusTask.Result;
72 var responses = organizationUsers.Select(organizationUserDetails =>
73 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Core\AdminConsole\OrganizationFeatures\OrganizationUsers\OrganizationUserUserDetailsQuery.cs (line 71)
68 await Task.WhenAll(twoFactorTask, claimedStatusTask);
69
70 var organizationUsersTwoFactorEnabled = twoFactorTask.Result.ToDictionary(u => u.user.Id, u => u.twoFactorIsEnabled);
71 var organizationUsersClaimedStatus = claimedStatusTask.Result;
72 var responses = organizationUsers.Select(organizationUserDetails =>
73 {
74 // Only set permissions for Custom user types for performance optimization
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS037 HttpClient instantiated directly 48 hits
📄 util\Setup\Program.cs (line 290)
287 url = $"{installationUrl}/installations/";
288 }
289
290 var response = new HttpClient().GetAsync(url + _context.Install.InstallationId).GetAwaiter().GetResult();
291
292 if (!response.IsSuccessStatusCode)
293 {
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 test\Common\MockedHttpClient\MockedHttpMessageHandler.cs (line 114)
111 /// <returns></returns>
112 public HttpClient ToHttpClient()
113 {
114 return new HttpClient(this);
115 }
116}
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS041 Unnecessary enumerable materialization 8 hits
📄 src\Core\KeyManagement\UserKey\Implementations\RotateUserAccountKeysCommand.cs (line 182)
179
180 if (model.Ciphers.Any())
181 {
182 var ciphersWithUpdatedDate = model.Ciphers.ToList().Select(c => { c.RevisionDate = now; return c; });
183 saveEncryptedDataActions.Add(_cipherRepository.UpdateForKeyRotation(user.Id, ciphersWithUpdatedDate));
184 }
185
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\Core\KeyManagement\UserKey\Implementations\RotateUserAccountKeysCommand.cs (line 188)
185
186 if (model.Folders.Any())
187 {
188 var foldersWithUpdatedDate = model.Folders.ToList().Select(f => { f.RevisionDate = now; return f; });
189 saveEncryptedDataActions.Add(_folderRepository.UpdateForKeyRotation(user.Id, foldersWithUpdatedDate));
190 }
191
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 18 hits
📄 src\Core\Auth\Attributes\MarketingInitiativeValidationAttribute.cs (line 6)
3
4namespace Bit.Core.Auth.Attributes;
5
6public class MarketingInitiativeValidationAttribute : ValidationAttribute
7{
8 private static readonly string[] _acceptedValues = [MarketingInitiativeConstants.Premium];
9
💬 MarketingInitiativeValidationAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\Core\Utilities\DomainNameAttribute.cs (line 12)
9/// Domain names can contain letters, numbers, dots, and hyphens.
10/// Domain names maybe internationalized (IDN) and contain unicode characters.
11/// </summary>
12public class DomainNameValidatorAttribute : ValidationAttribute
13{
14 // RFC 1123 compliant domain name regex
15 // - Allows alphanumeric characters and hyphens
💬 DomainNameValidatorAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 22 hits
📄 util\Setup\Program.cs (line 76)
73 if (_context.Parameters.TryGetValue("letsencrypt", out var sslManagedLetsEncrypt))
74 {
75 _context.Config.SslManagedLetsEncrypt =
76 sslManagedLetsEncrypt.ToLowerInvariant() == "y";
77 }
78 if (_context.Parameters.TryGetValue("domain", out var domain))
79 {
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 bitwarden_license\src\Scim\Users\GetUsersListQuery.cs (line 52)
49 var totalResults = 0;
50 if (!string.IsNullOrWhiteSpace(emailFilter))
51 {
52 var orgUser = orgUsers.FirstOrDefault(ou => ou.Email.ToLowerInvariant() == emailFilter);
53 if (orgUser != null)
54 {
55 userList.Add(orgUser);
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 4 hits
📄 src\Icons\Models\DomainName.cs (line 265)
262 {
263 if (_uniqueInstance == null)
264 {
265 lock (_syncObj)
266 {
267 if (_uniqueInstance == null)
268 {
💬 A lock was obtained on _syncObj but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\Icons\Models\DomainName.cs (line 281)
278
279 public static void Reset()
280 {
281 lock (_syncObj)
282 {
283 _uniqueInstance = null;
284 }
💬 A lock was obtained on _syncObj but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS054 Newtonsoft.Json mixed with System.Text.Json 60 hits
📄 src\Billing\Jobs\ReconcileAdditionalStorageJob.cs (line 149)
146 "{NewLine2}And would have updated database record tier: {Tier} to new MaxStorageGb: {MaxStorageGb}",
147 subscription.Id,
148 Environment.NewLine,
149 JsonSerializer.Serialize(updateOptions),
150 Environment.NewLine,
151 subscriptionPlanTier,
152 newMaxStorageGb);
💬 Attempting to serialize an object annotated with Newtonsoft.Json through System.Text.Json (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS054-NewtonsoftMixedWithSystemTextJson.md)
📄 src\Billing\Jobs\ReconcileAdditionalStorageJob.cs (line 149)
146 "{NewLine2}And would have updated database record tier: {Tier} to new MaxStorageGb: {MaxStorageGb}",
147 subscription.Id,
148 Environment.NewLine,
149 JsonSerializer.Serialize(updateOptions),
150 Environment.NewLine,
151 subscriptionPlanTier,
152 newMaxStorageGb);
💬 Attempting to serialize an object annotated with Newtonsoft.Json through System.Text.Json (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS054-NewtonsoftMixedWithSystemTextJson.md)
SS056 HttpRequest.Form read synchronously 8 hits
📄 bitwarden_license\src\Sso\Utilities\SsoAuthenticationMiddleware.cs (line 23)
20 public async Task Invoke(HttpContext context)
21 {
22 if ((context.Request.Method == "GET" && context.Request.Query.ContainsKey("SAMLart"))
23 || (context.Request.Method == "POST" && context.Request.Form.ContainsKey("SAMLart")))
24 {
25 throw new Exception("SAMLart parameter detected. SAML Artifact binding is not allowed.");
26 }
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
📄 bitwarden_license\src\Sso\Utilities\Saml2OptionsExtensions.cs (line 41)
38 context.Request.HasFormContentType)
39 {
40 string encodedMessage;
41 if (context.Request.Form.TryGetValue("SAMLResponse", out var response))
42 {
43 encodedMessage = response.FirstOrDefault();
44 }
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
SS058 String concatenated in a loop 8 hits
📄 test\Core.Test\AdminConsole\Entities\OrganizationTests.cs (line 212)
209 errorMessage += "\n\nPlease add the following lines to Organization.UpdateFromLicense():\n";
210 foreach (var prop in missingApplications)
211 {
212 errorMessage += $" {prop} = license.{prop};\n";
213 }
214 errorMessage += "\nNote: If the property maps to a different name on Organization (like Expires → ExpirationDate), adjust accordingly.";
215 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 test\Core.Test\Billing\Licenses\Services\Implementations\OrganizationLicenseClaimsFactoryTests.cs (line 82)
79 errorMessage += "\n\nPlease add the following claims to OrganizationLicenseClaimsFactory.GenerateClaims():\n";
80 foreach (var constant in constantsWithoutClaims)
81 {
82 errorMessage += $" new(nameof(OrganizationLicenseConstants.{constant}), entity.{constant}.ToString()),\n";
83 }
84 errorMessage += "\nNote: If the property is nullable, you may need to add it conditionally.";
85 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 564 hits
📄 test\Server.IntegrationTest\ServerTests.cs (line 15)
12
13 await tempDir.WriteAsync("my-file.txt", "Hello!");
14
15 using var server = new Server
16 {
17 ContentRoot = tempDir.Info.FullName,
18 WebRoot = ".",
💬 Server can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 test\Server.IntegrationTest\ServerTests.cs (line 43)
40 await tempDir.WriteAsync(Path.Join("images", "file.avif"), "ImagesStuff");
41 await tempDir.WriteAsync(Path.Join("test", "file.json"), "{}");
42
43 using var server = new Server
44 {
45 ContentRoot = tempDir.Info.FullName,
46 WebRoot = ".",
💬 Server can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 130 hits
📄 src\Core\Dirt\Services\Implementations\AzureServiceBusIntegrationListenerService.cs (line 12)
9 where TConfiguration : IIntegrationListenerConfiguration
10{
11 private readonly int _maxRetries;
12 private readonly IAzureServiceBusService _serviceBusService;
13 private readonly IIntegrationHandler _handler;
14 private readonly ServiceBusProcessor _processor;
15 private readonly ILogger _logger;
💬 Disposable field _serviceBusService in type AzureServiceBusIntegrationListenerService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Core\Dirt\Services\Implementations\AzureServiceBusIntegrationListenerService.cs (line 14)
11 private readonly int _maxRetries;
12 private readonly IAzureServiceBusService _serviceBusService;
13 private readonly IIntegrationHandler _handler;
14 private readonly ServiceBusProcessor _processor;
15 private readonly ILogger _logger;
16
17 public AzureServiceBusIntegrationListenerService(
💬 Disposable field _processor in type AzureServiceBusIntegrationListenerService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

mathnet-numerics

1602 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 8 hits
📄 src\Numerics.Tests\InterpolationTests\CubicSplineTest.cs (line 257)
254 var data = GenerateSplineData(amplitude, period, decay, minX, maxX, ofset, points);
255 CubicSpline it = CubicSpline.InterpolateBoundaries(data.Item1, data.Item2, SplineBoundaryCondition.Natural, 0, SplineBoundaryCondition.Natural, 0);
256 //start the time and calculate the min max values
257 var t = DateTime.Now;
258 var minMax = it.Extrema();
259 Assert.IsTrue(minMax.Item2.AlmostEqual(ofset, 0.3), "Expexted max value near ofset.");
260 Assert.IsTrue(minMax.Item1.AlmostEqual(ofset+period/2, 0.3) || minMax.Item1.AlmostEqual(ofset - period / 2, 0.3), "Expexted min value near ofset +- period/2.");
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Numerics.Tests\InterpolationTests\CubicSplineTest.cs (line 262)
259 Assert.IsTrue(minMax.Item2.AlmostEqual(ofset, 0.3), "Expexted max value near ofset.");
260 Assert.IsTrue(minMax.Item1.AlmostEqual(ofset+period/2, 0.3) || minMax.Item1.AlmostEqual(ofset - period / 2, 0.3), "Expexted min value near ofset +- period/2.");
261 //spit out the time it took to calculate
262 Console.WriteLine("Extrema took: " + (DateTime.Now - t).TotalMilliseconds.ToString("000.00")+" ms for "+points.ToString()+" points.");
263 //determine if the values are correct
264 var sp = it.StationaryPoints();
265 foreach (var x in sp)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 1064 hits
📄 src\Numerics\Differentiate.cs (line 54)
51 public static NumericalDerivative Order(int order)
52 {
53 var points = order + (order.IsEven() ? 1 : 2);
54 return new NumericalDerivative(points, points/2);
55 }
56
57 /// <summary>
💬 The operands in the divisive expression points/2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Numerics\Euclid.cs (line 479)
476 return 0;
477 }
478
479 return Math.Abs((a/GreatestCommonDivisor(a, b))*b);
480 }
481
482 /// <summary>
💬 The operands in the divisive expression a/GreatestCommonDivisor(a, b) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS005 Equals() and GetHashCode() not implemented together 24 hits
📄 src\Numerics\LinearAlgebra\Storage\SparseVectorStorage.cs (line 41)
38{
39 [Serializable]
40 [DataContract(Namespace = "urn:MathNet/Numerics/LinearAlgebra")]
41 public class SparseVectorStorage<T> : VectorStorage<T>
42 where T : struct, IEquatable<T>, IFormattable
43 {
44 // [ruegg] public fields are OK here
💬 Equals() and GetHashcode() must be implemented together on SparseVectorStorage (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\Numerics\LinearAlgebra\Storage\DiagonalMatrixStorage.cs (line 40)
37{
38 [Serializable]
39 [DataContract(Namespace = "urn:MathNet/Numerics/LinearAlgebra")]
40 public class DiagonalMatrixStorage<T> : MatrixStorage<T>
41 where T : struct, IEquatable<T>, IFormattable
42 {
43 // [ruegg] public fields are OK here
💬 Equals() and GetHashcode() must be implemented together on DiagonalMatrixStorage (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 88 hits
📄 src\Numerics\LinearAlgebra\Vector.BCL.cs (line 75)
72 /// </returns>
73 public sealed override int GetHashCode()
74 {
75 return Storage.GetHashCode();
76 }
77
78 /// <summary>
💬 GetHashCode() refers to mutable property Storage (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Numerics\LinearAlgebra\Storage\SparseVectorStorage.cs (line 251)
248 /// </returns>
249 public override int GetHashCode()
250 {
251 var values = Values;
252 var hashNum = Math.Min(ValueCount, 25);
253 int hash = 17;
254 unchecked
💬 GetHashCode() refers to mutable field Values (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 24 hits
📄 src\Numerics\Precision.cs (line 986)
983 }
984
985 [StructLayout(LayoutKind.Explicit)]
986 struct SingleIntUnion
987 {
988 [FieldOffset(0)]
989 public float Single;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SingleIntUnion. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Numerics\Optimization\QuadraticGradientProjectionSearch.cs (line 115)
112 }
113 }
114
115 public readonly struct GradientProjectionResult
116 {
117 public GradientProjectionResult(Vector<double> cauchyPoint, int fixedCount, List<bool> isFixed)
118 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct GradientProjectionResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 32 hits
📄 src\Numerics\Providers\FourierTransform\ManagedFourierTransformProvider.cs (line 118)
115 BluesteinForward(samples);
116 }
117
118 switch (scaling)
119 {
120 case FourierTransformScaling.SymmetricScaling:
121 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Numerics\Providers\FourierTransform\ManagedFourierTransformProvider.cs (line 85)
82 BluesteinForward(samples);
83 }
84
85 switch (scaling)
86 {
87 case FourierTransformScaling.SymmetricScaling:
88 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 170 hits
📄 src\Numerics\Distributions\SkewedGeneralizedT.cs (line 414)
411 // InverseCumulativeDistribution is not a part of the interface, so resort to type-checking.
412 if (d != null)
413 {
414 switch (d)
415 {
416 case SkewedGeneralizedError sge:
417 return sge.InverseCumulativeDistribution(pr);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Numerics\Distributions\SkewedGeneralizedT.cs (line 462)
459 // InverseCumulativeDistribution is not a part of the interface, so resort to type-checking.
460 if (_d != null)
461 {
462 switch (_d)
463 {
464 case SkewedGeneralizedError sge:
465 return sge.InverseCumulativeDistribution(p);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 16 hits
📄 src\Numerics.Tests\DistributionTests\CommonDistributionTests.cs (line 173)
170 /// <param name="delta">The error probability we are willing to tolerate.</param>
171 /// <param name="s">The samples to use for testing.</param>
172 /// <param name="dist">The distribution we are testing.</param>
173 public static void ContinuousVapnikChervonenkisTest(double epsilon, double delta, double[] s, IContinuousDistribution dist)
174 {
175 // Using VC-dimension, we can bound the probability of making an error when estimating empirical probability
176 // distributions. We are using Theorem 2.41 in "All Of Nonparametric Statistics".
💬 Method ContinuousVapnikChervonenkisTest might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 src\Numerics.Tests\DistributionTests\CommonDistributionTests.cs (line 197)
194 /// <param name="delta">The error probability we are willing to tolerate.</param>
195 /// <param name="s">The samples to use for testing.</param>
196 /// <param name="dist">The distribution we are testing.</param>
197 public static void DiscreteVapnikChervonenkisTest(double epsilon, double delta, int[] s, IDiscreteDistribution dist)
198 {
199 // Using VC-dimension, we can bound the probability of making an error when estimating empirical probability
200 // distributions. We are using Theorem 2.41 in "All Of Nonparametric Statistics".
💬 Method DiscreteVapnikChervonenkisTest might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS022 Exception thrown from implicit operator 32 hits
📄 src\Numerics\LinearAlgebra\Single\DenseVector.cs (line 206)
203 {
204 if (array == null)
205 {
206 throw new ArgumentNullException(nameof(array));
207 }
208
209 return new DenseVector(array);
💬 An exception is thrown from implicit operator DenseVector in type DenseVector (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
📄 src\Numerics\LinearAlgebra\Complex\DenseVector.cs (line 206)
203 {
204 if (array == null)
205 {
206 throw new ArgumentNullException(nameof(array));
207 }
208
209 return new DenseVector(array);
💬 An exception is thrown from implicit operator DenseVector in type DenseVector (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
SS023 Exception thrown from property getter 96 hits
📄 src\Numerics\LinearAlgebra\Double\Factorization\QR.cs (line 63)
60 {
61 if (FullR.RowCount != FullR.ColumnCount)
62 {
63 throw new ArgumentException("Matrix must be square.");
64 }
65
66 var det = 1.0;
💬 An exception is thrown from the getter of property Determinant (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Numerics\LinearAlgebra\Double\Factorization\GramSchmidt.cs (line 58)
55 {
56 if (FullR.RowCount != FullR.ColumnCount)
57 {
58 throw new ArgumentException("Matrix must be square.");
59 }
60
61 var det = 1.0;
💬 An exception is thrown from the getter of property Determinant (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS047 LINQ traversal before filter 16 hits
📄 src\Numerics\LinearAlgebra\Storage\SparseVectorStorage.cs (line 678)
675
676 public override IEnumerable<T> EnumerateNonZero()
677 {
678 return Values.Take(ValueCount).Where(x => !Zero.Equals(x));
679 }
680
681 public override IEnumerable<(int, T)> EnumerateNonZeroIndexed()
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 src\Numerics\LinearAlgebra\Storage\SparseCompressedRowMatrixStorage.cs (line 1703)
1700
1701 public override IEnumerable<T> EnumerateNonZero()
1702 {
1703 return Values.Take(ValueCount).Where(x => !Zero.Equals(x));
1704 }
1705
1706 public override IEnumerable<(int, int, T)> EnumerateNonZeroIndexed()
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS058 String concatenated in a loop 32 hits
📄 src\Numerics\LinearAlgebra\Complex\SparseVector.cs (line 878)
875 string current = string.Empty;
876 for (int i = 0; i < weakTokens.Length; i++)
877 {
878 current += weakTokens[i];
879 if (current.EndsWith("+") || current.EndsWith("-") || current.StartsWith("(") && !current.EndsWith(")"))
880 {
881 continue;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Numerics\LinearAlgebra\Complex\DenseVector.cs (line 720)
717 string current = string.Empty;
718 for (int i = 0; i < weakTokens.Length; i++)
719 {
720 current += weakTokens[i];
721 if (current.EndsWith("+") || current.EndsWith("-") || current.StartsWith("(") && !current.EndsWith(")"))
722 {
723 continue;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

WTM

1594 total diagnostics across 20 rules

SS001 Async method with void return type 2 hits
📄 demo\WalkingTec.Mvvm.BlazorDemo\WalkingTec.Mvvm.BlazorDemo.Shared\WtmBlazorUtils\BasePage.cs (line 187)
184 }
185
186
187 public async void SetError(ValidateForm form, ErrorObj errors)
188 {
189 if (errors != null)
190 {
💬 Method SetError is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 demo\WalkingTec.Mvvm.BlazorDemo\WalkingTec.Mvvm.BlazorDemo.Shared\WtmBlazorUtils\BasePage.cs (line 187)
184 }
185
186
187 public async void SetError(ValidateForm form, ErrorObj errors)
188 {
189 if (errors != null)
190 {
💬 Method SetError is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 176 hits
📄 src\WalkingTec.Mvvm.Core\LoginUserInfo.cs (line 54)
51 /// 用户的数据权限列表
52 /// </summary>
53 public List<SimpleDataPri> DataPrivileges { get; set; }
54 public long TimeTick { get; set; } = DateTime.Now.Ticks;
55 public async System.Threading.Tasks.Task LoadBasicInfoAsync(WTMContext context)
56 {
57 if (string.IsNullOrEmpty(this.ITCode) || context?.DC == null || context.BaseUserQuery == null)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\WalkingTec.Mvvm.Core\BasePagedListVM.cs (line 167)
164 else
165 {
166 Guid g = Guid.NewGuid();
167 var FileName = typeof(TModel).Name + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff");
168 //文件根目录
169 string RootPath = $"{Wtm.ConfigInfo.HostRoot}\\export{g}";
170
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 14 hits
📄 src\WalkingTec.Mvvm.Core\BasePagedListVM.cs (line 156)
153
154 //获取分成Excel的个数
155 ExportMaxCount = ExportMaxCount == 0 ? 1000000 : (ExportMaxCount > 1000000 ? 1000000 : ExportMaxCount);
156 ExportExcelCount = listcount < ExportMaxCount ? 1 : ((listcount % ExportMaxCount) == 0 ? (listcount / ExportMaxCount) : (listcount / ExportMaxCount + 1));
157
158 //如果是1,直接下载Excel,如果是多个,下载ZIP包
159 if (ExportExcelCount == 1)
💬 The operands in the divisive expression listcount / ExportMaxCount are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\WalkingTec.Mvvm.Core\BasePagedListVM.cs (line 156)
153
154 //获取分成Excel的个数
155 ExportMaxCount = ExportMaxCount == 0 ? 1000000 : (ExportMaxCount > 1000000 ? 1000000 : ExportMaxCount);
156 ExportExcelCount = listcount < ExportMaxCount ? 1 : ((listcount % ExportMaxCount) == 0 ? (listcount / ExportMaxCount) : (listcount / ExportMaxCount + 1));
157
158 //如果是1,直接下载Excel,如果是多个,下载ZIP包
159 if (ExportExcelCount == 1)
💬 The operands in the divisive expression listcount / ExportMaxCount are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 8 hits
📄 src\WalkingTec.Mvvm.Core\Helper\EntityHelper.cs (line 33)
30 T entity = (T)Activator.CreateInstance(typeof(T));
31 foreach (DataColumn col in table.Columns)
32 {
33 (entity as DynamicData).Add(col.ColumnName, row[col] == DBNull.Value ? null : row[col]);
34 }
35 entityList.Add(entity);
36 }
💬 Type DataColumn is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\WalkingTec.Mvvm.Core\Helper\EntityHelper.cs (line 33)
30 T entity = (T)Activator.CreateInstance(typeof(T));
31 foreach (DataColumn col in table.Columns)
32 {
33 (entity as DynamicData).Add(col.ColumnName, row[col] == DBNull.Value ? null : row[col]);
34 }
35 entityList.Add(entity);
36 }
💬 Type DataColumn is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS009 Random instantiated in a loop 20 hits
📄 src\WalkingTec.Mvvm.Core\Extensions\SystemExtensions\TypeExtension.cs (line 225)
222 }
223 catch { }
224 }
225 Random r = new Random();
226 val = r.Next(start, end).ToString();
227 }
228 else if (pro.PropertyType.IsBoolOrNullableBool())
💬 Variable r of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
📄 src\WalkingTec.Mvvm.Core\Extensions\SystemExtensions\TypeExtension.cs (line 235)
232 {
233 boolvalues.Add("null");
234 }
235 Random r = new Random();
236 var index = r.Next(0, boolvalues.Count);
237 val = boolvalues[index];
238 }
💬 Variable r of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 src\WalkingTec.Mvvm.Core\Extensions\ConfigExtension.cs (line 106)
103
104 [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
105
106 private struct IISConfigurationData
107
108 {
109
💬 Implement Equals(), GetHashCode() and ToString() methods on struct IISConfigurationData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\WalkingTec.Mvvm.Core\Extensions\ConfigExtension.cs (line 106)
103
104 [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
105
106 private struct IISConfigurationData
107
108 {
109
💬 Implement Equals(), GetHashCode() and ToString() methods on struct IISConfigurationData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 16 hits
📄 src\WalkingTec.Mvvm.Core\DataContext.cs (line 786)
783 public object CreateCommandParameter(string name, object value, ParameterDirection dir)
784 {
785 object rv = null;
786 switch (this.DBType)
787 {
788 case DBTypeEnum.SqlServer:
789 rv = new SqlParameter(name, value) { Direction = dir };
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\WalkingTec.Mvvm.Core\Support\DateRange.cs (line 187)
184 switch (Epoch.Kind)
185 {
186 case DateTimeKind.Local:
187 switch (time.Kind)
188 {
189 case DateTimeKind.Unspecified:
190 return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second, time.Millisecond, DateTimeKind.Local);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 28 hits
📄 src\WalkingTec.Mvvm.Core\DataContext.cs (line 786)
783 public object CreateCommandParameter(string name, object value, ParameterDirection dir)
784 {
785 object rv = null;
786 switch (this.DBType)
787 {
788 case DBTypeEnum.SqlServer:
789 rv = new SqlParameter(name, value) { Direction = dir };
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\WalkingTec.Mvvm.Core\WorkFlow\ApproveTimeLine.cs (line 23)
20 get
21 {
22 string rv = "";
23 switch (Action)
24 {
25 case "等待审批":
26 rv = "等待" + this.Approvers + "审批";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 2 hits
📄 test\WalkingTec.Mvvm.Core.Test\VM\BaseBatchVMTest.cs (line 67)
64 }
65 }
66
67 public void InitData()
68 {
69 using (var context = new DataContext(_seed, DBTypeEnum.Memory))
70 {
💬 Method InitData might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 test\WalkingTec.Mvvm.Core.Test\VM\BaseBatchVMTest.cs (line 67)
64 }
65 }
66
67 public void InitData()
68 {
69 using (var context = new DataContext(_seed, DBTypeEnum.Memory))
70 {
💬 Method InitData might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS033 Async overload is available 382 hits
📄 src\WalkingTec.Mvvm.Core\BaseCRUDVM.cs (line 981)
978 //如果是普通的TopBasePoco,则进行物理删除
979 else if (typeof(TModel).GetTypeInfo().IsSubclassOf(typeof(TopBasePoco)))
980 {
981 DoRealDelete();
982 }
983 }
984
💬 Async overload available for BaseCRUDVM.DoRealDelete (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\WalkingTec.Mvvm.Core\DataContext.cs (line 177)
174 systemManagement.Children.Add(item);
175 }
176 }
177 Set<FrameworkMenu>().Add(systemManagement);
178 Set<FunctionPrivilege>().AddRange(systemManagement.FlatTree().Select(x => new FunctionPrivilege { RoleCode = "001", MenuItemId = x.ID, Allowed = true }));
179
180 if (IsSpa == false)
💬 Async overload available for DbSet.Add (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 312 hits
📄 src\WalkingTec.Mvvm.Core\WTMContext.cs (line 390)
387 {
388 Dictionary<string, string> headers = new Dictionary<string, string>();
389 headers.Add("Authorization", "Bearer " + remoteToken);
390 var user = CallAPI<LoginUserInfo>("mainhost", "/api/_account/checkuserinfo?IsApi=false", HttpMethodEnum.GET, new { }, 10, headers: headers).Result;
391 rv = user.Data;
392 if (rv != null)
393 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\WalkingTec.Mvvm.Core\WTMContext.cs (line 399)
396 }
397 else if(string.IsNullOrEmpty(password)==false)
398 {
399 var loginjwt = CallAPI<Token>("mainhost", "/api/_account/loginjwt", HttpMethodEnum.POST, new { Account = username, Password = password }, 10).Result;
400 if (string.IsNullOrEmpty(loginjwt?.Data?.AccessToken) == false)
401 {
402 remoteToken = loginjwt?.Data?.AccessToken;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 12 hits
📄 demo\WalkingTec.Mvvm.ReactDemo\Areas\_Admin\Controllers\FrameworkGroupController.cs (line 131)
128 DC.Set<FrameworkUserGroup>().RemoveRange(gr);
129 DC.SaveChanges();
130 await Wtm.RemoveUserCacheByGroup(GroupCode.ToArray());
131 Wtm.RemoveGroupCache(Wtm.LoginUserInfo.CurrentTenant).Wait();
132 return Ok(ids.Count());
133 }
134 }
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 demo\WalkingTec.Mvvm.VueDemo\Areas\_Admin\Controllers\FrameworkGroupController.cs (line 131)
128 DC.Set<FrameworkUserGroup>().RemoveRange(gr);
129 DC.SaveChanges();
130 await Wtm.RemoveUserCacheByGroup(GroupCode.ToArray());
131 Wtm.RemoveGroupCache(Wtm.LoginUserInfo.CurrentTenant).Wait();
132 return Ok(ids.Count());
133 }
134 }
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS038 HttpContext stored in a field 2 hits
📄 src\WalkingTec.Mvvm.Core\WTMContext.cs (line 30)
27{
28 public class WTMContext : IDisposable
29 {
30 private HttpContext _httpContext;
31 public HttpContext HttpContext { get => _httpContext; }
32
33 private IServiceProvider _serviceProvider;
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
📄 src\WalkingTec.Mvvm.Core\WTMContext.cs (line 30)
27{
28 public class WTMContext : IDisposable
29 {
30 private HttpContext _httpContext;
31 public HttpContext HttpContext { get => _httpContext; }
32
33 private IServiceProvider _serviceProvider;
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
SS041 Unnecessary enumerable materialization 6 hits
📄 src\WalkingTec.Mvvm.Core\Extensions\DCExtension.cs (line 266)
263 //根据Text对下拉菜单数据排序
264 if (SortByName == true)
265 {
266 rv = query.Select(lambda).ToList().OrderBy(x => x.Text).ToList();
267 }
268 else
269 {
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\WalkingTec.Mvvm.Core\Extensions\DCExtension.cs (line 159)
156 //根据Text对下拉菜单数据排序
157 if (SortByName == true)
158 {
159 rv = query.Select(lambda).ToList().OrderBy(x => x.Text).ToList();
160 }
161 else
162 {
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS049 Comparing strings without StringComparison 216 hits
📄 src\WalkingTec.Mvvm.Core\ConfigOptions\Configs.cs (line 81)
78 {
79 if (_hasMainHost == null)
80 {
81 _mainHost = Domains?.Where(x => x.Key.ToLower() == "mainhost").Select(x => x.Value.Address).FirstOrDefault();
82 _hasMainHost = !string.IsNullOrEmpty(_mainHost);
83 }
84 return _hasMainHost == true;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\WalkingTec.Mvvm.Core\ConfigOptions\Configs.cs (line 93)
90 {
91 get
92 {
93 _mainHost = Domains?.Where(x => x.Key.ToLower() == "mainhost").Select(x => x.Value.Address).FirstOrDefault();
94 if(_mainHost != null)
95 {
96 _mainHost = _mainHost.Trim();
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS056 HttpRequest.Form read synchronously 52 hits
📄 src\WalkingTec.Mvvm.Core\WTMContext.cs (line 931)
928 }
929 if (HttpContext.Request.HasFormContentType)
930 {
931 var f = HttpContext.Request.Form;
932 foreach (var key in f.Keys)
933 {
934 if (rv.FC.Keys.Contains(key) == false)
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
📄 src\WalkingTec.Mvvm.Mvc\Helper\RequestExtension.cs (line 34)
31 if(request.HasFormContentType == true)
32 {
33 Dictionary<string, string> data = new Dictionary<string, string>();
34 foreach (var item in request.Form)
35 {
36 data.Add(item.Key, item.Value);
37 }
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
SS057 Collection manipulated during traversal 28 hits
📄 demo\WalkingTec.Mvvm.BlazorDemo\WalkingTec.Mvvm.BlazorDemo.ViewModel\FrameworkRoleVMs\FrameworkRoleMDVM2.cs (line 54)
51 {
52 if (topdata[i].TenantAllowed == false || (topdata[i].Url != null && ct.EnableSub == false && topdata[i].Url.ToLower().Contains("frameworktenant")))
53 {
54 topdata.RemoveAt(i);
55 i--;
56 continue;
57 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 demo\WalkingTec.Mvvm.BlazorDemo\WalkingTec.Mvvm.BlazorDemo.ViewModel\FrameworkRoleVMs\FrameworkRoleMDVM2.cs (line 63)
60 {
61 if (topdata[i].Url != null && new Regex("^" + au + "[/\\?]?", RegexOptions.IgnoreCase).IsMatch(topdata[i].Url))
62 {
63 topdata.RemoveAt(i);
64 i--;
65 break;
66 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 242 hits
📄 src\WalkingTec.Mvvm.Core\BaseVM.cs (line 323)
320 var p = this;
321 while (p != null && string.IsNullOrEmpty(p.PropertyNameInParent)==false)
322 {
323 rv = p.PropertyNameInParent + "." + rv;
324 p = p.ParentVM;
325 }
326 return rv;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\WalkingTec.Mvvm.Core\BaseImportVM.cs (line 430)
427 {
428 //保存子表字段信息稍后处理
429 ParentEntity.Add(ep.FieldName, ep);
430 ParentEntityValues += ep.Value;
431 }
432 }
433 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 62 hits
📄 demo\WalkingTec.Mvvm.BlazorDemo\WalkingTec.Mvvm.BlazorDemo.ViewModel\FrameworkUserVms\FrameworkUserVM.cs (line 40)
37
38 public override async Task DoAddAsync()
39 {
40 using (var trans = DC.BeginTransaction())
41 {
42 if (SelectedRolesCodes != null)
43 {
💬 IDbContextTransaction can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 demo\WalkingTec.Mvvm.BlazorDemo\WalkingTec.Mvvm.BlazorDemo.ViewModel\FrameworkGroupVMs\FrameworkGroupVM.cs (line 48)
45
46 public override async Task DoDeleteAsync()
47 {
48 using (var tran = DC.BeginTransaction())
49 {
50 try
51 {
💬 IDbContextTransaction can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 12 hits
📄 src\WalkingTec.Mvvm.Core\Support\Quartz\WtmJob.cs (line 13)
10{
11 public class WtmJob : IJob, IDisposable
12 {
13 private IServiceScope _ss;
14 private WTMContext _wtm;
15 protected WTMContext Wtm
16 {
💬 Disposable field _ss in type WtmJob is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\WalkingTec.Mvvm.Core\Support\Quartz\WtmJob.cs (line 14)
11 public class WtmJob : IJob, IDisposable
12 {
13 private IServiceScope _ss;
14 private WTMContext _wtm;
15 protected WTMContext Wtm
16 {
17 get
💬 Disposable field _wtm in type WtmJob is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

ModernWpf

1576 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 8 hits
📄 samples\MahAppsSample\ControlPages\SimpleTimePickerPage.xaml.cs (line 22)
19
20 private void SetValueToNow_Click(object sender, RoutedEventArgs e)
21 {
22 TimePicker.SelectedDateTime = DateTime.Now;
23 }
24
25 private void ClearValue_Click(object sender, RoutedEventArgs e)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 samples\MahAppsSample\ControlPages\SimpleTimePickerPage.xaml.cs (line 22)
19
20 private void SetValueToNow_Click(object sender, RoutedEventArgs e)
21 {
22 TimePicker.SelectedDateTime = DateTime.Now;
23 }
24
25 private void ClearValue_Click(object sender, RoutedEventArgs e)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 168 hits
📄 ModernWpf.Controls\Repeater\Layouts\UniformGridLayout\UniformGridLayoutState.cs (line 104)
101
102 var usedSpace = (numItemsPerColumn * (itemSizeMinor + minorItemSpacing)) - minorItemSpacing;
103 var remainingSpace = (int)(availableSizeMinor - usedSpace);
104 extraMinorPixelsForEachItem = remainingSpace / ((int)numItemsPerColumn);
105 }
106
107 if (stretch == UniformGridLayoutItemsStretch.Fill)
💬 The operands in the divisive expression remainingSpace / ((int)numItemsPerColumn) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 ModernWpf.Controls\Repeater\Layouts\UniformGridLayout\UniformGridLayout.cs (line 284)
281 int itemsPerLine = (int)Math.Min( // note use of unsigned ints
282 Math.Max(1u, (uint)OM.Minor(availableSize) / GetMinorSizeWithSpacing(context)),
283 Math.Max(1u, m_maximumRowsOrColumns));
284 int indexOfFirstInLine = (targetIndex / itemsPerLine) * itemsPerLine;
285 index = indexOfFirstInLine;
286 var state = GetAsGridState(context.LayoutState);
287 offset = OM.MajorStart(GetLayoutRectForDataIndex(availableSize, indexOfFirstInLine, state.FlowAlgorithm.LastExtent, context));
💬 The operands in the divisive expression targetIndex / itemsPerLine are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 16 hits
📄 ModernWpf.SampleApp\ControlPages\ListView2Page.xaml.cs (line 96)
93 {
94 var item = contacts3Filtered[i];
95 // If contact is not in the filtered argument list, remove it from the ListView's source.
96 if (!filteredData.Contains(item))
97 {
98 contacts3Filtered.Remove(item);
99 }
💬 Type Contact is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 ModernWpf.SampleApp\ControlPages\ListView2Page.xaml.cs (line 96)
93 {
94 var item = contacts3Filtered[i];
95 // If contact is not in the filtered argument list, remove it from the ListView's source.
96 if (!filteredData.Contains(item))
97 {
98 contacts3Filtered.Remove(item);
99 }
💬 Type Contact is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 48 hits
📄 ModernWpf\Standard\NativeMethods.cs (line 184)
181
182 public override int GetHashCode()
183 {
184 return (_left << 16 | Utility.LOWORD(_right)) ^ (_top << 16 | Utility.LOWORD(_bottom));
185 }
186 }
187
💬 GetHashCode() refers to mutable field _left (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 ModernWpf\Standard\NativeMethods.cs (line 184)
181
182 public override int GetHashCode()
183 {
184 return (_left << 16 | Utility.LOWORD(_right)) ^ (_top << 16 | Utility.LOWORD(_bottom));
185 }
186 }
187
💬 GetHashCode() refers to mutable field _right (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS011 OnPropertyChanged without nameof operator 4 hits
📄 test\ModernWpfTestApp\ApiTests\RepeaterTests\SelectionModelTests.cs (line 1530)
1527 set
1528 {
1529 _intProperty = value;
1530 OnPropertyChanged("IntProperty");
1531 }
1532 }
1533
💬 OnPropertyChanged(IntProperty) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
📄 test\ModernWpfTestApp\ApiTests\RepeaterTests\SelectionModelTests.cs (line 1530)
1527 set
1528 {
1529 _intProperty = value;
1530 OnPropertyChanged("IntProperty");
1531 }
1532 }
1533
💬 OnPropertyChanged(IntProperty) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 240 hits
📄 ModernWpf\MS\Win32\NativeMethodsCLR.cs (line 40)
37
38 // NOTE: this replaces the RECT struct in NativeMethodsCLR.cs because it adds an extra method IsEmpty
39 [StructLayout(LayoutKind.Sequential)]
40 public struct RECT
41 {
42 public int left;
43 public int top;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RECT. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 ModernWpf\Standard\NativeMethods.cs (line 189)
186 }
187
188 [StructLayout(LayoutKind.Sequential)]
189 internal struct SIZE
190 {
191 public int cx;
192 public int cy;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SIZE. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 292 hits
📄 ModernWpf\Controls\Primitives\CornerRadiusFilterConverter.cs (line 18)
15 {
16 CornerRadius result = radius;
17
18 switch (filterKind)
19 {
20 case CornerRadiusFilterKind.Top:
21 result.BottomLeft = 0;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 ModernWpf\Controls\Primitives\CornerRadiusFilterConverter.cs (line 71)
68
69 private double GetDoubleValue(CornerRadius radius, CornerRadiusFilterKind filterKind)
70 {
71 switch (filterKind)
72 {
73 case CornerRadiusFilterKind.TopLeftValue:
74 return radius.TopLeft;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 586 hits
📄 ModernWpf\ThemeResources.cs (line 153)
150 else
151 {
152 var appTheme = RequestedTheme ?? ApplicationTheme.Light;
153 switch (appTheme)
154 {
155 case ApplicationTheme.Light:
156 EnsureLightResources();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 ModernWpf\TitleBar\TitleBarButton.cs (line 292)
289
290 private IntPtr TitleBarButtonFilterMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
291 {
292 switch ((uint)msg)
293 {
294 case WM_NCHITTEST:
295 if (IsMousePositionWithin(lParam))
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 48 hits
📄 test\ModernWpfTestApp\ApiTests\CommonStylesTests.cs (line 169)
166 }
167 }
168
169 public void DumpThemeResources()
170 {
171 RunOnUIThread.Execute(() =>
172 {
💬 Method DumpThemeResources might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 test\ModernWpfTestApp\ApiTests\RepeaterTests\ViewportTests.cs (line 100)
97 }
98
99 // [TestMethod] Temporarily disabled for bug 18866003
100 public void ValidateItemsRepeaterScrollHostScenario()
101 {
102 var realizationRects = new List<Rect>();
103 var scrollViewer = (ScrollViewer)null;
💬 Method ValidateItemsRepeaterScrollHostScenario might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS023 Exception thrown from property getter 90 hits
📄 ModernWpf.Controls\Common\EmptyEnumerator.cs (line 62)
59 {
60#pragma warning disable 6503 // "Property get methods should not throw exceptions."
61
62 throw new InvalidOperationException();
63
64#pragma warning restore 6503
65 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 ModernWpf.Controls\Repeater\Layouts\VirtualLayoutContextAdapter.cs (line 96)
93 }
94 else
95 {
96 throw new InvalidOperationException();
97 }
98 }
99 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 12 hits
📄 ModernWpf.SampleApp\Data\DataGridDataSource.cs (line 31)
28 {
29 while (!sr.EndOfStream)
30 {
31 string line = sr.ReadLine();
32 string[] values = line.Split(',');
33
34 _items.Add(
💬 Async overload available for StreamReader.ReadLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 ModernWpf.SampleApp\Data\DataGridDataSource.cs (line 31)
28 {
29 while (!sr.EndOfStream)
30 {
31 string line = sr.ReadLine();
32 string[] values = line.Split(',');
33
34 _items.Add(
💬 Async overload available for StreamReader.ReadLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 test\ModernWpfTestApp\Utilities\TopLevelTestPageAttribute.cs (line 7)
4using System;
5namespace MUXControlsTestApp
6{
7 public class TopLevelTestPageAttribute : Attribute
8 {
9 public string Name { get; set; } = "NoName";
10
💬 TopLevelTestPageAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 test\ModernWpfTestApp\Utilities\TopLevelTestPageAttribute.cs (line 7)
4using System;
5namespace MUXControlsTestApp
6{
7 public class TopLevelTestPageAttribute : Attribute
8 {
9 public string Name { get; set; } = "NoName";
10
💬 TopLevelTestPageAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS051 Locking on mutable reference 8 hits
📄 test\ModernWpfTestApp\App.xaml.cs (line 72)
69 public static void RunAfterSplashScreenDismissed(Action action)
70 {
71 var app = Application.Current as App;
72 lock (app._actionsToRunAfterSplashScreenDismissedAndRootIsCreated)
73 {
74 if (app._isSplashScreenDismissed && app._isRootCreated)
75 {
💬 A lock was obtained on _actionsToRunAfterSplashScreenDismissedAndRootIsCreated but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 test\ModernWpfTestApp\App.xaml.cs (line 87)
84
85 private void SplashScreenDismissedAndRootCreated()
86 {
87 lock (_actionsToRunAfterSplashScreenDismissedAndRootIsCreated)
88 {
89 foreach (var action in _actionsToRunAfterSplashScreenDismissedAndRootIsCreated)
90 {
💬 A lock was obtained on _actionsToRunAfterSplashScreenDismissedAndRootIsCreated but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 24 hits
📄 ModernWpf.Controls\Repeater\ItemsRepeater\ViewManager.cs (line 193)
190
191 if (!virtInfo.IsPinned)
192 {
193 m_pinnedPool.RemoveAt(i);
194 --i;
195
196 // Pinning was the only thing keeping this element alive.
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 ModernWpf.Controls\Repeater\ItemsRepeater\ViewManager.cs (line 518)
515
516 if (virtInfo.Index == index)
517 {
518 m_pinnedPool.RemoveAt(i);
519 element = elementInfo.PinnedElement;
520 elementInfo.VirtualizationInfo.MoveOwnershipToLayoutFromPinnedPool();
521
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 28 hits
📄 ModernWpf.Controls\Repeater\Common\IndexPath.cs (line 104)
101 string result = "R";
102 foreach (int index in m_path)
103 {
104 result += ".";
105 result += index;
106 }
107
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 ModernWpf.Controls\Repeater\Common\IndexPath.cs (line 105)
102 foreach (int index in m_path)
103 {
104 result += ".";
105 result += index;
106 }
107
108 return result;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

FluentFTP

1576 total diagnostics across 14 rules

SS001 Async method with void return type 14 hits
📄 FluentFTP\Monitors\AsyncFtpMonitor.cs (line 60)
57 /// <summary>
58 /// Polls the FTP folder for changes
59 /// </summary>
60 protected virtual async void PollFolder(object state) {
61 try {
62
63 // exit if not connected
💬 Method PollFolder is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 FluentFTP\Monitors\AsyncFtpMonitor.cs (line 60)
57 /// <summary>
58 /// Polls the FTP folder for changes
59 /// </summary>
60 protected virtual async void PollFolder(object state) {
61 try {
62
63 // exit if not connected
💬 Method PollFolder is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 280 hits
📄 FluentFTP\Streams\FtpSocketStream.cs (line 1209)
1206 throw new InvalidOperationException("The base network stream is null.");
1207 }
1208
1209 var authStart = DateTime.Now;
1210 string authType, cipherSuite;
1211
1212 if (Client.Config.CustomStream != null) {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 FluentFTP\Streams\FtpSocketStream.cs (line 1297)
1294 }
1295
1296 if (Client.Config.LogDurations) {
1297 var authDuration = DateTime.Now.Subtract(authStart);
1298 ((IInternalFtpClient)Client).LogStatus(FtpTraceLevel.Info, "FTPS authentication successful, lib = " + authType + ", cipher suite = " + cipherSuite + " [" + authDuration.ToShortString() + "]");
1299 }
1300 else {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 196 hits
📄 FluentFTP\Client\Modules\FileTransferModule.cs (line 43)
40 // reduce chunk size to optimize rate control
41 const int chunkSizeMin = 64;
42 while (chunkSize > chunkSizeMin) {
43 var chunkLenInMs = 1000L * chunkSize / rateLimitBytes;
44 if (chunkLenInMs <= rateControlResolution) {
45 break;
46 }
💬 The operands in the divisive expression 1000L * chunkSize / rateLimitBytes are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 FluentFTP\Client\BaseClient\GetReply.cs (line 148)
145 else {
146 if (elapsedTime > (previousElapsedTime + 1000)) {
147 previousElapsedTime = elapsedTime;
148 LogWithPrefix(FtpTraceLevel.Verbose, "Waiting - " + ((timeOut - elapsedTime) / 1000).ToString() + " seconds left");
149 // if we have more then 5 seconds left, tickle the server some more
150 if (timeOut - elapsedTime >= 5000) {
151 LogWithPrefix(FtpTraceLevel.Verbose, "Sending NOOP (<-GetReply)");
💬 The operands in the divisive expression (timeOut - elapsedTime) / 1000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 56 hits
📄 FluentFTP\Model\FtpReply.cs (line 9)
6 /// <summary>
7 /// Represents a reply to an event on the server
8 /// </summary>
9 public struct FtpReply {
10 /// <summary>
11 /// The type of response received from the last command executed
12 /// </summary>
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FtpReply. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 FluentFTP\Model\FtpLogEntry.cs (line 7)
4 /// <summary>
5 /// Metadata of a single log message.
6 /// </summary>
7 public readonly struct FtpLogEntry {
8 public FtpTraceLevel Severity { get; }
9 public string Message { get; }
10 public Exception Exception { get; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FtpLogEntry. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 168 hits
📄 FluentFTP\Client\AsyncClient\MoveDirectory.cs (line 41)
38 if (existsMode != FtpRemoteExists.NoCheck) {
39 bool destExists = await DirectoryExists(dest, token);
40 if (destExists) {
41 switch (existsMode) {
42 case FtpRemoteExists.Overwrite:
43 case FtpRemoteExists.OverwriteInPlace:
44 await DeleteDirectory(dest, token);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 FluentFTP\Client\SyncClient\MoveDirectory.cs (line 40)
37 if (existsMode != FtpRemoteExists.NoCheck) {
38 var destExists = DirectoryExists(dest);
39 if (destExists) {
40 switch (existsMode) {
41 case FtpRemoteExists.Overwrite:
42 case FtpRemoteExists.OverwriteInPlace:
43 DeleteDirectory(dest);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 252 hits
📄 FluentFTP\Client\Modules\ServerFeatureModule.cs (line 127)
124
125 if ((m = Regex.Match(featName, @"^HASH\s+(?<types>.*)$")).Success) {
126 foreach (var type in m.Groups["types"].Value.Split(';')) {
127 switch (type.ToUpper().Trim()) {
128 case "SHA-1":
129 case "SHA-1*":
130 hashAlgorithms |= FtpHashAlgorithm.SHA1;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 FluentFTP\Client\AsyncClient\MoveDirectory.cs (line 41)
38 if (existsMode != FtpRemoteExists.NoCheck) {
39 bool destExists = await DirectoryExists(dest, token);
40 if (destExists) {
41 switch (existsMode) {
42 case FtpRemoteExists.Overwrite:
43 case FtpRemoteExists.OverwriteInPlace:
44 await DeleteDirectory(dest, token);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 28 hits
📄 FluentFTP\Client\BaseClient\Properties.cs (line 286)
283 if (m_stream == null || !m_stream.IsConnected) {
284 if (Config.SelfConnectMode == FtpSelfConnectMode.Never ||
285 ((Status.ConnectCount == 0) && Config.SelfConnectMode == FtpSelfConnectMode.OnConnectionLost)) {
286 throw new FtpException("A call to Connect(...) is needed prior to calling this API!");
287 }
288
289 if (ClientType is "AsyncFtpClient") {
💬 An exception is thrown from the getter of property Capabilities (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 FluentFTP\Client\BaseClient\Properties.cs (line 324)
321 if (m_stream == null || !m_stream.IsConnected) {
322 if (Config.SelfConnectMode == FtpSelfConnectMode.Never ||
323 ((Status.ConnectCount == 0) && Config.SelfConnectMode == FtpSelfConnectMode.OnConnectionLost)) {
324 throw new FtpException("A call to Connect(...) is needed prior to calling this API!");
325 }
326
327 if (ClientType is "AsyncFtpClient") {
💬 An exception is thrown from the getter of property HashAlgorithms (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 262 hits
📄 FluentFTP\Client\Modules\ConnectModule.cs (line 256)
253 var permaEx = IsPermanentConnectionFailure(ex, config.AbortOnTimeout);
254 if (permaEx != null) {
255 if (config.CloneConnection) {
256 conn.Dispose();
257 }
258
259 // rethrow permanent failures so caller can be made aware of it
💬 Async overload available for AsyncFtpClient.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 FluentFTP\Client\Modules\ConnectModule.cs (line 288)
285
286 Exit:
287 if (config.CloneConnection) {
288 conn.Dispose();
289 }
290
291 return results;
💬 Async overload available for AsyncFtpClient.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 10 hits
📄 FluentFTP\Streams\FtpSocketStream.cs (line 904)
901
902 if (!Client.Status.CachedHostIpads.TryGetValue(host, out IPAddress[] ipads)) {
903#if NETSTANDARD || NET5_0_OR_GREATER
904 ipads = Dns.GetHostAddressesAsync(host).Result;
905#else
906 ipads = Dns.GetHostAddresses(host);
907#endif
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 FluentFTP\Streams\FtpSocketStream.cs (line 904)
901
902 if (!Client.Status.CachedHostIpads.TryGetValue(host, out IPAddress[] ipads)) {
903#if NETSTANDARD || NET5_0_OR_GREATER
904 ipads = Dns.GetHostAddressesAsync(host).Result;
905#else
906 ipads = Dns.GetHostAddresses(host);
907#endif
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS040 Unused result on immutable object 14 hits
📄 FluentFTP\Helpers\Parsers\NonStopParser.cs (line 59)
56 var owner = values[5] + values[6];
57 var permissions = "";
58 if (values.Length > 7) {
59 values[7].Trim(TrimValues);
60 }
61
62 // create a new list item object with the parsed metadata
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
📄 FluentFTP\Helpers\Parsers\NonStopParser.cs (line 59)
56 var owner = values[5] + values[6];
57 var permissions = "";
58 if (values.Length > 7) {
59 values[7].Trim(TrimValues);
60 }
61
62 // create a new list item object with the parsed metadata
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
SS049 Comparing strings without StringComparison 14 hits
📄 FluentFTP\Helpers\Parsers\WindowsParser.cs (line 44)
41 timeColon = true;
42 }
43
44 if (values[2].ToUpper() == DirectoryMarker || char.IsDigit(values[2][0])) {
45 dirOrFile = true;
46 }
47 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 FluentFTP\Helpers\Parsers\WindowsParser.cs (line 44)
41 timeColon = true;
42 }
43
44 if (values[2].ToUpper() == DirectoryMarker || char.IsDigit(values[2][0])) {
45 dirOrFile = true;
46 }
47 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 182 hits
📄 FluentFTP\Client\BaseClient\GetReply.cs (line 193)
190 continue;
191 }
192
193 sequence += "," + response.Split(' ')[0];
194
195 if (exhaustNoop &&
196 ((response.StartsWith("200") && (response.IndexOf("NOOP", StringComparison.OrdinalIgnoreCase) >= 0)) ||
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 FluentFTP\Client\BaseClient\GetReply.cs (line 215)
212 }
213 }
214
215 reply.InfoMessages += response + "\n";
216 lines++;
217
218 if (linesExpected > 0 && lines >= linesExpected) {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 24 hits
📄 FluentFTP\Client\AsyncClient\DownloadBytes.cs (line 38)
35 LogFunction(nameof(DownloadBytes), new object[] { remotePath });
36
37 // download the file from the server
38 using (var outStream = new MemoryStream()) {
39 var ok = await DownloadFileInternalAsync(null, remotePath, outStream, restartPosition, progress, token, new FtpProgress(1, 0), 0, false, stopPosition);
40 return ok ? outStream.ToArray() : null;
41 }
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 FluentFTP\Client\AsyncClient\UploadBytes.cs (line 43)
40 LogFunction(nameof(UploadBytes), new object[] { remotePath, existsMode, createRemoteDir });
41
42 // write the file onto the server
43 using (var ms = new MemoryStream(fileData)) {
44 ms.Position = 0;
45 return await UploadFileInternalAsync(ms, null, remotePath, createRemoteDir, existsMode, false, false, progress, token, new FtpProgress(1, 0));
46 }
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 76 hits
📄 FluentFTP\Streams\FtpSocketStream.cs (line 33)
30 /// <summary>
31 /// The client this stream is associated with
32 /// </summary>
33 public readonly BaseFtpClient Client;
34
35 /// <summary>
36 /// This stream connection to be associated with this client
💬 Disposable field Client in type FtpSocketStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 FluentFTP\Streams\FtpDataStream.cs (line 22)
19 set => m_commandStatus = value;
20 }
21
22 private BaseFtpClient m_control = null;
23
24 /// <summary>
25 /// Gets or sets the control connection for this data stream. Setting
💬 Disposable field m_control in type FtpDataStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

opencvsharp

1358 total diagnostics across 14 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 src\tools\OpenCvSharp.ReleaseMaker\Packer.cs (line 198)
195
196 private static string GetBinaryDstDirName(string version)
197 {
198 var date = DateTime.Now.ToString("yyyyMMdd");
199 return $"OpenCvSharp-{version}-{date}";
200 }
201
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\tools\OpenCvSharp.ReleaseMaker\Packer.cs (line 198)
195
196 private static string GetBinaryDstDirName(string version)
197 {
198 var date = DateTime.Now.ToString("yyyyMMdd");
199 return $"OpenCvSharp-{version}-{date}";
200 }
201
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 12 hits
📄 src\OpenCvSharp\Cv2\Cv2_core.cs (line 1006)
1003 NativeMethods.HandleException(
1004 NativeMethods.core_mixChannels(
1005 srcPtr, (uint)src.Length, dstPtr, (uint)dst.Length,
1006 fromTo, (uint)(fromTo.Length / 2)));
1007
1008 GC.KeepAlive(src);
1009 GC.KeepAlive(dst);
💬 The operands in the divisive expression fromTo.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\OpenCvSharp\Modules\core\Mat\Mat.cs (line 4148)
4145 /// <typeparam name="T"></typeparam>
4146 /// <returns></returns>
4147 public unsafe Span<T> AsSpan<T>() where T : unmanaged
4148 => IsContinuous() ? new Span<T>(DataPointer, (int)Total() * ElemSize() / sizeof(T)) : [];
4149
4150 #endregion
4151}
💬 The operands in the divisive expression (int)Total() * ElemSize() / sizeof(T) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 6 hits
📄 src\OpenCvSharp\Fundamentals\ResourcesTracker.cs (line 25)
22
23 lock (asyncLock)
24 {
25 trackedObjects.Add(obj);
26 }
27 return obj;
28 }
💬 Type DisposableObject is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\OpenCvSharp\Fundamentals\ResourcesTracker.cs (line 25)
22
23 lock (asyncLock)
24 {
25 trackedObjects.Add(obj);
26 }
27 return obj;
28 }
💬 Type DisposableObject is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 588 hits
📄 src\OpenCvSharp\Modules\imgproc\Model\CircleSegment.cs (line 98)
95 /// <returns>An integer value that specifies a hash value for this object.</returns>
96 public override int GetHashCode()
97 {
98 return Center.GetHashCode() + Radius.GetHashCode();
99 }
100
101 /// <summary>
💬 GetHashCode() refers to mutable field Center (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\OpenCvSharp\Modules\imgproc\Model\CircleSegment.cs (line 98)
95 /// <returns>An integer value that specifies a hash value for this object.</returns>
96 public override int GetHashCode()
97 {
98 return Center.GetHashCode() + Radius.GetHashCode();
99 }
100
101 /// <summary>
💬 GetHashCode() refers to mutable field Radius (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 102 hits
📄 src\OpenCvSharp\Modules\calib3d\UsacParams.cs (line 39)
36
37#pragma warning disable CA1815
38[StructLayout(LayoutKind.Sequential)]
39public struct WUsacParams
40{
41 public double Confidence;
42 public int IsParallel;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct WUsacParams. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\OpenCvSharp\Modules\core\RNG.cs (line 12)
9/// </summary>
10/// <remarks>operations.hpp</remarks>
11[StructLayout(LayoutKind.Sequential)]
12public struct RNG : IEquatable<RNG>
13{
14 private ulong state;
15
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RNG. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 6 hits
📄 src\OpenCvSharp\Modules\core\InputArray.cs (line 515)
512 return MatType.CV_64FC1;
513#else
514 var code = System.Type.GetTypeCode(t);
515 switch (code)
516 {
517 case TypeCode.Byte:
518 return MatType.CV_8UC1;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\OpenCvSharp\Modules\core\InputArray.cs (line 515)
512 return MatType.CV_64FC1;
513#else
514 var code = System.Type.GetTypeCode(t);
515 switch (code)
516 {
517 case TypeCode.Byte:
518 return MatType.CV_8UC1;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 6 hits
📄 src\OpenCvSharp\Modules\core\InputArray.cs (line 515)
512 return MatType.CV_64FC1;
513#else
514 var code = System.Type.GetTypeCode(t);
515 switch (code)
516 {
517 case TypeCode.Byte:
518 return MatType.CV_8UC1;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\OpenCvSharp\Modules\core\InputArray.cs (line 515)
512 return MatType.CV_64FC1;
513#else
514 var code = System.Type.GetTypeCode(t);
515 switch (code)
516 {
517 case TypeCode.Byte:
518 return MatType.CV_8UC1;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS022 Exception thrown from implicit operator 6 hits
📄 src\OpenCvSharp\Modules\core\MatExpr.cs (line 57)
54 {
55#pragma warning disable CA1065 // TODO
56 if (self is null)
57 throw new ArgumentNullException(nameof(self));
58#pragma warning restore CA1065
59 return self.ToMat();
60 }
💬 An exception is thrown from implicit operator Mat in type MatExpr (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
📄 src\OpenCvSharp\Modules\core\MatExpr.cs (line 57)
54 {
55#pragma warning disable CA1065 // TODO
56 if (self is null)
57 throw new ArgumentNullException(nameof(self));
58#pragma warning restore CA1065
59 return self.ToMat();
60 }
💬 An exception is thrown from implicit operator Mat in type MatExpr (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
SS023 Exception thrown from property getter 36 hits
📄 src\OpenCvSharp\Modules\core\Algorithm.cs (line 53)
50 get
51 {
52 if (ptr == IntPtr.Zero)
53 throw new ObjectDisposedException(GetType().Name);
54
55 NativeMethods.HandleException(
56 NativeMethods.core_Algorithm_empty(ptr, out var ret));
💬 An exception is thrown from the getter of property Empty (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\OpenCvSharp\Modules\imgproc\GeneralizedHough.cs (line 19)
16 get
17 {
18 if (ptr == IntPtr.Zero)
19 throw new ObjectDisposedException(GetType().Name);
20 NativeMethods.HandleException(
21 NativeMethods.imgproc_GeneralizedHough_getCannyLowThresh(ptr, out var ret));
22 GC.KeepAlive(this);
💬 An exception is thrown from the getter of property CannyLowThresh (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS030 Exception thrown from Equals 6 hits
📄 src\OpenCvSharp\Modules\core\Mat\Mat.cs (line 1116)
1113 public MatExpr Equals(Mat m)
1114 {
1115 if (m is null)
1116 throw new ArgumentNullException(nameof(m));
1117
1118 NativeMethods.HandleException(
1119 NativeMethods.core_Mat_operatorEQ_MatMat(ptr, m.CvPtr, out var ret));
💬 An exception is thrown from the Equals(Mat) method in type Mat (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
📄 src\OpenCvSharp\Modules\core\Mat\Mat.cs (line 1116)
1113 public MatExpr Equals(Mat m)
1114 {
1115 if (m is null)
1116 throw new ArgumentNullException(nameof(m));
1117
1118 NativeMethods.HandleException(
1119 NativeMethods.core_Mat_operatorEQ_MatMat(ptr, m.CvPtr, out var ret));
💬 An exception is thrown from the Equals(Mat) method in type Mat (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
SS033 Async overload is available 4 hits
📄 src\tools\OpenCvSharp.NupkgBetaRemover\Program.cs (line 34)
31 using (var nuspecContentStream = nuspecEntry.Open())
32 using (var nuspecContentStreamReader = new StreamReader(nuspecContentStream, Encoding.UTF8))
33 {
34 nuspecContent = nuspecContentStreamReader.ReadToEnd();
35 }
36
37 nuspecContent = Regex.Replace(nuspecContent, @"-beta-?\d*</version>", "</version>");
💬 Async overload available for StreamReader.ReadToEnd (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\tools\OpenCvSharp.NupkgBetaRemover\Program.cs (line 48)
45 using (var nuspecContentStream = nuspecEntry.Open())
46 using (var nuspecContentStreamWriter = new StreamWriter(nuspecContentStream, Encoding.UTF8))
47 {
48 nuspecContentStreamWriter.Write(nuspecContent);
49 }
50 }
51
💬 Async overload available for StreamWriter.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS058 String concatenated in a loop 8 hits
📄 src\tools\OpenCvSharp.NupkgBetaRemover\Program.cs (line 43)
40 nuspecContent = Regex.Replace(nuspecContent, @"(?<=<dependency.*version="")(?<version>\d{1,2}\.\d{1,2}\.\d{1,2}\.\d{8})(?<betaVersion>-beta-?\d*)",
41 match => match.Groups["version"].Value);
42 }
43 nuspecContent += new string(' ', 1000);
44
45 using (var nuspecContentStream = nuspecEntry.Open())
46 using (var nuspecContentStreamWriter = new StreamWriter(nuspecContentStream, Encoding.UTF8))
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\OpenCvSharp\Modules\videoio\FourCC.cs (line 116)
113 // padding
114 while (code.Length < 4)
115 {
116 code += " ";
117 }
118
119 var value = VideoWriter.FourCC(code[0], code[1], code[2], code[3]);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 6 hits
📄 src\tools\OpenCvSharp.NupkgBetaRemover\Program.cs (line 31)
28 continue;
29
30 string nuspecContent;
31 using (var nuspecContentStream = nuspecEntry.Open())
32 using (var nuspecContentStreamReader = new StreamReader(nuspecContentStream, Encoding.UTF8))
33 {
34 nuspecContent = nuspecContentStreamReader.ReadToEnd();
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\tools\OpenCvSharp.NupkgBetaRemover\Program.cs (line 45)
42 }
43 nuspecContent += new string(' ', 1000);
44
45 using (var nuspecContentStream = nuspecEntry.Open())
46 using (var nuspecContentStreamWriter = new StreamWriter(nuspecContentStream, Encoding.UTF8))
47 {
48 nuspecContentStreamWriter.Write(nuspecContent);
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 570 hits
📄 src\OpenCvSharp\Modules\barcode\BarcodeDetector.cs (line 12)
9/// </summary>
10public class BarcodeDetector : DisposableCvObject
11{
12 private Ptr? objectPtr;
13
14 internal BarcodeDetector(IntPtr ptr)
15 {
💬 Disposable field objectPtr in type BarcodeDetector is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\OpenCvSharp\Modules\ml\NormalBayesClassifier.cs (line 10)
7/// </summary>
8public class NormalBayesClassifier : StatModel
9{
10 private Ptr? ptrObj;
11
12 /// <summary>
13 /// Creates instance by raw pointer cv::ml::NormalBayesClassifier*
💬 Disposable field ptrObj in type NormalBayesClassifier is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Eto

1344 total diagnostics across 12 rules

SS003 Integer divided by integer causing implicit rounding 216 hits
📄 src\Eto\Drawing\BitmapData.cs (line 69)
66 _scanWidth = scanWidth;
67 _bitsPerPixel = bitsPerPixel;
68 _controlObject = controlObject;
69 _bytesPerPixel = (bitsPerPixel + 7) / 8;
70 _premultipliedAlpha = premultipliedAlpha;
71 }
72
💬 The operands in the divisive expression (bitsPerPixel + 7) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Eto\Drawing\Size.cs (line 260)
257 /// <returns>A new instance of a Size struct with the width and height of <paramref name="size"/> divided by <paramref name="factor"/></returns>
258 public static Size operator / (Size size, int factor)
259 {
260 return new Size (size.Width / factor, size.Height / factor);
261 }
262
263 /// <summary>
💬 The operands in the divisive expression size.Width / factor are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 8 hits
📄 src\Eto\Forms\Application.cs (line 260)
257 {
258 var window = (Window)sender;
259 window.Closed -= HandleClosed;
260 if (windows.Contains(window))
261 windows.Remove(window);
262 }
263
💬 Type Window is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Eto\Forms\Application.cs (line 260)
257 {
258 var window = (Window)sender;
259 window.Closed -= HandleClosed;
260 if (windows.Contains(window))
261 windows.Remove(window);
262 }
263
💬 Type Window is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 8 hits
📄 src\Eto\Forms\FileFilter.cs (line 9)
6/// <remarks>
7/// Each filter defines an option for the user to limit the selection of files in the dialog.
8/// </remarks>
9public class FileFilter
10{
11 /// <summary>
12 /// Initializes a new instance of the <see cref="FileFilter"/> class.
💬 Equals() and GetHashcode() must be implemented together on FileFilter (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\Eto\Forms\FileFilter.cs (line 9)
6/// <remarks>
7/// Each filter defines an option for the user to limit the selection of files in the dialog.
8/// </remarks>
9public class FileFilter
10{
11 /// <summary>
12 /// Initializes a new instance of the <see cref="FileFilter"/> class.
💬 Equals() and GetHashcode() must be implemented together on FileFilter (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 408 hits
📄 src\Eto\Drawing\ColorCMYK.cs (line 171)
168 /// </summary>
169 public override int GetHashCode ()
170 {
171 return C.GetHashCode () ^ M.GetHashCode () ^ Y.GetHashCode () ^ K.GetHashCode () ^ A.GetHashCode ();
172 }
173
174 /// <summary>
💬 GetHashCode() refers to mutable property C (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Eto\Drawing\ColorCMYK.cs (line 171)
168 /// </summary>
169 public override int GetHashCode ()
170 {
171 return C.GetHashCode () ^ M.GetHashCode () ^ Y.GetHashCode () ^ K.GetHashCode () ^ A.GetHashCode ();
172 }
173
174 /// <summary>
💬 GetHashCode() refers to mutable property M (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 80 hits
📄 src\Eto\EventLookup.cs (line 9)
6 static readonly Assembly etoAssembly = typeof(EventLookup).Assembly;
7 static readonly Dictionary<Type, string[]> externalEvents = new Dictionary<Type, string[]>();
8
9 struct EventDeclaration
10 {
11 public readonly string Identifier;
12 public readonly MethodInfo Method;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EventDeclaration. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Eto\Drawing\ColorCMYK.cs (line 13)
10/// </remarks>
11/// <copyright>(c) 2014 by Curtis Wensley</copyright>
12/// <license type="BSD-3">See LICENSE for full terms</license>
13public struct ColorCMYK : IEquatable<ColorCMYK>
14{
15 /// <summary>
16 /// Cyan component
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ColorCMYK. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 48 hits
📄 src\Eto\Forms\ThemedControls\ThemedSegmentedButtonHandler.cs (line 228)
225 {
226 selectionMode = value;
227
228 switch (value)
229 {
230 case SegmentedSelectionMode.None:
231 ClearSelection();
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Eto\Forms\Controls\TreeItem.cs (line 50)
47 return children;
48 children = new TreeItemCollection();
49 children.CollectionChanged += (sender, e) => {
50 switch (e.Action)
51 {
52 case NotifyCollectionChangedAction.Reset:
53 foreach (var item in children)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 96 hits
📄 src\Eto\CollectionChangedHandler.cs (line 280)
277 private protected virtual void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
278 {
279 BeginUpdates();
280 switch (e.Action)
281 {
282 case NotifyCollectionChangedAction.Add:
283 if (e.NewStartingIndex != -1)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Eto\Drawing\DashStyle.cs (line 60)
57 return true;
58 }
59
60 switch (value.ToUpperInvariant())
61 {
62 case "SOLID":
63 style = DashStyles.Solid;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS022 Exception thrown from implicit operator 8 hits
📄 src\Eto\Forms\FileFilter.cs (line 73)
70 {
71 var parts = filter.Split('|');
72 if (parts.Length != 2)
73 throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Filter must be in the form of '<name>|<ext>;<ext>;<ext>;'"), nameof(filter));
74
75 return new FileFilter
76 {
💬 An exception is thrown from implicit operator FileFilter in type FileFilter (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
📄 src\Eto\Forms\FileFilter.cs (line 73)
70 {
71 var parts = filter.Split('|');
72 if (parts.Length != 2)
73 throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Filter must be in the form of '<name>|<ext>;<ext>;<ext>;'"), nameof(filter));
74
75 return new FileFilter
76 {
💬 An exception is thrown from implicit operator FileFilter in type FileFilter (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md)
SS023 Exception thrown from property getter 32 hits
📄 src\Eto\Widget.cs (line 88)
85 get
86 {
87 if (IsDisposed)
88 throw new ObjectDisposedException(GetType().FullName);
89 return _handler;
90 }
91 internal set => _handler = value;
💬 An exception is thrown from the getter of property Handler (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Eto\Platform.cs (line 422)
419 {
420 var message = "Could not detect platform. Are you missing a platform assembly?";
421 if (errors.Count > 1)
422 throw new AggregateException(message, errors);
423 if (errors.Count == 1)
424 throw new InvalidOperationException(message, errors[0]);
425 throw new InvalidOperationException(message);
💬 An exception is thrown from the getter of property Detect (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS044 Attribute must specify [AttributeUsage] 8 hits
📄 src\Eto\PclTypes.cs (line 18)
15 /// Type converter attribute, for type converter compatibility in portable class libraries.
16 /// </summary>
17 [Obsolete("Since 2.5, Use System.ComponentModel.TypeConverterAttribute instead")]
18 public class TypeConverterAttribute : Attribute
19 {
20 /// <summary>
21 /// Gets the name of the type for the type converter of the associated type.
💬 TypeConverterAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\Eto\PclTypes.cs (line 18)
15 /// Type converter attribute, for type converter compatibility in portable class libraries.
16 /// </summary>
17 [Obsolete("Since 2.5, Use System.ComponentModel.TypeConverterAttribute instead")]
18 public class TypeConverterAttribute : Attribute
19 {
20 /// <summary>
21 /// Gets the name of the type for the type converter of the associated type.
💬 TypeConverterAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS058 String concatenated in a loop 8 hits
📄 src\Eto\Drawing\FontConverter.cs (line 90)
87 }
88
89 if (typefaceName != null)
90 familyName += "," + typefaceName;
91
92 typefaceName = cur;
93 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Eto\Drawing\FontConverter.cs (line 90)
87 }
88
89 if (typefaceName != null)
90 familyName += "," + typefaceName;
91
92 typefaceName = cur;
93 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 424 hits
📄 src\Eto\Forms\ThemedControls\ThemedFontPickerHandler.cs (line 8)
5/// </summary>
6public class ThemedFontPickerHandler : ThemedControlHandler<Button, FontPicker, FontPicker.ICallback>, FontPicker.IHandler
7{
8 private Font font;
9 private FontDialog dialog;
10
11 /// <summary>
💬 Disposable field font in type ThemedFontPickerHandler is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Eto\Forms\ThemedControls\ThemedFontPickerHandler.cs (line 9)
6public class ThemedFontPickerHandler : ThemedControlHandler<Button, FontPicker, FontPicker.ICallback>, FontPicker.IHandler
7{
8 private Font font;
9 private FontDialog dialog;
10
11 /// <summary>
12 /// Initializes a new instance of the <see cref="T:Eto.Forms.ThemedControls.ThemedFontPickerHandler"/> class.
💬 Disposable field dialog in type ThemedFontPickerHandler is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Polly

1322 total diagnostics across 10 rules

SS003 Integer divided by integer causing implicit rounding 90 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 136 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 422 hits
No source samples extracted
SS019 Switch is missing default label 24 hits
No source samples extracted
SS033 Async overload is available 318 hits
No source samples extracted
SS034 Accessing Task.Result without await 60 hits
No source samples extracted
SS035 Synchronous task wait instead of await 96 hits
No source samples extracted
SS037 HttpClient instantiated directly 10 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 56 hits
No source samples extracted
SS066 Disposable field is not disposed 110 hits
No source samples extracted

AngleSharp

1318 total diagnostics across 14 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 10 hits
📄 src\AngleSharp\Dom\Events\Event.cs (line 39)
36 {
37 _flags = EventFlags.None;
38 _phase = EventPhase.None;
39 _time = DateTime.Now;
40 _composed = false;
41 }
42
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\AngleSharp\Dom\Events\Event.cs (line 39)
36 {
37 _flags = EventFlags.None;
38 _phase = EventPhase.None;
39 _time = DateTime.Now;
40 _composed = false;
41 }
42
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 60 hits
📄 src\AngleSharp\Text\Punycode.cs (line 346)
343
344 var k = 0u;
345
346 delta = firstTime ? delta / Damp : delta / 2;
347 delta += delta / numPoints;
348
349 for (k = 0; delta > ((PunycodeBase - Tmin) * Tmax) / 2; k += PunycodeBase)
💬 The operands in the divisive expression delta / Damp are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\AngleSharp\Text\Punycode.cs (line 346)
343
344 var k = 0u;
345
346 delta = firstTime ? delta / Damp : delta / 2;
347 delta += delta / numPoints;
348
349 for (k = 0; delta > ((PunycodeBase - Tmin) * Tmax) / 2; k += PunycodeBase)
💬 The operands in the divisive expression delta / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 30 hits
📄 src\AngleSharp\Dom\Internal\NodeList.cs (line 74)
71
72 internal void RemoveAt(Int32 index) => _entries.RemoveAt(index);
73
74 internal Boolean Contains(Node node) => _entries.Contains(node);
75
76 #endregion
77
💬 Type Node is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\AngleSharp\Dom\Internal\MutationHost.cs (line 41)
38
39 public void Register(MutationObserver observer)
40 {
41 if (!_observers.Contains(observer))
42 {
43 _observers.Add(observer);
44 }
💬 Type MutationObserver is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 10 hits
📄 src\AngleSharp\Dom\Internal\Attr.cs (line 13)
10 /// <summary>
11 /// Represents a generic node attribute.
12 /// </summary>
13 public sealed class Attr : IAttr, IConstructableAttr
14 {
15 #region Fields
16
💬 Equals() and GetHashcode() must be implemented together on Attr (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\AngleSharp\Dom\Internal\Attr.cs (line 13)
10 /// <summary>
11 /// Represents a generic node attribute.
12 /// </summary>
13 public sealed class Attr : IAttr, IConstructableAttr
14 {
15 #region Fields
16
💬 Equals() and GetHashcode() must be implemented together on Attr (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 230 hits
📄 src\AngleSharp\Dom\Url.cs (line 444)
441 {
442 unchecked
443 {
444 var hashCode = _fragment != null ? StringComparer.Ordinal.GetHashCode(_fragment) : 0;
445 hashCode = (hashCode * 397) ^ (_query != null ? StringComparer.Ordinal.GetHashCode(_query) : 0);
446 hashCode = (hashCode * 397) ^ (_path != null ? StringComparer.Ordinal.GetHashCode(_path) : 0);
447 hashCode = (hashCode * 397) ^ (_scheme != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(_scheme) : 0);
💬 GetHashCode() refers to mutable field _fragment (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\AngleSharp\Dom\Url.cs (line 444)
441 {
442 unchecked
443 {
444 var hashCode = _fragment != null ? StringComparer.Ordinal.GetHashCode(_fragment) : 0;
445 hashCode = (hashCode * 397) ^ (_query != null ? StringComparer.Ordinal.GetHashCode(_query) : 0);
446 hashCode = (hashCode * 397) ^ (_path != null ? StringComparer.Ordinal.GetHashCode(_path) : 0);
447 hashCode = (hashCode * 397) ^ (_scheme != null ? StringComparer.OrdinalIgnoreCase.GetHashCode(_scheme) : 0);
💬 GetHashCode() refers to mutable field _fragment (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 180 hits
📄 src\AngleSharp\Common\ArrayPoolExtensions.cs (line 14)
11 return new Lease<T>(ArrayPool<T>.Shared, arr, length);
12 }
13
14 internal readonly struct Lease<T> : IDisposable
15 {
16 private readonly ArrayPool<T> _owner;
17 private readonly T[] _data;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Lease. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\AngleSharp\Css\Parser\CssSelectorToken.cs (line 8)
5 /// <summary>
6 /// The CSS selector token.
7 /// </summary>
8 readonly struct CssSelectorToken
9 {
10 #region Fields
11
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CssSelectorToken. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 200 hits
📄 src\AngleSharp\Dom\NodeExtensions.cs (line 429)
426 {
427 var forbidden = false;
428
429 switch (node.NodeType)
430 {
431 case NodeType.Element:
432 forbidden = document.DocumentElement is not null || child is IDocumentType || child.IsFollowedByDoctype();
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\AngleSharp\Html\Parser\HtmlTokenizer.cs (line 2956)
2953 var attributes = tag.Attributes;
2954 State = HtmlParseMode.PCData;
2955
2956 switch (tag.Type)
2957 {
2958 case HtmlTokenType.StartTag:
2959 for (var i = attributes.Count - 1; i > 0; i--)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 370 hits
📄 src\AngleSharp\Html\Parser\Tokens\Struct\StructAttributes.cs (line 25)
22 /// <param name="item">Attribute to add.</param>
23 public void Add(MemoryHtmlAttributeToken item)
24 {
25 switch (_count)
26 {
27 case 0:
28 _t0 = item;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\AngleSharp\Dom\Url.cs (line 722)
719
720 if (index != length)
721 {
722 switch (input[index])
723 {
724 case Symbols.QuestionMark:
725 return ParseQuery(input, index + 1, length);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 20 hits
📄 src\AngleSharp\Io\RequesterExtensions.cs (line 169)
166
167 private static IDownload CheckIntegrity(this CorsRequest cors, IDownload download)
168 {
169 var response = download.Task.Result;
170 var value = cors.Request.Source?.GetAttribute(AttributeNames.Integrity);
171 var integrity = cors.Integrity;
172
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\AngleSharp\Io\RequesterExtensions.cs (line 169)
166
167 private static IDownload CheckIntegrity(this CorsRequest cors, IDownload download)
168 {
169 var response = download.Task.Result;
170 var value = cors.Request.Source?.GetAttribute(AttributeNames.Integrity);
171 var integrity = cors.Integrity;
172
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS048 Locking on discouraged object (string, Type, this) 30 hits
📄 src\AngleSharp\Io\BaseLoader.cs (line 64)
61 /// <param name="download">The download to add.</param>
62 protected virtual void Add(IDownload download)
63 {
64 lock (this)
65 {
66 _downloads.Add(download);
67 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 src\AngleSharp\Io\BaseLoader.cs (line 76)
73 /// <param name="download">The download to remove.</param>
74 protected virtual void Remove(IDownload download)
75 {
76 lock (this)
77 {
78 _downloads.Remove(download);
79 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS057 Collection manipulated during traversal 20 hits
📄 src\AngleSharp\Dom\Internal\NamedNodeMap.cs (line 72)
69 if (name.Is(_items[i].Name))
70 {
71 var attr = _items[i];
72 _items.RemoveAt(i);
73 attr.Container = null;
74
75 if (!suppressMutationObservers)
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\AngleSharp\Dom\Internal\NamedNodeMap.cs (line 96)
93 if (localName.Is(_items[i].LocalName) && namespaceUri.Is(_items[i].NamespaceUri))
94 {
95 var attr = _items[i];
96 _items.RemoveAt(i);
97 attr.Container = null;
98
99 if (!suppressMutationObservers)
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 10 hits
📄 src\AngleSharp\Dom\ElementExtensions.cs (line 1593)
1590 // Recreate selector path
1591 if (!String.IsNullOrEmpty(path))
1592 {
1593 path = $"{name}>{path}";
1594 }
1595 else
1596 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\AngleSharp\Dom\ElementExtensions.cs (line 1593)
1590 // Recreate selector path
1591 if (!String.IsNullOrEmpty(path))
1592 {
1593 path = $"{name}>{path}";
1594 }
1595 else
1596 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 src\AngleSharp\FormatExtensions.cs (line 65)
62 /// <param name="stream">The output stream to use.</param>
63 public static async Task ToCssAsync(this IStyleFormattable style, Stream stream)
64 {
65 using var writer = new StreamWriter(stream);
66 await style.ToCssAsync(writer).ConfigureAwait(false);
67 }
68
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\AngleSharp\FormatExtensions.cs (line 137)
134 /// <param name="stream">The output stream to use.</param>
135 public static async Task ToHtmlAsync(this IMarkupFormattable markup, Stream stream)
136 {
137 using var writer = new StreamWriter(stream);
138 await markup.ToHtmlAsync(writer).ConfigureAwait(false);
139 }
140 }
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 140 hits
📄 src\AngleSharp\Dom\Internal\Window.cs (line 20)
17 {
18 #region Fields
19
20 private readonly Document _document;
21
22 private String? _name;
23 private Int32 _outerHeight;
💬 Disposable field _document in type Window is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\AngleSharp\Text\TextSource.cs (line 17)
14 /// </summary>
15 public sealed class TextSource : ITextSource
16 {
17 private readonly WritableTextSource _writableSource;
18 private readonly IReadOnlyTextSource _readOnlyTextSource;
19
20 /// <summary>
💬 Disposable field _writableSource in type TextSource is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

PicView

1296 total diagnostics across 10 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 18 hits
📄 src\PicView.Core\DebugTools\DebugHelper.cs (line 35)
32 public static void LogDebug(string className, string methodName, Exception exception)
33 {
34 Debug.WriteLine(
35 $"\n[{DateTime.Now.ToString("T", CultureInfo.CurrentCulture)}] {className}.{methodName} exception: {exception.Message}");
36 Debug.WriteLine(exception.StackTrace + Environment.NewLine);
37 }
38
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\PicView.Core\DebugTools\DebugHelper.cs (line 44)
41 public static void LogDebug(string className, string methodName, string exceptionMessage)
42 {
43 Debug.WriteLine(
44 $"\n[{DateTime.Now.ToString("T", CultureInfo.CurrentCulture)}] {className}.{methodName} exception: {exceptionMessage}");
45 }
46}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 68 hits
📄 src\PicView.Core\Extensions\FileExtensions.cs (line 23)
20 return "0 B";
21 }
22
23 var magnitude = BitOperations.Log2((ulong)fileSize) / 10;
24
25 return magnitude is 0 ? FormatBytes(fileSize) : FormatWithSuffix(fileSize, magnitude);
26 }
💬 The operands in the divisive expression BitOperations.Log2((ulong)fileSize) / 10 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\PicView.Core\Exif\GpsHelper.cs (line 55)
52 return 0;
53 }
54
55 double degrees = rationals[0].Numerator / rationals[0].Denominator;
56 double minutes = rationals[1].Numerator / rationals[1].Denominator;
57 double seconds = rationals[2].Numerator / rationals[2].Denominator;
58
💬 The operands in the divisive expression rationals
SS017 Struct without Equals/GetHashCode/ToString overridden 38 hits
📄 src\PicView.Core\Gallery\GalleryThumbInfo.cs (line 12)
9 /// <summary>
10 /// Represents the data for a gallery thumbnail.
11 /// </summary>
12 public readonly struct GalleryThumbHolder : IEquatable<GalleryThumbHolder>
13 {
14 public string FileLocation { get; }
15 public string FileName { get; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct GalleryThumbHolder. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\PicView.Core\Navigation\FileTypeResolver.cs (line 17)
14 /// </summary>
15 /// <param name="type">The type of the loadable file.</param>
16 /// <param name="data">The data associated with the loadable file.</param>
17 public readonly struct FileTypeStruct(LoadAbleFileType type, string data)
18 {
19 /// <summary>
20 /// Gets the type of the loadable file.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FileTypeStruct. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 22 hits
📄 src\PicView.Avalonia\Crop\CropResizer.cs (line 78)
75 var size = Math.Max(newWidth, newHeight);
76
77 // Adjust position based on resize mode to maintain the correct anchor point
78 switch (mode)
79 {
80 case CropResizeMode.TopLeft:
81 newX = originalRect.X + originalRect.Width - size;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\PicView.Avalonia\Crop\CropKeyboardManager.cs (line 20)
17 return;
18 }
19
20 switch (e.Key)
21 {
22 case Key.Enter:
23 await vm.Crop.SaveCroppedImageAsync();
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 56 hits
📄 src\PicView.Core\ViewModels\ImageInfoWindowViewModel.cs (line 55)
52 TextBoxMaxWidth.Value = width < thirdBreakPoint ? 0 : TextMaxWidth;
53 ExtraTextBoxMaxWidth.Value = width < fourthBreakPoint ? 0 : TextMaxWidth;
54
55 switch (width)
56 {
57 case <= firstBreakPoint:
58 TextBoxWidth.Value = TextBoxXlWidth.Value = width - (textWidth + scrollBarThickness + smallPadding);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\PicView.Core.WindowsNT\FileHandling\ArchiveExtractionHelper.cs (line 102)
99 var installDir = subKey.GetValue("InstallLocation")?.ToString();
100 if (installDir == null) continue;
101
102 switch (subKeyName)
103 {
104 case "7-Zip":
105 return Path.Combine(installDir, SevenZip);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 src\PicView.Benchmarks\StartupBenchmarks\LanguageBenchmark.cs (line 123)
120
121 if (dir == null)
122 {
123 throw new DirectoryNotFoundException(
124 "Could not locate 'src' directory starting from the application base directory.");
125 }
126
💬 An exception is thrown from the getter of property GetLanguagesDirectory (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\PicView.Benchmarks\StartupBenchmarks\LanguageBenchmark.cs (line 133)
130
131 if (!Directory.Exists(fullPath))
132 {
133 throw new DirectoryNotFoundException($"Languages directory not found at '{fullPath}'.");
134 }
135
136 return fullPath;
💬 An exception is thrown from the getter of property GetLanguagesDirectory (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 10 hits
📄 src\PicView.Core\ImageEffects\ImageEffectsHelper.cs (line 40)
37 if (fileInfo.Length >= 2147483648)
38 {
39 // ReSharper disable once MethodHasAsyncOverloadWithCancellation
40 magick.Read(filestream);
41 }
42 else
43 {
💬 Async overload available for MagickImage.Read (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\PicView.Core\ImageReading\MagickPerformanceReader.cs (line 55)
52 // Fixes "The file is too long. This operation is currently limited to supporting files less than 2 gigabytes in size."
53 await using var fileStream = FileStreamUtils.GetOptimizedFileStream(fileInfo);
54 // ReSharper disable once MethodHasAsyncOverload
55 image.Read(fileStream);
56 return image;
57 }
58}
💬 Async overload available for MagickImage.Read (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 2 hits
📄 src\PicView.Avalonia\Printing\PrintCore.cs (line 79)
76 {
77 DebugHelper.LogDebug(nameof(PrintCore), nameof(ToGrayScale), e);
78 var mainVm = Dispatcher.UIThread.Invoke(() => UIHelper.GetMainView.DataContext as MainViewModel);
79 var cached = NavigationManager.GetPreLoadValueAsync(mainVm.PicViewer.FileInfo.Value).Result;
80 src = cached.ImageModel.Image as Bitmap ?? throw new NullReferenceException();
81 width = src.PixelSize.Width;
82 height = src.PixelSize.Height;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\PicView.Avalonia\Printing\PrintCore.cs (line 79)
76 {
77 DebugHelper.LogDebug(nameof(PrintCore), nameof(ToGrayScale), e);
78 var mainVm = Dispatcher.UIThread.Invoke(() => UIHelper.GetMainView.DataContext as MainViewModel);
79 var cached = NavigationManager.GetPreLoadValueAsync(mainVm.PicViewer.FileInfo.Value).Result;
80 src = cached.ImageModel.Image as Bitmap ?? throw new NullReferenceException();
81 width = src.PixelSize.Width;
82 height = src.PixelSize.Height;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 src\PicView.Avalonia\Clipboard\ClipboardImageOperations.cs (line 101)
98 return string.Empty;
99 }
100
101 using (var stream = new MemoryStream())
102 {
103 bitmap.Save(stream, 100);
104 return Convert.ToBase64String(stream.ToArray());
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\PicView.Avalonia\FileSystem\PdfExport.cs (line 44)
41
42 var localPath = chosenFile.Path.LocalPath;
43
44 using var pngStream = new MemoryStream();
45 // Avalonia's Bitmap.Save writes PNG by default (no format parameter).
46 bitmap.Save(pngStream);
47 pngStream.Position = 0;
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 1074 hits
📄 src\PicView.Core\ViewModels\PicViewerModel.cs (line 23)
20
21 public BindableReactiveProperty<FileInfo?> FileInfo { get; } = new();
22
23 public BindableReactiveProperty<ObservableCollection<FileSearchResult>> FilteredFileInfos { get; } = new();
24
25 /// <summary>
26 /// The image's pixel width
💬 Disposable field FilteredFileInfos in type PicViewerModel is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\PicView.Core\ViewModels\PicViewerModel.cs (line 41)
38
39 public BindableReactiveProperty<ImageType> ImageType { get; } = new();
40
41 public BindableReactiveProperty<MagickFormat?> Format { get; } = new();
42
43 public BindableReactiveProperty<double> RotationAngle { get; } = new(0);
44
💬 Disposable field Format in type PicViewerModel is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

WPF-Samples

1222 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 126 hits
📄 Sample Applications\DataBindingDemo\AddProductWindow.cs (line 26)
23 private void OnInit(object sender, RoutedEventArgs e)
24 {
25 DataContext = new AuctionItem(null,
26 ProductCategory.DvDs, 1, DateTime.Now, ((App) Application.Current).CurrentUser,
27 SpecialFeatures.None);
28 }
29
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Sample Applications\DataBindingDemo\FutureDateRule.cs (line 23)
20 {
21 return new ValidationResult(false, "Value is not a valid date. Please enter a valid date");
22 }
23 if (DateTime.Now.Date > date)
24 {
25 return new ValidationResult(false, "Value is not a future date. Please enter a date in the future.");
26 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 66 hits
📄 Sample Applications\FontDialog\FontChooser.cs (line 1818)
1815
1816 while (first < limit)
1817 {
1818 var i = first + (limit - first)/2;
1819 var item = (IComparable) (itemList[i]);
1820 var comparison = item.CompareTo(value);
1821 if (comparison < 0)
💬 The operands in the divisive expression (limit - first)/2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Sample Applications\LayoutTransitionsDemo\MainWindow.cs (line 151)
148 {
149 var target = Targets[i] as LayoutToLayoutTarget;
150 (Hosts[i] as LayoutToLayoutHost)?.BeginAnimating(false);
151 Grid.SetRow(target, i/5);
152 Grid.SetColumn(target, i%5);
153 LTLGrid.Children.Add(target);
154 }
💬 The operands in the divisive expression i/5 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS011 OnPropertyChanged without nameof operator 242 hits
📄 Sample Applications\DataBindingDemo\AuctionItem.cs (line 41)
38 public void AddBid(Bid bid)
39 {
40 _bids.Add(bid);
41 OnPropertyChanged("CurrentPrice");
42 }
43
44 protected void OnPropertyChanged(string name)
💬 OnPropertyChanged(CurrentPrice) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
📄 Sample Applications\DataBindingDemo\AuctionItem.cs (line 62)
59 throw new ArgumentException("Item Description Should be added");
60 }
61 _description = value;
62 OnPropertyChanged("Description");
63
64 }
65 }
💬 OnPropertyChanged(Description) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 56 hits
📄 Sample Applications\FontDialog\FontChooser.cs (line 357)
354 }
355 }
356
357 public struct Item
358 {
359 public readonly string Tag;
360 public readonly object Value;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Item. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Sample Applications\FontDialog\FontChooser.cs (line 357)
354 }
355 }
356
357 public struct Item
358 {
359 public readonly string Tag;
360 public readonly object Value;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Item. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 36 hits
📄 Sample Applications\FontDialog\FontChooser.cs (line 1856)
1853 // Behavior is similar to a Win32 combo box.
1854 private void OnComboBoxPreviewKeyDown(TextBox textBox, ListBox listBox, KeyEventArgs e)
1855 {
1856 switch (e.Key)
1857 {
1858 case Key.Up:
1859 // Move up from the current position.
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Sample Applications\FontDialog\FontChooser.cs (line 1856)
1853 // Behavior is similar to a Win32 combo box.
1854 private void OnComboBoxPreviewKeyDown(TextBox textBox, ListBox listBox, KeyEventArgs e)
1855 {
1856 switch (e.Key)
1857 {
1858 case Key.Up:
1859 // Move up from the current position.
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 248 hits
📄 Sample Applications\EditingExaminerDemo\CommandLine.cs (line 263)
260 {
261 try
262 {
263 switch (i)
264 {
265 case 0:
266 returnValue = ReflectionUtils.GetField(objectInstance, propertyName);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Sample Applications\EditingExaminerDemo\ReflectionUtils.cs (line 717)
714 newargs = null;
715 instance = null;
716
717 switch (invokeType)
718 {
719 case InvokeType.StaticMethod:
720 defaultFlags |= BindingFlags.InvokeMethod;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 Sample Applications\GraphingCalculatorDemo\Parser\VariableExpression.cs (line 38)
35 {
36 return (double) Environment[_identifier];
37 }
38 throw new UndefinedVariableException(_identifier + " is not defined");
39 }
40 }
41
💬 An exception is thrown from the getter of property Value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Sample Applications\GraphingCalculatorDemo\Parser\VariableExpression.cs (line 38)
35 {
36 return (double) Environment[_identifier];
37 }
38 throw new UndefinedVariableException(_identifier + " is not defined");
39 }
40 }
41
💬 An exception is thrown from the getter of property Value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS049 Comparing strings without StringComparison 252 hits
📄 Sample Applications\HtmlToXamlDemo\CssStylesheet.cs (line 28)
25 // for further cascading style application
26 public void DiscoverStyleDefinitions(XmlElement htmlElement)
27 {
28 if (htmlElement.LocalName.ToLower() == "link")
29 {
30 return;
31 // Add LINK elements processing for included stylesheets
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Sample Applications\HtmlToXamlDemo\CssStylesheet.cs (line 35)
32 // <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet>
33 }
34
35 if (htmlElement.LocalName.ToLower() != "style")
36 {
37 // This is not a STYLE element. Recurse into it
38 for (var htmlChildNode = htmlElement.FirstChild;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS050 Parameter assigned in constructor 4 hits
📄 Sample Applications\GraphingCalculatorDemo\Parser\Tokenizer.cs (line 22)
19 {
20 if (function == null)
21 {
22 function = string.Empty;
23 }
24 _function = function;
25 _index = 0;
💬 Suspicious assignment of parameter function in constructor of Tokenizer (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
📄 Sample Applications\GraphingCalculatorDemo\Parser\Tokenizer.cs (line 22)
19 {
20 if (function == null)
21 {
22 function = string.Empty;
23 }
24 _function = function;
25 _index = 0;
💬 Suspicious assignment of parameter function in constructor of Tokenizer (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
SS057 Collection manipulated during traversal 4 hits
📄 Animation\Per-FrameAnimation\ParticleEffects\FireworkEffect.cs (line 110)
107
108 //only increment counter for live particles
109 if (_timeTracker.ElapsedTime > p.DeathTime)
110 _particles.RemoveAt(i);
111 else
112 i++;
113 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 Animation\Per-FrameAnimation\ParticleEffects\FireworkEffect.cs (line 110)
107
108 //only increment counter for live particles
109 if (_timeTracker.ElapsedTime > p.DeathTime)
110 _particles.RemoveAt(i);
111 else
112 i++;
113 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 140 hits
📄 Sample Applications\EditingExaminerDemo\XamlHelper.cs (line 138)
135 strs = xaml.Split('<');
136 for (var i = 1; i < strs.Length; i++)
137 {
138 value += ProcessEachTag(strs[i]);
139 }
140 return s1 + value + s2;
141 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Sample Applications\EditingExaminerDemo\XamlHelper.cs (line 196)
193 //Take care of properties:
194 while (str.Length > 0)
195 {
196 returnValue += propertynameStart + str.Substring(0, str.IndexOf("=", StringComparison.Ordinal)) + endRun +
197 "=";
198 str = str.Substring(str.IndexOf("\"", StringComparison.Ordinal) + 1).Trim();
199 returnValue += propertyValueStart + str.Substring(0, str.IndexOf("\"", StringComparison.Ordinal)) +
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 44 hits
📄 Documents\Fixed Documents\DocumentSerialization\HtmlXmlConverter\htmllexicalanalyzer.cs (line 746)
743 #region Private Fields
744
745 // string reader which will move over input text
746 private StringReader _inputStringReader;
747 // next character code read from input that is not yet part of any token
748 // and the character it represents
749 private int _nextCharacterCode;
💬 Disposable field _inputStringReader in type HtmlLexicalAnalyzer is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Documents\Fixed Documents\DocumentSerialization\ThumbViewer.xaml.cs (line 675)
672
673 // Bookmarks and comments
674 AnnotationService _annServ = null;
675 AnnotationStore _annStore = null;
676 MemoryStream _annotationBuffer = null;
677
678 // filename open
💬 Disposable field _annStore in type ThumbViewer is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

subtitleedit

1112 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 54 hits
📄 src\libse\Settings\SubtitleSettings.cs (line 215)
212 CurrentDCinemaFontUri = DCinemaFontFile;
213 CurrentDCinemaFontId = "Arial";
214 }
215 CurrentDCinemaIssueDate = DateTime.Now.ToString("s");
216 CurrentDCinemaMovieTitle = "title";
217 CurrentDCinemaReelNumber = "1";
218 CurrentDCinemaFontColor = SKColors.White;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\libse\ContainerFormats\Mp4\Mp4Parser.cs (line 109)
106 return new DateTime(1904, 1, 1, 0, 0, 0, DateTimeKind.Utc).Add(TimeSpan.FromSeconds(Moov.Mvhd.CreationTime));
107 }
108
109 return DateTime.Now;
110 }
111 }
112
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 240 hits
📄 src\libse\VobSub\VobSubWriter.cs (line 79)
76
77 public static void WriteEndianWord(int i, Stream stream)
78 {
79 stream.WriteByte((byte)(i / 256));
80 stream.WriteByte((byte)(i % 256));
81 }
82
💬 The operands in the divisive expression i / 256 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\libse\VobSub\VobSubWriter.cs (line 228)
225 // write whole image in one 0x800 part
226
227 long j = (headerSize - 20) + toWrite;
228 subHeader[18] = (byte)(j / 0x100);
229 subHeader[19] = (byte)(j % 0x100);
230
231 // First Write header
💬 The operands in the divisive expression j / 0x100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 10 hits
📄 src\libse\GermanNouns.cs (line 26)
23
24 _regularExpressionList = new Dictionary<Regex, string>
25 {
26 { new Regex(@"\bDas essen\b", RegexOptions.Compiled), "Das Essen" },
27 { new Regex(@"\bdas essen\b", RegexOptions.Compiled), "das Essen" }
28 };
29 }
💬 Type Regex is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\libse\GermanNouns.cs (line 27)
24 _regularExpressionList = new Dictionary<Regex, string>
25 {
26 { new Regex(@"\bDas essen\b", RegexOptions.Compiled), "Das Essen" },
27 { new Regex(@"\bdas essen\b", RegexOptions.Compiled), "das Essen" }
28 };
29 }
30
💬 Type Regex is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 2 hits
📄 src\libse\Translate\TranslationPair.cs (line 6)
3
4namespace Nikse.SubtitleEdit.Core.Translate
5{
6 public class TranslationPair : IEquatable<TranslationPair>
7 {
8 public string Name { get; }
9
💬 Equals() and GetHashcode() must be implemented together on TranslationPair (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\libse\Translate\TranslationPair.cs (line 6)
3
4namespace Nikse.SubtitleEdit.Core.Translate
5{
6 public class TranslationPair : IEquatable<TranslationPair>
7 {
8 public string Name { get; }
9
💬 Equals() and GetHashcode() must be implemented together on TranslationPair (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 4 hits
📄 src\libse\Common\Dimension.cs (line 36)
33 {
34 unchecked
35 {
36 return (Height * 397) ^ Width;
37 }
38 }
39 }
💬 GetHashCode() refers to mutable property Height (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\libse\Common\Dimension.cs (line 36)
33 {
34 unchecked
35 {
36 return (Height * 397) ^ Width;
37 }
38 }
39 }
💬 GetHashCode() refers to mutable property Width (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS015 String placeholders in wrong order 4 hits
📄 src\libse\BluRaySup\BluRaySupParser.cs (line 910)
907 var y = BigEndianInt16(buffer, 4 + offset);
908 var width = BigEndianInt16(buffer, 6 + offset);
909 var height = BigEndianInt16(buffer, 8 + offset);
910 log.AppendLine(string.Format("WinId: {4}, X: {0}, Y: {1}, Width: {2}, Height: {3}", x, y, width, height, windowId));
911 offset += 9;
912 }
913 }
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 src\libse\SubtitleFormats\UnknownSubtitle38.cs (line 26)
23 //1 00:50:34:22 00:50:39:13
24 //Ich muss dafür sorgen,
25 //dass die Epsteins weiterleben
26 sb.AppendLine(string.Format("{4} {0} {1}{2}{3}{2}", EncodeTimeCode(p.StartTime), EncodeTimeCode(p.EndTime), Environment.NewLine, HtmlUtil.RemoveHtmlTags(p.Text), index));
27 index++;
28 }
29 return sb.ToString();
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 8 hits
📄 src\libse\Common\FastBitmap.cs (line 9)
6{
7 public unsafe class FastBitmap
8 {
9 public struct PixelData
10 {
11 public byte Blue;
12 public byte Green;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PixelData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\libse\Common\ZipExtractor.cs (line 34)
31 /// <summary>
32 /// Represents an entry in Zip file directory
33 /// </summary>
34 public struct ZipFileEntry
35 {
36 /// <summary>Compression method</summary>
37 public Compression Method;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ZipFileEntry. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 8 hits
📄 src\libse\ContainerFormats\Matroska\MatroskaFile.cs (line 95)
92 clusterNo < maxClustersToSeek &&
93 (element = ReadElement()) != null)
94 {
95 switch (element.Id)
96 {
97 case ElementId.Info:
98 ReadInfoElement(element);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\libse\ContainerFormats\Matroska\MatroskaFile.cs (line 143)
140 Element element;
141 while (_stream.Position < cluster.EndPosition && (element = ReadElement()) != null && !done)
142 {
143 switch (element.Id)
144 {
145 case ElementId.None:
146 done = true;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 104 hits
📄 src\libse\AutoTranslate\PapagoTranslate.cs (line 121)
118 else
119 {
120 // Handle codes that might not have a culture match
121 switch (code)
122 {
123 case "th":
124 result.Add(new TranslationPair("Thai", code, code));
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\libse\SubtitleFormats\YouTubeSbv.cs (line 92)
89
90 private void ReadLine(Subtitle subtitle, string line, string next)
91 {
92 switch (_expecting)
93 {
94 case ExpectingLine.TimeCodes:
95 if (TryReadTimeCodesLine(line, _paragraph))
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 36 hits
📄 src\libse\AutoTranslate\SeamlessM4TTranslate.cs (line 68)
65 var input = "{ \"input\": { \"task_name\":\"T2TT (Text to Text translation)\", \"input_text\": \"" + Json.EncodeJsonText(text.Trim()) + "\", \"input_text_language\": \"" + sourceLanguageCode + "\", \"target_language_text_only\": \"" + targetLanguageCode + "\" }}";
66 var content = new StringContent(input, Encoding.UTF8);
67 content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
68 var result = _httpClient.PostAsync("predictions", content).Result;
69 result.EnsureSuccessStatusCode();
70 var bytes = await result.Content.ReadAsByteArrayAsync();
71 var json = Encoding.UTF8.GetString(bytes).Trim();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\libse\AutoTranslate\NoLanguageLeftBehindServe.cs (line 58)
55 var content = new StringContent(input, Encoding.UTF8);
56 content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
57
58 var result = _httpClient.PostAsync("translate", content).Result;
59 result.EnsureSuccessStatusCode();
60 var bytes = await result.Content.ReadAsByteArrayAsync();
61 var json = Encoding.UTF8.GetString(bytes).Trim();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS049 Comparing strings without StringComparison 30 hits
📄 src\libse\SubtitleFormats\DCinemaSmpte2007.cs (line 897)
894 }
895
896 string text;
897 if (textLines.All(p => p.VerticalAlignment.ToLowerInvariant() == "bottom"))
898 {
899 text = string.Join(Environment.NewLine, textLines.OrderByDescending(p => p.GetVerticalPositionAsNumber()).Select(p => p.Text));
900 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\libse\SubtitleFormats\DCinemaSmpte2014.cs (line 911)
908 }
909
910 string text;
911 if (textLines.All(p => p.VerticalAlignment.ToLowerInvariant() == "bottom"))
912 {
913 text = string.Join(Environment.NewLine, textLines.OrderByDescending(p => p.GetVerticalPositionAsNumber()).Select(p => p.Text));
914 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS057 Collection manipulated during traversal 2 hits
📄 src\libse\Common\Subtitle.cs (line 913)
910 var p = Paragraphs[i];
911 if (newParagraph.StartTime.TotalMilliseconds < p.StartTime.TotalMilliseconds)
912 {
913 Paragraphs.Insert(i, newParagraph);
914 return i;
915 }
916 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\libse\Common\Subtitle.cs (line 913)
910 var p = Paragraphs[i];
911 if (newParagraph.StartTime.TotalMilliseconds < p.StartTime.TotalMilliseconds)
912 {
913 Paragraphs.Insert(i, newParagraph);
914 return i;
915 }
916 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 550 hits
📄 src\libse\Common\WebVttHelper.cs (line 524)
521 {
522 foreach (var style in styles)
523 {
524 text = "<c." + style.Name.TrimStart('.') + ">" + text + "</c>";
525 }
526
527 return text;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\libse\SubtitleFormats\YouTubeTranscript.cs (line 78)
75 }
76 else
77 {
78 p.Text = p.Text + Environment.NewLine + s;
79 }
80
81 if (p.Text.Length > 800)
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 src\libse\Http\HttpClientDownloader.cs (line 45)
42 using (var response = await _httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
43 {
44 var contentLength = response.Content.Headers.ContentLength;
45 using (var downloadStream = await response.Content.ReadAsStreamAsync())
46 {
47 if (progress == null || !contentLength.HasValue)
48 {
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\libse\Http\HttpClientDownloader.cs (line 45)
42 using (var response = await _httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
43 {
44 var contentLength = response.Content.Headers.ContentLength;
45 using (var downloadStream = await response.Content.ReadAsStreamAsync())
46 {
47 if (progress == null || !contentLength.HasValue)
48 {
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 58 hits
📄 src\libse\AutoTranslate\SeamlessM4TTranslate.cs (line 17)
14{
15 public class SeamlessM4TTranslate : IAutoTranslator, IDisposable
16 {
17 private HttpClient _httpClient;
18
19 public static string StaticName { get; set; } = "SeamlessM4T";
20 public override string ToString() => StaticName;
💬 Disposable field _httpClient in type SeamlessM4TTranslate is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\libse\Http\HttpClientDownloader.cs (line 14)
11{
12 public class HttpClientDownloader : IDownloader
13 {
14 private readonly HttpClient _httpClient;
15
16 public HttpClientDownloader(HttpClient httpClient) => _httpClient = httpClient;
17
💬 Disposable field _httpClient in type HttpClientDownloader is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

DotNetty

1080 total diagnostics across 12 rules

SS001 Async method with void return type 6 hits
📄 examples\Discard.Client\DiscardClientHandler.cs (line 36)
33 this.ctx.CloseAsync();
34 }
35
36 async void GenerateTraffic()
37 {
38 try
39 {
💬 Method GenerateTraffic is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 examples\Discard.Client\DiscardClientHandler.cs (line 36)
33 this.ctx.CloseAsync();
34 }
35
36 async void GenerateTraffic()
37 {
38 try
39 {
💬 Method GenerateTraffic is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 24 hits
📄 test\DotNetty.Tests.Common\XUnitOutputLogger.cs (line 28)
25 {
26 try
27 {
28 this.output.WriteLine($"{DateTime.Now}\t[{logLevel.ToString()}]\t{eventId.Name}\t{this.categoryName}\t{formatter(state, exception)}\t{exception}");
29 }
30 catch (Exception ex)
31 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 test\DotNetty.Tests.Common\XUnitOutputLogger.cs (line 28)
25 {
26 try
27 {
28 this.output.WriteLine($"{DateTime.Now}\t[{logLevel.ToString()}]\t{eventId.Name}\t{this.categoryName}\t{formatter(state, exception)}\t{exception}");
29 }
30 catch (Exception ex)
31 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 522 hits
📄 test\DotNetty.Common.Tests\ThreadLocalPoolTest.cs (line 277)
274 }
275
276 // The implementation uses maxCapacity / 2 as limit per WeakOrderQueue
277 Assert.True(array.Length - maxCapacity / 2 <= Volatile.Read(ref instancesCount),
278 "The instances count (" + Volatile.Read(ref instancesCount) + ") must be <= array.length (" + array.Length
279 + ") - maxCapacity (" + maxCapacity + ") / 2 as we not pool all new handles" +
280 " internally");
💬 The operands in the divisive expression maxCapacity / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 test\DotNetty.Buffers.Tests\ByteBufferUtilTests.cs (line 19)
16 var rand = new Random();
17 rand.NextBytes(b1);
18 rand.NextBytes(b2);
19 int iB1 = b1.Length / 2;
20 int iB2 = iB1 + b1.Length;
21 int length = b1.Length - iB1;
22 Array.Copy(b1, iB1, b2, iB2, length);
💬 The operands in the divisive expression b1.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 72 hits
📄 test\DotNetty.Codecs.Protobuf.Tests\Addressbook.cs (line 558)
555 public override int GetHashCode()
556 {
557 int hash = 1;
558 hash ^= people_.GetHashCode();
559 return hash;
560 }
561
💬 GetHashCode() refers to mutable field people_ (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 test\DotNetty.Codecs.Protobuf.Tests\Addressbook.cs (line 174)
171 public override int GetHashCode()
172 {
173 int hash = 1;
174 if (Name.Length != 0) hash ^= Name.GetHashCode();
175 if (Id != 0) hash ^= Id.GetHashCode();
176 if (Email.Length != 0) hash ^= Email.GetHashCode();
177 hash ^= phones_.GetHashCode();
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS032 Thread.Sleep used in async method 6 hits
📄 test\DotNetty.Common.Tests\Concurrency\SingleThreadEventExecutorTests.cs (line 135)
132 var scheduler = new SingleThreadEventExecutor("test", TimeSpan.FromMilliseconds(10));
133 if (delayInMs > 0)
134 {
135 Thread.Sleep(delayInMs);
136 }
137 Task shutdownTask = scheduler.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(50), TimeSpan.FromSeconds(1));
138 await Task.WhenAny(shutdownTask, Task.Delay(TimeSpan.FromSeconds(5)));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 test\DotNetty.Common.Tests\Concurrency\SingleThreadEventExecutorTests.cs (line 135)
132 var scheduler = new SingleThreadEventExecutor("test", TimeSpan.FromMilliseconds(10));
133 if (delayInMs > 0)
134 {
135 Thread.Sleep(delayInMs);
136 }
137 Task shutdownTask = scheduler.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(50), TimeSpan.FromSeconds(1));
138 await Task.WhenAny(shutdownTask, Task.Delay(TimeSpan.FromSeconds(5)));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 20 hits
📄 test\DotNetty.Tests.Common\TaskExtensions.cs (line 38)
35 {
36 if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
37 {
38 cts.Cancel();
39 return await task;
40 }
41 }
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 test\DotNetty.Tests.Common\TaskExtensions.cs (line 52)
49 {
50 if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
51 {
52 cts.Cancel();
53 await task;
54 return;
55 }
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 300 hits
📄 test\DotNetty.Tests.Common\ReadListeningHandler.cs (line 96)
93 throw new TimeoutException("ReceiveAsync timed out");
94 }
95
96 return promise.Task.Result;
97 }
98
99 return await promise.Task;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 test\DotNetty.Tests.Common\ReadListeningHandler.cs (line 96)
93 throw new TimeoutException("ReceiveAsync timed out");
94 }
95
96 return promise.Task.Result;
97 }
98
99 return await promise.Task;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 108 hits
📄 examples\Discard.Client\Program.cs (line 62)
59 }
60 finally
61 {
62 group.ShutdownGracefullyAsync().Wait(1000);
63 }
64 }
65
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 test\DotNetty.Tests.End2End\End2EndTests.cs (line 106)
103 finally
104 {
105 Task serverCloseTask = closeServerFunc();
106 clientChannel?.CloseAsync().Wait(TimeSpan.FromSeconds(5));
107 group.ShutdownGracefullyAsync().Wait(TimeSpan.FromSeconds(5));
108 if (!serverCloseTask.Wait(ShutdownTimeout))
109 {
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS048 Locking on discouraged object (string, Type, this) 6 hits
📄 examples\SecureChat.Server\SecureChatServerHandler.cs (line 20)
17 IChannelGroup g = group;
18 if (g == null)
19 {
20 lock (this)
21 {
22 if (group == null)
23 {
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 examples\SecureChat.Server\SecureChatServerHandler.cs (line 20)
17 IChannelGroup g = group;
18 if (g == null)
19 {
20 lock (this)
21 {
22 if (group == null)
23 {
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS058 String concatenated in a loop 6 hits
📄 test\DotNetty.Codecs.Http.Tests\Multipart\HttpPostRequestDecoderTest.cs (line 123)
120 strings[i] = Extradata;
121 for (int j = 0; j < i; j++)
122 {
123 strings[i] += '\r';
124 }
125 }
126
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 test\DotNetty.Codecs.Http.Tests\Multipart\HttpPostRequestDecoderTest.cs (line 123)
120 strings[i] = Extradata;
121 for (int j = 0; j < i; j++)
122 {
123 strings[i] += '\r';
124 }
125 }
126
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 test\DotNetty.Buffers.Tests\UnpooledWriteStreamTests.cs (line 27)
24
25 IByteBuffer buffer = Unpooled.Buffer(BufferCapacity);
26 int initialWriterIndex = buffer.WriterIndex;
27 using (var stream = new PortionedMemoryStream(bytes, Enumerable.Repeat(1, int.MaxValue).Select(_ => random.Next(1, 10240))))
28 {
29 await buffer.WriteBytesAsync(stream, CopyLength);
30 }
💬 PortionedMemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 test\DotNetty.Buffers.Tests\UnpooledWriteStreamTests.cs (line 27)
24
25 IByteBuffer buffer = Unpooled.Buffer(BufferCapacity);
26 int initialWriterIndex = buffer.WriterIndex;
27 using (var stream = new PortionedMemoryStream(bytes, Enumerable.Repeat(1, int.MaxValue).Select(_ => random.Next(1, 10240))))
28 {
29 await buffer.WriteBytesAsync(stream, CopyLength);
30 }
💬 PortionedMemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 6 hits
📄 test\DotNetty.Buffers.Tests\PortionedMemoryStream.cs (line 15)
12 readonly byte[] data;
13 int position;
14 readonly IEnumerable<ArraySegment<byte>> dataFeedSource;
15 IEnumerator<ArraySegment<byte>> currentDataFeed;
16
17 public PortionedMemoryStream(byte[] data, IEnumerable<int> readCounts)
18 {
💬 Disposable field currentDataFeed in type PortionedMemoryStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 test\DotNetty.Buffers.Tests\PortionedMemoryStream.cs (line 15)
12 readonly byte[] data;
13 int position;
14 readonly IEnumerable<ArraySegment<byte>> dataFeedSource;
15 IEnumerator<ArraySegment<byte>> currentDataFeed;
16
17 public PortionedMemoryStream(byte[] data, IEnumerable<int> readCounts)
18 {
💬 Disposable field currentDataFeed in type PortionedMemoryStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Power-Fx

1014 total diagnostics across 22 rules

SS001 Async method with void return type 2 hits
📄 src\libraries\Microsoft.PowerFx.Repl\Repl.cs (line 565)
562 return replResult;
563 }
564
565 public virtual async void OnFormulaUpdate(string name, FormulaValue newValue)
566 {
567 if (PrintResult)
568 {
💬 Method OnFormulaUpdate is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\libraries\Microsoft.PowerFx.Repl\Repl.cs (line 565)
562 return replResult;
563 }
564
565 public virtual async void OnFormulaUpdate(string name, FormulaValue newValue)
566 {
567 if (PrintResult)
568 {
💬 Method OnFormulaUpdate is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 14 hits
📄 src\libraries\Microsoft.PowerFx.Interpreter\Functions\LibraryDate.cs (line 754)
751
752 if (args.Length == 0)
753 {
754 var tzOffsetDays = tzInfo.GetUtcOffset(DateTime.Now).TotalDays;
755 return new NumberValue(irContext, tzOffsetDays * -1440);
756 }
757
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\IRTests\IRTests.cs (line 80)
77
78 var stringVar = FormulaValue.New("lichess.org");
79 var integerVar = FormulaValue.New(1);
80 var datetimeVar = FormulaValue.New(DateTime.Now);
81
82 engine.Config.SymbolTable.EnableMutationFunctions();
83 engine.Config.SymbolTable.AddConstant("stringVar", stringVar);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 18 hits
📄 src\libraries\Microsoft.PowerFx.Core\Utils\RedBlackTree.cs (line 557)
554 default:
555 if ((nodeCount & 1) == 1)
556 {
557 half = nodeCount / 2;
558 }
559 else
560 {
💬 The operands in the divisive expression nodeCount / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\libraries\Microsoft.PowerFx.Core\Utils\RedBlackTree.cs (line 561)
558 }
559 else
560 {
561 half = (nodeCount + 1) / 2;
562 if (((nodeCount + 2) & (nodeCount + 1)) == 0)
563 {
564 leftColor = Color.Red;
💬 The operands in the divisive expression (nodeCount + 1) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 596 hits
📄 src\libraries\Microsoft.PowerFx.Core\Entities\QueryOptions\ExpandQueryOptions.cs (line 176)
173
174 private bool AddExpand(ExpandQueryOptions expand)
175 {
176 _expands.Add(expand);
177 return true;
178 }
179
💬 Type ExpandQueryOptions is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\libraries\Microsoft.PowerFx.Core\Parser\TexlParser.cs (line 127)
124 if (varIdent != null)
125 {
126 // Add incomplete UDFArgs (colon & type are missing) as well, these are needed for intellisense.
127 args.Add(new UDFArg(varIdent.As<IdentToken>(), typeIdent: null, colonToken: null, argIndex));
128 }
129
130 // If the result was an error, keep moving cursor until end of expression
💬 Type UDFArg is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 2 hits
📄 src\libraries\Microsoft.PowerFx.Core\Utils\DPath.cs (line 20)
17 [ThreadSafeImmutable]
18 public struct DPath : IEquatable<DPath>, ICheckable
19 {
20 private class Node : ICheckable
21 {
22 public const int HashNull = 0x340CA819;
23
💬 Equals() and GetHashcode() must be implemented together on Node (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\libraries\Microsoft.PowerFx.Core\Utils\DPath.cs (line 20)
17 [ThreadSafeImmutable]
18 public struct DPath : IEquatable<DPath>, ICheckable
19 {
20 private class Node : ICheckable
21 {
22 public const int HashNull = 0x340CA819;
23
💬 Equals() and GetHashcode() must be implemented together on Node (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 86 hits
📄 src\libraries\Microsoft.PowerFx.Core\Texl\Intellisense\SignatureHelp\SignatureInformation.cs (line 80)
77 /// <returns>A hash code for the current object.</returns>
78 public override int GetHashCode()
79 {
80 return (Label, Documentation).GetHashCode();
81 }
82 }
83}
💬 GetHashCode() refers to mutable property Label (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\libraries\Microsoft.PowerFx.Core\Texl\Intellisense\SignatureHelp\SignatureInformation.cs (line 80)
77 /// <returns>A hash code for the current object.</returns>
78 public override int GetHashCode()
79 {
80 return (Label, Documentation).GetHashCode();
81 }
82 }
83}
💬 GetHashCode() refers to mutable property Documentation (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS009 Random instantiated in a loop 2 hits
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\LanguageServiceProtocol\SemanticTokensEncoderTests.cs (line 124)
121
122 for (var i = 0; i < MaxOverlappingToks; i++)
123 {
124 var rand = new Random();
125 var idx = rand.Next(tokens.Count);
126 var chosenToken = tokens[idx];
127 for (var j = chosenToken.StartIndex; j < chosenToken.EndIndex; j++)
💬 Variable rand of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\LanguageServiceProtocol\SemanticTokensEncoderTests.cs (line 124)
121
122 for (var i = 0; i < MaxOverlappingToks; i++)
123 {
124 var rand = new Random();
125 var idx = rand.Next(tokens.Count);
126 var chosenToken = tokens[idx];
127 for (var j = chosenToken.StartIndex; j < chosenToken.EndIndex; j++)
💬 Variable rand of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 36 hits
📄 src\libraries\Microsoft.PowerFx.Core\Entities\ColumnMetadata.cs (line 27)
24 ServerGenerated = 1,
25 }
26
27 internal struct ColumnLookupMetadata
28 {
29 public readonly bool IsSearchable;
30 public readonly bool IsSearchRequired;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ColumnLookupMetadata. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\libraries\Microsoft.PowerFx.Core\Entities\ColumnMetadata.cs (line 39)
36 }
37 }
38
39 internal struct ColumnAttachmentMetadata
40 {
41 public readonly string ListFunctionName;
42 public readonly string GetFunctionName;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ColumnAttachmentMetadata. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 32 hits
📄 src\libraries\Microsoft.PowerFx.Core\Binding\BinderUtils.cs (line 1509)
1506 {
1507 Contracts.AssertValue(node);
1508 nodeValue = null;
1509 switch (node.Kind)
1510 {
1511 case NodeKind.StrLit:
1512 nodeValue = node.AsStrLit().Value;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\libraries\Microsoft.PowerFx.Core\IR\CoercionMatrix.cs (line 56)
53 case DKind.Currency:
54 if (usePowerFxV1CompatibilityRules)
55 {
56 switch (fromType.Kind)
57 {
58 case DKind.Number:
59 return CoercionKind.NumberToCurrency;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 80 hits
📄 src\libraries\Microsoft.PowerFx.Core\Utils\RedBlackTree.cs (line 28)
25
26 var rgkvp = items.ToArray();
27 var count = rgkvp.Length;
28 switch (count)
29 {
30 case 0:
31 return null;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\libraries\Microsoft.PowerFx.Core\Binding\BinderUtils.cs (line 1509)
1506 {
1507 Contracts.AssertValue(node);
1508 nodeValue = null;
1509 switch (node.Kind)
1510 {
1511 case NodeKind.StrLit:
1512 nodeValue = node.AsStrLit().Value;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS020 Test method without public modifier 6 hits
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\ConfigTests.cs (line 450)
447 // - runtime evaluation
448 // These ignore the Threads's / Config / Engine's current culture.
449 [Fact]
450 private void MultiCulture1()
451 {
452 RunOnIsolatedThread(_doNotUseCulture, MultiCulture1ThreadProc);
453 }
💬 Test method "MultiCulture1" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\ConfigTests.cs (line 456)
453 }
454
455 [Fact]
456 private void MultiCultureWithCurrentUICulture()
457 {
458 // $$$ Don't use CurrentUICulture
459 CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
💬 Test method "MultiCultureWithCurrentUICulture" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
SS021 Test method without test attribute 4 hits
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\LanguageServiceProtocol\RedesignedLanguageServerTests\LanguageServerTestBase.cs (line 29)
26
27 private TestHandlerFactory HandlerFactory { get; set; }
28
29 public TestLogger Logger { get; set; }
30
31 public TestHostTaskExecutor HostTaskExecutor { get; set; }
32
💬 Method set_Logger might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\LanguageServiceProtocol\RedesignedLanguageServerTests\LanguageServerTestBase.cs (line 31)
28
29 public TestLogger Logger { get; set; }
30
31 public TestHostTaskExecutor HostTaskExecutor { get; set; }
32
33 public LanguageServerTestBase()
34 : base()
💬 Method set_HostTaskExecutor might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS023 Exception thrown from property getter 16 hits
📄 src\libraries\Microsoft.PowerFx.Core\Public\Config\ComposedReadOnlySymbolTable.cs (line 91)
88 var newHash = this.VersionHash;
89 if (newHash != current)
90 {
91 throw new InvalidOperationException($"Symbol Table was mutated during read.");
92 }
93 }
94
💬 An exception is thrown from the getter of property Functions (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\libraries\Microsoft.PowerFx.Core\Public\CheckResult.cs (line 249)
246 {
247 if (_topLevelIdentifiers == null)
248 {
249 throw new InvalidOperationException($"Call {nameof(ApplyDependencyAnalysis)} first.");
250 }
251
252 return _topLevelIdentifiers;
💬 An exception is thrown from the getter of property TopLevelIdentifiers (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS027 Exception thrown from Dispose 4 hits
📄 src\libraries\Microsoft.PowerFx.Core\Annotations\GuardSingleThreaded.cs (line 44)
41 if (thisId != _currentId)
42 {
43 // Should never be possible if we use 'using' and keep Dispose() on same thread.
44 throw new InvalidOperationException($"Operation switched thread. Started {_currentId}. Now {thisId}.");
45 }
46
47 var oldId = Interlocked.Exchange(ref _parent._id, 0);
💬 An exception is thrown from the Dispose() method in type GuardInstance (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 src\libraries\Microsoft.PowerFx.Core\Annotations\GuardSingleThreaded.cs (line 50)
47 var oldId = Interlocked.Exchange(ref _parent._id, 0);
48 if (oldId != _currentId)
49 {
50 throw new InvalidOperationException($"Operation mismatched. Started {oldId}. Current {_currentId}.");
51 }
52 }
53 }
💬 An exception is thrown from the Dispose() method in type GuardInstance (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS032 Thread.Sleep used in async method 2 hits
📄 src\tests\Microsoft.PowerFx.Connectors.Tests.Shared\PowerAppsForMakersTests.cs (line 132)
129 {
130 double duration = double.Parse(m.Groups["d"].Value);
131 long ticks = (long)(((duration * 1.05) + 2.0) * 10000000.0);
132 Thread.Sleep(new TimeSpan(ticks));
133
134 tryAgain = true;
135 retryCount++;
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 src\tests\Microsoft.PowerFx.Connectors.Tests.Shared\PowerAppsForMakersTests.cs (line 132)
129 {
130 double duration = double.Parse(m.Groups["d"].Value);
131 long ticks = (long)(((duration * 1.05) + 2.0) * 10000000.0);
132 Thread.Sleep(new TimeSpan(ticks));
133
134 tryAgain = true;
135 retryCount++;
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 10 hits
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\MutationFunctionsTests.cs (line 567)
564
565 foreach (var row in _inner.Rows)
566 {
567 var value1 = row.Value.GetField(keyFieldName);
568 var value2 = recordValue.GetField(keyFieldName);
569
570 if (value1.TryGetPrimitiveValue(out object primaryKeyValue1) && value2.TryGetPrimitiveValue(out object primaryKeyValue2) && primaryKeyValue1.ToString() == primaryKeyValue2.ToString())
💬 Async overload available for RecordValue.GetField (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\tests\Microsoft.PowerFx.Interpreter.Tests.Shared\MutationFunctionsTests.cs (line 568)
565 foreach (var row in _inner.Rows)
566 {
567 var value1 = row.Value.GetField(keyFieldName);
568 var value2 = recordValue.GetField(keyFieldName);
569
570 if (value1.TryGetPrimitiveValue(out object primaryKeyValue1) && value2.TryGetPrimitiveValue(out object primaryKeyValue2) && primaryKeyValue1.ToString() == primaryKeyValue2.ToString())
571 {
💬 Async overload available for RecordValue.GetField (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 48 hits
📄 src\libraries\Microsoft.PowerFx.Core\Public\Values\RecordValue.cs (line 165)
162
163 public FormulaValue GetField(string fieldName)
164 {
165 return GetFieldAsync(fieldName, CancellationToken.None).Result;
166 }
167
168 /// <summary>
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\libraries\Microsoft.PowerFx.Core\Public\Values\RecordValue.cs (line 198)
195 // Internal, for already verified values.
196 internal FormulaValue GetField(FormulaType fieldType, string fieldName)
197 {
198 return GetFieldAsync(fieldType, fieldName, CancellationToken.None).Result;
199 }
200
201 internal async Task<FormulaValue> GetFieldAsync(FormulaType fieldType, string fieldName, CancellationToken cancellationToken)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS049 Comparing strings without StringComparison 8 hits
📄 src\libraries\Microsoft.PowerFx.Interpreter\Functions\Mutation\RemoveFunction.cs (line 215)
212 {
213 var lastArgValue = (string)lastArg.ToObject();
214
215 if (lastArgValue.ToUpperInvariant() == "ALL")
216 {
217 all = true;
218 toExclude = 2;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\libraries\Microsoft.PowerFx.Interpreter\Functions\Mutation\RemoveFunction.cs (line 144)
141 {
142 var strNode = (StrLitNode)args[i];
143
144 if (strNode.Value.ToUpperInvariant() != "ALL")
145 {
146 fValid = false;
147 errors.EnsureError(args[i], ErrRemoveAllArg, args[i]);
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS057 Collection manipulated during traversal 2 hits
📄 src\libraries\Microsoft.PowerFx.Core\Texl\Intellisense\IntellisenseSuggestion.cs (line 290)
287 {
288 if (a._argCount < argCount)
289 {
290 _overloads.Remove(a);
291 }
292 }
293 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\libraries\Microsoft.PowerFx.Core\Texl\Intellisense\IntellisenseSuggestion.cs (line 290)
287 {
288 if (a._argCount < argCount)
289 {
290 _overloads.Remove(a);
291 }
292 }
293 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 10 hits
📄 src\libraries\Microsoft.PowerFx.Core\Functions\TexlFunction.cs (line 528)
525
526 for (var i = 0; i < args.Length; i++)
527 {
528 argHash += args[i].ToString();
529 }
530
531 return Hashing.HashString(argHash);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\libraries\Microsoft.PowerFx.Core\Texl\Builtins\Match.cs (line 374)
371 if (captureName == ColumnName_FullMatch.Value)
372 {
373 fullMatchHidden = true;
374 errorParam += ColumnName_FullMatch.Value + " ";
375 }
376 else if (captureName == ColumnName_SubMatches.Value && alteredOptions.Contains(MatchOptionChar.NumberedSubMatches))
377 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 src\tests\Microsoft.PowerFx.Connectors.Tests.Shared\Helpers\LoggingTestServer.cs (line 187)
184 using HttpRequestMessage clone = new HttpRequestMessage(request.Method, request.RequestUri);
185
186 // Copy the request's content (via a MemoryStream) into the cloned object
187 using var ms = new MemoryStream();
188 if (request.Content != null)
189 {
190 await request.Content.CopyToAsync(ms, cancellationToken);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\tests\Microsoft.PowerFx.Connectors.Tests.Shared\LivePublicSwaggerTests.cs (line 241)
238 private static async Task<OpenApiDocument> ReadSwaggerFromUrl(string url, ITestOutputHelper output)
239 {
240 using HttpClient http = new HttpClient();
241 using Stream stream = await http.GetStreamAsync(new Uri(url));
242 OpenApiReaderSettings oars = new OpenApiReaderSettings() { RuleSet = ConnectorFunction.DefaultValidationRuleSet };
243 ReadResult rr = await new OpenApiStreamReader(oars).ReadAsync(stream, CancellationToken.None);
244 OpenApiDiagnostic diag = rr.OpenApiDiagnostic;
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 32 hits
📄 src\tools\Repl\Program.cs (line 809)
806 // Implementation of ICopilotService using OpenAI Responses API
807 internal class ChatGptCopilotService : ICopilotService
808 {
809 private readonly HttpClient _httpClient;
810 private readonly ChatGptCredentials _credentials;
811 private bool _disposed;
812
💬 Disposable field _httpClient in type ChatGptCopilotService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\tools\Repl\Program.cs (line 187)
184 private class MyRepl : PowerFxREPL, IDisposable
185 {
186 public int _promptNumber = 1;
187 private readonly ICopilotService _copilotService;
188 private bool _disposed;
189
190 public override string Prompt => _numberedPrompts ? $"\n{_promptNumber++}>> " : "\n>> ";
💬 Disposable field _copilotService in type MyRepl is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Ocelot

978 total diagnostics across 16 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 54 hits
No source samples extracted
SS003 Integer divided by integer causing implicit rounding 60 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 12 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 24 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 12 hits
No source samples extracted
SS019 Switch is missing default label 6 hits
No source samples extracted
SS021 Test method without test attribute 6 hits
No source samples extracted
SS033 Async overload is available 450 hits
No source samples extracted
SS034 Accessing Task.Result without await 48 hits
No source samples extracted
SS037 HttpClient instantiated directly 24 hits
No source samples extracted
SS038 HttpContext stored in a field 36 hits
No source samples extracted
SS049 Comparing strings without StringComparison 6 hits
No source samples extracted
SS054 Newtonsoft.Json mixed with System.Text.Json 18 hits
No source samples extracted
SS056 HttpRequest.Form read synchronously 6 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 48 hits
No source samples extracted
SS066 Disposable field is not disposed 168 hits
No source samples extracted

octokit.net

954 total diagnostics across 18 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 256 hits
📄 Octokit.Tests.Integration\Clients\MilestonesClientTests.cs (line 26)
23 [IntegrationTest]
24 public async Task CanRetrieveOneMilestone()
25 {
26 var newMilestone = new NewMilestone("a milestone") { DueOn = DateTime.Now };
27 var created = await _milestonesClient.Create(_context.RepositoryOwner, _context.RepositoryName, newMilestone);
28
29 var result = await _milestonesClient.Get(_context.RepositoryOwner, _context.RepositoryName, created.Number);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Octokit.Tests.Integration\Clients\MilestonesClientTests.cs (line 37)
34 [IntegrationTest]
35 public async Task CanRetrieveOneMilestoneWithRepositoryId()
36 {
37 var newMilestone = new NewMilestone("a milestone") { DueOn = DateTime.Now };
38 var created = await _milestonesClient.Create(_context.Repository.Id, newMilestone);
39
40 var result = await _milestonesClient.Get(_context.Repository.Id, created.Number);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 4 hits
📄 Octokit.AsyncPaginationExtension\PaginatedList.cs (line 25)
22
23 private async Task<T?> Get(int index)
24 {
25 var page = await _pages[index / _pageSize].ConfigureAwait(false);
26 index %= _pageSize;
27 return page.Count > index ? page[index] : default;
28 }
💬 The operands in the divisive expression index / _pageSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Octokit.AsyncPaginationExtension\PaginatedList.cs (line 25)
22
23 private async Task<T?> Get(int index)
24 {
25 var page = await _pages[index / _pageSize].ConfigureAwait(false);
26 index %= _pageSize;
27 return page.Count > index ? page[index] : default;
28 }
💬 The operands in the divisive expression index / _pageSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 16 hits
📄 Octokit.Tests.Integration\Clients\ReferencesClientTests.cs (line 114)
111 var firstRefsPage = await _fixture.GetAll("octokit", "octokit.net", startOptions);
112 var secondRefsPage = await _fixture.GetAll("octokit", "octokit.net", skipStartOptions);
113
114 Assert.DoesNotContain(firstRefsPage, x => secondRefsPage.Contains(x));
115 }
116
117 [IntegrationTest(Skip = "This is paging for a long long time")]
💬 Type Reference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Octokit.Tests.Integration\Clients\ReferencesClientTests.cs (line 172)
169 var firstRefsPage = await _fixture.GetAll(7528679, startOptions);
170 var secondRefsPage = await _fixture.GetAll(7528679, skipStartOptions);
171
172 Assert.DoesNotContain(firstRefsPage, x => secondRefsPage.Contains(x));
173 }
174
175 [IntegrationTest]
💬 Type Reference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 2 hits
📄 Octokit\Http\ProductHeaderValue.cs (line 81)
78
79 public override int GetHashCode()
80 {
81 return _productHeaderValue.GetHashCode();
82 }
83
84 public override string ToString()
💬 GetHashCode() refers to mutable field _productHeaderValue (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Octokit\Http\ProductHeaderValue.cs (line 81)
78
79 public override int GetHashCode()
80 {
81 return _productHeaderValue.GetHashCode();
82 }
83
84 public override string ToString()
💬 GetHashCode() refers to mutable field _productHeaderValue (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 Octokit.Tests.Conventions\TypeExtensions.cs (line 127)
124
125 public enum TypeCategory { Other, Task, GenericTask, ReadOnlyList, ClientInterface }
126
127 public struct CustomTypeInfo
128 {
129 public Type Type { get; set; }
130 public TypeCategory TypeCategory { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CustomTypeInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Octokit.Tests.Conventions\TypeExtensions.cs (line 127)
124
125 public enum TypeCategory { Other, Task, GenericTask, ReadOnlyList, ClientInterface }
126
127 public struct CustomTypeInfo
128 {
129 public Type Type { get; set; }
130 public TypeCategory TypeCategory { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CustomTypeInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 Octokit\Http\ApiConnection.cs (line 672)
669
670 var response = await Connection.GetResponse<IReadOnlyList<T>>(uri, cancellationToken).ConfigureAwait(false);
671
672 switch (response.HttpResponse.StatusCode)
673 {
674 case HttpStatusCode.Accepted:
675 continue;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Octokit\Http\ApiConnection.cs (line 672)
669
670 var response = await Connection.GetResponse<IReadOnlyList<T>>(uri, cancellationToken).ConfigureAwait(false);
671
672 switch (response.HttpResponse.StatusCode)
673 {
674 case HttpStatusCode.Accepted:
675 continue;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 14 hits
📄 Octokit\Http\SimpleJsonSerializer.cs (line 219)
216
217 private static Type GetPayloadType(string activityType)
218 {
219 switch (activityType)
220 {
221 case "CheckRunEvent":
222 return typeof(CheckRunEventPayload);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Octokit\Models\Request\ProjectCardMove.cs (line 12)
9 public ProjectCardMove(ProjectCardPosition position, int columnId, long? cardId)
10 {
11 ColumnId = columnId;
12 switch (position)
13 {
14 case ProjectCardPosition.Top:
15 Position = "top";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 6 hits
📄 Octokit\Helpers\PropertyOrField.cs (line 104)
101
102 if (getDelegate == null)
103 {
104 throw new InvalidOperationException("Property and Field cannot both be null");
105 }
106
107 if (Base64Encoded)
💬 An exception is thrown from the getter of property GetDelegate (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Octokit\Helpers\PropertyOrField.cs (line 135)
132 }
133 if (setDelegate == null)
134 {
135 throw new InvalidOperationException("Property and Field cannot both be null");
136 }
137 if (Base64Encoded)
138 {
💬 An exception is thrown from the getter of property SetDelegate (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS032 Thread.Sleep used in async method 24 hits
📄 Octokit.Tests.Integration\Clients\MigrationsClientTests.cs (line 138)
135 {
136 while (!isExported)
137 {
138 Thread.Sleep(2000);
139 }
140
141 var contents = await _gitHub.Migration.Migrations.GetArchive(_orgName, _migrationContext.Id);
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 Octokit.Tests.Integration\Clients\MigrationsClientTests.cs (line 151)
148 {
149 while (!isExported)
150 {
151 Thread.Sleep(2000);
152 }
153
154 await _gitHub.Migration.Migrations.DeleteArchive(_orgName, _migrationContext.Id);
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 6 hits
📄 Octokit.Generators\AsyncPaginationExtensionsGenerator.cs (line 70)
67 {
68 var type = Path.GetFileNameWithoutExtension(file);
69
70 foreach (var line in File.ReadAllLines(file))
71 {
72 var match = paginatedCallRegex.Match(line);
73
💬 Async overload available for File.ReadAllLines (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Octokit.Tests.Integration\Clients\ActionsWorkflowRunsClientTests.cs (line 176)
173
174 try
175 {
176 File.WriteAllBytes(tempFile, logs);
177
178 using (var archive = ZipFile.OpenRead(tempFile))
179 {
💬 Async overload available for File.WriteAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 586 hits
📄 Octokit\Http\Connection.cs (line 713)
710 {
711 var credentialTask = CredentialStore.GetCredentials();
712 if (credentialTask == null) return Credentials.Anonymous;
713 return credentialTask.Result ?? Credentials.Anonymous;
714 }
715 // Note this is for convenience. We probably shouldn't allow this to be mutable.
716 set
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Octokit.Tests.Integration\Clients\AssigneesClientTests.cs (line 19)
16 _github = Helper.GetAuthenticatedClient();
17 var repoName = Helper.MakeNameWithTimestamp("public-repo");
18
19 _context = _github.CreateRepositoryContext(new NewRepository(repoName)).Result;
20 }
21
22 [IntegrationTest]
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 8 hits
📄 Octokit.Tests.Integration\Clients\RepositoriesClientTests.cs (line 722)
719 using (var repoContext = await _github.CreateUserRepositoryContext())
720 {
721 var reference = _github.Git.Reference.GetAll(repoContext.RepositoryOwner, repoContext.RepositoryName).Result.First();
722 _github.Git.Reference.Create(repoContext.RepositoryId, new NewReference("refs/heads/primary", reference.Object.Sha)).Wait();
723 var update = new RepositoryUpdate() { DefaultBranch = "primary" };
724
725 var updatedRepository = await _github.Repository.Edit(repoContext.RepositoryOwner, repoContext.RepositoryName, update);
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 Octokit.Tests.Integration\Clients\RepositoriesClientTests.cs (line 737)
734 using (var repoContext = await _github.CreateUserRepositoryContext())
735 {
736 var reference = _github.Git.Reference.GetAll(repoContext.RepositoryOwner, repoContext.RepositoryName).Result.First();
737 _github.Git.Reference.Create(repoContext.RepositoryId, new NewReference("refs/heads/primary", reference.Object.Sha)).Wait();
738 var update = new RepositoryUpdate() { DefaultBranch = "primary" };
739
740 var updatedRepository = await _github.Repository.Edit(repoContext.RepositoryId, update);
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS041 Unnecessary enumerable materialization 4 hits
📄 Octokit.Tests.Conventions\PreviewsTests.cs (line 79)
76
77 var validHeaders = defaultHeaders.Concat(previewAcceptHeaders);
78
79 var notAllowedHeaders = values.Values.ToList().Except(validHeaders).OrderBy(k => k);
80 if (notAllowedHeaders.Any())
81 {
82 throw new InvalidAcceptHeadersFound(notAllowedHeaders);
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 Octokit.Tests.Conventions\PreviewsTests.cs (line 79)
76
77 var validHeaders = defaultHeaders.Concat(previewAcceptHeaders);
78
79 var notAllowedHeaders = values.Values.ToList().Except(validHeaders).OrderBy(k => k);
80 if (notAllowedHeaders.Any())
81 {
82 throw new InvalidAcceptHeadersFound(notAllowedHeaders);
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 Octokit.Tests.Integration\PotentiallyFlakyTestAttribute.cs (line 10)
7 /// * Calls for details of repositories which already exist and was not created by the test itself (so could disappear over time)
8 /// * Calls for details of users which already exist (so could disappear over time)
9 /// </summary>
10 public class PotentiallyFlakyTestAttribute : Attribute
11 {
12 }
13}
💬 PotentiallyFlakyTestAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 Octokit.Tests.Integration\PotentiallyFlakyTestAttribute.cs (line 10)
7 /// * Calls for details of repositories which already exist and was not created by the test itself (so could disappear over time)
8 /// * Calls for details of users which already exist (so could disappear over time)
9 /// </summary>
10 public class PotentiallyFlakyTestAttribute : Attribute
11 {
12 }
13}
💬 PotentiallyFlakyTestAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS047 LINQ traversal before filter 4 hits
📄 Octokit.Tests.Conventions\TypeExtensions.cs (line 30)
27 // the same effect as cancelling the token, so we should
28 // think about how we want to ensure these conventions are
29 // validated
30 return type.GetMethods().OrderBy(m => m.Name)
31 .Where(m => m.GetParameters().All(p => p.ParameterType != typeof(CancellationToken)))
32 .ToArray();
33 }
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 Octokit.Tests.Conventions\TypeExtensions.cs (line 30)
27 // the same effect as cancelling the token, so we should
28 // think about how we want to ensure these conventions are
29 // validated
30 return type.GetMethods().OrderBy(m => m.Name)
31 .Where(m => m.GetParameters().All(p => p.ParameterType != typeof(CancellationToken)))
32 .ToArray();
33 }
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS058 String concatenated in a loop 4 hits
📄 Octokit\Helpers\StringExtensions.cs (line 61)
58 var parameterProperty = values.GetType().GetProperty(parameter);
59 if (parameterProperty != null)
60 {
61 expansion += string.IsNullOrWhiteSpace(expansion) ? "?" : "&";
62 expansion += parameter + "=" +
63 Uri.EscapeDataString("" + parameterProperty.GetValue(values, new object[0]));
64 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Octokit\Helpers\StringExtensions.cs (line 62)
59 if (parameterProperty != null)
60 {
61 expansion += string.IsNullOrWhiteSpace(expansion) ? "?" : "&";
62 expansion += parameter + "=" +
63 Uri.EscapeDataString("" + parameterProperty.GetValue(values, new object[0]));
64 }
65 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 Octokit.Tests.Integration\Clients\ReleasesClientTests.cs (line 667)
664
665 string textContent;
666
667 using (var zipstream = new MemoryStream((byte[])response.Body))
668 using (var archive = new ZipArchive(zipstream))
669 {
670 var entry = archive.Entries[0];
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Octokit.Tests.Integration\Clients\ReleasesClientTests.cs (line 667)
664
665 string textContent;
666
667 using (var zipstream = new MemoryStream((byte[])response.Body))
668 using (var archive = new ZipArchive(zipstream))
669 {
670 var entry = archive.Entries[0];
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 8 hits
📄 Octokit.Tests\Http\RedirectHandlerTests.cs (line 181)
178
179 public class MockRedirectHandler : HttpMessageHandler
180 {
181 readonly HttpResponseMessage _response1;
182 readonly HttpResponseMessage _response2;
183 private bool _Response1Sent;
184
💬 Disposable field _response1 in type MockRedirectHandler is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Octokit.Tests\Http\RedirectHandlerTests.cs (line 182)
179 public class MockRedirectHandler : HttpMessageHandler
180 {
181 readonly HttpResponseMessage _response1;
182 readonly HttpResponseMessage _response2;
183 private bool _Response1Sent;
184
185 public MockRedirectHandler(HttpResponseMessage response1, HttpResponseMessage response2 = null)
💬 Disposable field _response2 in type MockRedirectHandler is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

MessagePack-CSharp

938 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
No source samples extracted
SS003 Integer divided by integer causing implicit rounding 284 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 48 hits
No source samples extracted
SS006 Throwing null will always result in a runtime exception 24 hits
No source samples extracted
SS007 [Flags] enum values are not powers of two 6 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 4 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 212 hits
No source samples extracted
SS018 Switch does not handle all enum options 2 hits
No source samples extracted
SS019 Switch is missing default label 44 hits
No source samples extracted
SS033 Async overload is available 2 hits
No source samples extracted
SS044 Attribute must specify [AttributeUsage] 10 hits
No source samples extracted
SS046 Unbounded stackalloc 240 hits
No source samples extracted
SS047 LINQ traversal before filter 24 hits
No source samples extracted
SS048 Locking on discouraged object (string, Type, this) 24 hits
No source samples extracted
SS066 Disposable field is not disposed 12 hits
No source samples extracted

NLog

910 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 16 hits
No source samples extracted
SS003 Integer divided by integer causing implicit rounding 102 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 64 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 8 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 316 hits
No source samples extracted
SS018 Switch does not handle all enum options 8 hits
No source samples extracted
SS019 Switch is missing default label 126 hits
No source samples extracted
SS023 Exception thrown from property getter 24 hits
No source samples extracted
SS044 Attribute must specify [AttributeUsage] 8 hits
No source samples extracted
SS057 Collection manipulated during traversal 16 hits
No source samples extracted
SS058 String concatenated in a loop 52 hits
No source samples extracted
SS066 Disposable field is not disposed 170 hits
No source samples extracted

quartznet

892 total diagnostics across 13 rules

SS003 Integer divided by integer causing implicit rounding 64 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 148 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 56 hits
No source samples extracted
SS018 Switch does not handle all enum options 4 hits
No source samples extracted
SS019 Switch is missing default label 28 hits
No source samples extracted
SS033 Async overload is available 12 hits
No source samples extracted
SS034 Accessing Task.Result without await 4 hits
No source samples extracted
SS048 Locking on discouraged object (string, Type, this) 4 hits
No source samples extracted
SS051 Locking on mutable reference 12 hits
No source samples extracted
SS058 String concatenated in a loop 4 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 532 hits
No source samples extracted
SS064 Unnecessary ToString() on Span 4 hits
No source samples extracted
SS066 Disposable field is not disposed 20 hits
No source samples extracted

ClosedXML

858 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 64 hits
📄 ClosedXML\Excel\CalcEngine\ScalarValue.cs (line 311)
308 // Format 17 'mmm-yy'
309 if (DateTime.TryParseExact(text, new[] { "MMM-y", "MMMM-y" }, culture, dateStyle, out var dateFormat17))
310 {
311 if (dateFormat17.Year != DateTime.Now.Year && dateFormat17.Year >= 2030)
312 dateFormat17 = dateFormat17.AddYears(-100);
313
314 return ToSerialDate(dateFormat17, out serialDateTime);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 ClosedXML\Excel\CalcEngine\Functions\DateAndTime.cs (line 381)
378
379 private static ScalarValue Now()
380 {
381 return DateTime.Now.ToSerialDateTime();
382 }
383
384 private static ScalarValue Second(CalcContext ctx, double serialDate)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 168 hits
📄 ClosedXML\Excel\Coordinates\Emu.cs (line 15)
12 private const int PerInch = 914400;
13 private const int PerCm = 360000;
14 private const int PerMm = PerCm / 10;
15 private const int PerPt = PerInch / 72;
16 private const int PerPc = PerInch / 6;
17
18 private readonly AbsLengthUnit _preferredUnit;
💬 The operands in the divisive expression PerInch / 72 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 ClosedXML\Excel\Coordinates\Emu.cs (line 16)
13 private const int PerCm = 360000;
14 private const int PerMm = PerCm / 10;
15 private const int PerPt = PerInch / 72;
16 private const int PerPc = PerInch / 6;
17
18 private readonly AbsLengthUnit _preferredUnit;
19
💬 The operands in the divisive expression PerInch / 6 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 74 hits
📄 ClosedXML\Excel\CalcEngine\Reference.cs (line 90)
87 {
88 var lhsWorksheets = lhs.Areas.Count == 1
89 ? lhs.Areas.Select(a => a.Worksheet).Where(ws => ws is not null).ToList()!
90 : lhs.Areas.Select(a => a.Worksheet ?? contextWorksheet).Where(ws => ws is not null).Distinct().ToList();
91 if (lhsWorksheets.Count() > 1)
92 return XLError.IncompatibleValue;
93
💬 Type XLWorksheet is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 ClosedXML\Excel\CalcEngine\Reference.cs (line 98)
95
96 var rhsWorksheets = rhs.Areas.Count == 1
97 ? rhs.Areas.Select(a => a.Worksheet).Where(ws => ws is not null).ToList()!
98 : rhs.Areas.Select(a => a.Worksheet ?? contextWorksheet).Where(ws => ws is not null).Distinct().ToList();
99 if (rhsWorksheets.Count() > 1)
100 return XLError.IncompatibleValue;
101
💬 Type XLWorksheet is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 208 hits
📄 ClosedXML\Excel\Cells\SharedStringTable.cs (line 179)
176 {
177 unchecked
178 {
179 return ((Value is not null ? Value.GetHashCode() : 0) * 397) ^ Inline.GetHashCode();
180 }
181 }
182 }
💬 GetHashCode() refers to mutable field Value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 ClosedXML\Excel\Cells\SharedStringTable.cs (line 179)
176 {
177 unchecked
178 {
179 return ((Value is not null ? Value.GetHashCode() : 0) * 397) ^ Inline.GetHashCode();
180 }
181 }
182 }
💬 GetHashCode() refers to mutable field Value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 122 hits
📄 ClosedXML.IO.CodeGen\Unit.cs (line 6)
3/// <summary>
4/// A type to use in generics instead of <c>void</c>.
5/// </summary>
6internal struct Unit
7{
8 public static readonly Unit Value = new();
9};
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Unit. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 ClosedXML\Graphics\Dpi.cs (line 8)
5 /// <summary>
6 /// A DPI resolution.
7 /// </summary>
8 public readonly struct Dpi
9 {
10 /// <summary>
11 /// Horizontal DPI resolution.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Dpi. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 28 hits
📄 ClosedXML.IO\XmlTreeReader.cs (line 251)
248 {
249 // All unspecified nodes should be skipped. It is either comments, processing
250 // instructions or something that shouldn't ever happen (e.g. attribute).
251 switch (nodeType)
252 {
253 case XmlNodeType.Text:
254 case XmlNodeType.Whitespace:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 ClosedXML.IO\XmlTreeReader.cs (line 251)
248 {
249 // All unspecified nodes should be skipped. It is either comments, processing
250 // instructions or something that shouldn't ever happen (e.g. attribute).
251 switch (nodeType)
252 {
253 case XmlNodeType.Text:
254 case XmlNodeType.Whitespace:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 100 hits
📄 ClosedXML.IO\XmlTreeReader.cs (line 251)
248 {
249 // All unspecified nodes should be skipped. It is either comments, processing
250 // instructions or something that shouldn't ever happen (e.g. attribute).
251 switch (nodeType)
252 {
253 case XmlNodeType.Text:
254 case XmlNodeType.Whitespace:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 ClosedXML.IO\XmlTreeReader.cs (line 251)
248 {
249 // All unspecified nodes should be skipped. It is either comments, processing
250 // instructions or something that shouldn't ever happen (e.g. attribute).
251 switch (nodeType)
252 {
253 case XmlNodeType.Text:
254 case XmlNodeType.Whitespace:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 8 hits
📄 ClosedXML.Tests\Examples\ColumnsTests.cs (line 35)
32 }
33
34 //[Test] // Not working yet
35 public void InsertColumns()
36 {
37 TestHelper.RunTestExample<InsertColumns>(@"Columns\InsertColumns.xlsx");
38 }
💬 Method InsertColumns might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 ClosedXML.Tests\Examples\RowsTests.cs (line 29)
26 }
27
28 //[Test] // Not working yet
29 public void InsertRows()
30 {
31 TestHelper.RunTestExample<InsertRows>(@"Rows\InsertRows.xlsx");
32 }
💬 Method InsertRows might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS023 Exception thrown from property getter 44 hits
📄 ClosedXML\Excel\Hyperlinks\XLHyperlink_public.cs (line 103)
100 }
101
102 if (Container is null)
103 throw new InvalidOperationException("Hyperlink is not attached to a worksheet.");
104
105 var sheetName = Container.WorksheetName;
106 return String.Concat(
💬 An exception is thrown from the getter of property InternalAddress (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 ClosedXML\Excel\Style\Colors\XLColor_Public.cs (line 45)
42 get
43 {
44 if (ColorType == XLColorType.Theme)
45 throw new InvalidOperationException("Cannot convert theme color to Color.");
46
47 if (ColorType == XLColorType.Indexed)
48 return IndexedColors[Indexed].Color;
💬 An exception is thrown from the getter of property Color (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS046 Unbounded stackalloc 8 hits
📄 ClosedXML\Excel\Cells\XLCell.cs (line 2057)
2054 // If we have more than 1 code unit per grapheme, the code units can
2055 // be distributed through multiple grapheme. In the worst case, all extra
2056 // code units are in exactly one grapheme -> allocate buffer of that size.
2057 Span<int> codePointsBuffer = stackalloc int[1 + text.Length - graphemeStarts.Length];
2058 for (var i = 0; i < graphemeStarts.Length; ++i)
2059 {
2060 var startIdx = graphemeStarts[i];
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
📄 ClosedXML\Excel\CalcEngine\Functions\Text.cs (line 678)
675 return XLError.IncompatibleValue;
676
677 // Process by ODF specification. Add one character for optional 0 before decimal.
678 Span<char> textSpan = stackalloc char[text.Length + 1];
679 var newLength = 0;
680 var decimalSeen = false;
681 foreach (var c in text)
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
SS049 Comparing strings without StringComparison 16 hits
📄 ClosedXML\Excel\XLWorkbook_Load.cs (line 839)
836 {
837 var moveWithCellsElement = clientData.Elements().FirstOrDefault(e => e.Name.LocalName == "MoveWithCells");
838 var sizeWithCellsElement = clientData.Elements().FirstOrDefault(e => e.Name.LocalName == "SizeWithCells");
839 Boolean moveWithCells = !(moveWithCellsElement != null && moveWithCellsElement.Value.ToLower() == "true");
840 Boolean sizeWithCells = !(sizeWithCellsElement != null && sizeWithCellsElement.Value.ToLower() == "true");
841 if (moveWithCells && !sizeWithCells)
842 drawing.Style.Properties.Positioning = XLDrawingAnchor.MoveWithCells;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 ClosedXML\Excel\XLWorkbook_Load.cs (line 840)
837 var moveWithCellsElement = clientData.Elements().FirstOrDefault(e => e.Name.LocalName == "MoveWithCells");
838 var sizeWithCellsElement = clientData.Elements().FirstOrDefault(e => e.Name.LocalName == "SizeWithCells");
839 Boolean moveWithCells = !(moveWithCellsElement != null && moveWithCellsElement.Value.ToLower() == "true");
840 Boolean sizeWithCells = !(sizeWithCellsElement != null && sizeWithCellsElement.Value.ToLower() == "true");
841 if (moveWithCells && !sizeWithCells)
842 drawing.Style.Properties.Positioning = XLDrawingAnchor.MoveWithCells;
843 else if (moveWithCells && sizeWithCells)
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS057 Collection manipulated during traversal 4 hits
📄 ClosedXML\Excel\CalcEngine\DependencyTree.cs (line 257)
254 _dependents[i] = _dependents[_dependents.Count - 1];
255
256 // Remove last item, capacity is unchanged, only list size is updated.
257 _dependents.RemoveAt(_dependents.Count - 1);
258 }
259 }
260
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 ClosedXML\Excel\CalcEngine\DependencyTree.cs (line 257)
254 _dependents[i] = _dependents[_dependents.Count - 1];
255
256 // Remove last item, capacity is unchanged, only list size is updated.
257 _dependents.RemoveAt(_dependents.Count - 1);
258 }
259 }
260
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 8 hits
📄 ClosedXML.IO\XmlTreeReader.cs (line 260)
257 if (value.Length == 0)
258 value = _reader.Value;
259 else
260 value += _reader.Value;
261 break;
262 case XmlNodeType.EntityReference:
263 value += _reader.Name; // Does it even work? I have no idea how to get this node.
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 ClosedXML.IO\XmlTreeReader.cs (line 260)
257 if (value.Length == 0)
258 value = _reader.Value;
259 else
260 value += _reader.Value;
261 break;
262 case XmlNodeType.EntityReference:
263 value += _reader.Name; // Does it even work? I have no idea how to get this node.
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS064 Unnecessary ToString() on Span 2 hits
📄 ClosedXML\Excel\CalcEngine\Functions\Text.cs (line 717)
714 percentCount++;
715 }
716
717 if (!double.TryParse(textSpan.ToString(), NumberStyles.Float | NumberStyles.AllowParentheses, CultureInfo.InvariantCulture, out var number))
718 return XLError.IncompatibleValue;
719
720 // Too large exponent can return infinity
💬 Unnecessary ToString() call, an overload that accepts Span<char> is available (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS064-UnnecessaryToStringOnSpan.md)
📄 ClosedXML\Excel\CalcEngine\Functions\Text.cs (line 717)
714 percentCount++;
715 }
716
717 if (!double.TryParse(textSpan.ToString(), NumberStyles.Float | NumberStyles.AllowParentheses, CultureInfo.InvariantCulture, out var number))
718 return XLError.IncompatibleValue;
719
720 // Too large exponent can return infinity
💬 Unnecessary ToString() call, an overload that accepts Span<char> is available (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS064-UnnecessaryToStringOnSpan.md)
SS066 Disposable field is not disposed 4 hits
📄 ClosedXML\Excel\XLWorkbook.cs (line 728)
725
726 private XLLoadSource _loadSource = XLLoadSource.New;
727 private String _originalFile;
728 private Stream _originalStream;
729 private XLWorkbookProtection _workbookProtection;
730
731 #endregion Fields
💬 Disposable field _originalStream in type XLWorkbook is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 ClosedXML\Excel\XLWorkbook.cs (line 728)
725
726 private XLLoadSource _loadSource = XLLoadSource.New;
727 private String _originalFile;
728 private Stream _originalStream;
729 private XLWorkbookProtection _workbookProtection;
730
731 #endregion Fields
💬 Disposable field _originalStream in type XLWorkbook is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

opentk

836 total diagnostics across 13 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 src\Generator.Bind\Main.cs (line 207)
204
205 foreach (var generator in Generators)
206 {
207 long ticks = DateTime.Now.Ticks;
208
209 generator.Process();
210
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Generator.Bind\Main.cs (line 214)
211 var writer = new CSharpSpecWriter();
212 writer.WriteBindings(generator);
213
214 ticks = DateTime.Now.Ticks - ticks;
215
216 Console.WriteLine();
217 Console.WriteLine("Bindings generated in {0} seconds.", ticks / (double)10000000.0);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 84 hits
📄 src\OpenTK.Mathematics\Vector\Vector4i.cs (line 364)
361 /// <param name="result">Result of the operation.</param>
362 public static void Divide(in Vector4i vector, int scale, out Vector4i result)
363 {
364 result.X = vector.X / scale;
365 result.Y = vector.Y / scale;
366 result.Z = vector.Z / scale;
367 result.W = vector.W / scale;
💬 The operands in the divisive expression vector.X / scale are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\OpenTK.Mathematics\Vector\Vector4i.cs (line 365)
362 public static void Divide(in Vector4i vector, int scale, out Vector4i result)
363 {
364 result.X = vector.X / scale;
365 result.Y = vector.Y / scale;
366 result.Z = vector.Z / scale;
367 result.W = vector.W / scale;
368 }
💬 The operands in the divisive expression vector.Y / scale are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 src\Generator.Rewrite\Program.cs (line 193)
190 {
191 if (method.HasPInvokeInfo)
192 {
193 if (removedModuleReferences.Contains(method.PInvokeInfo.Module))
194 {
195 Console.Error.WriteLine($"The method {method} still references a removed ModuleReference {method.PInvokeInfo.Module}");
196 }
💬 Type ModuleReference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Generator.Bind\CSharpSpecWriter.cs (line 236)
233 // Emit native signatures.
234 // These are required by the patcher.
235 int current_signature = 0;
236 foreach (var d in wrappers.Values.SelectMany(e => e).Select(w => w.WrappedDelegate).Distinct())
237 {
238 sw.WriteLine("[Slot({0})]", d.Slot);
239 sw.WriteLine("[DllImport(Library, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]");
💬 Type Delegate is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 486 hits
📄 src\OpenTK.Mathematics\Data\Color4.cs (line 189)
186 /// <returns>A System.Int32 containing the hashcode of this Color4 structure.</returns>
187 public override readonly int GetHashCode()
188 {
189 return HashCode.Combine(R, G, B, A);
190 }
191
192 /// <summary>
💬 GetHashCode() refers to mutable field R (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\OpenTK.Mathematics\Data\Color4.cs (line 189)
186 /// <returns>A System.Int32 containing the hashcode of this Color4 structure.</returns>
187 public override readonly int GetHashCode()
188 {
189 return HashCode.Combine(R, G, B, A);
190 }
191
192 /// <summary>
💬 GetHashCode() refers to mutable field G (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS015 String placeholders in wrong order 64 hits
📄 src\OpenTK.Mathematics\Vector\Vector4i.cs (line 1855)
1852 /// <inheritdoc />
1853 public readonly string ToString(string format, IFormatProvider formatProvider)
1854 {
1855 return string.Format(
1856 "({0}{4} {1}{4} {2}{4} {3})",
1857 X.ToString(format, formatProvider),
1858 Y.ToString(format, formatProvider),
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 src\OpenTK.Mathematics\Vector\Vector2b.cs (line 359)
356 /// <inheritdoc cref="IFormattable.ToString(string?, IFormatProvider?)"/>
357 public readonly string ToString(IFormatProvider formatProvider)
358 {
359 return string.Format(
360 "({0}{2} {1})",
361 X.ToString(formatProvider),
362 Y.ToString(formatProvider),
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 132 hits
📄 src\OpenTK.Mathematics\Geometry\BezierCurveCubic.cs (line 18)
15 /// Represents a cubic bezier curve with two anchor and two control points.
16 /// </summary>
17 [Serializable]
18 public struct BezierCurveCubic
19 {
20 /// <summary>
21 /// Start anchor point.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BezierCurveCubic. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\OpenTK.Mathematics\Geometry\BezierCurveQuadric.cs (line 18)
15 /// Represents a quadric bezier curve with two anchor and one control point.
16 /// </summary>
17 [Serializable]
18 public struct BezierCurveQuadric
19 {
20 /// <summary>
21 /// Start anchor point.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BezierCurveQuadric. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 8 hits
📄 src\OpenTK.Input\Hid\HidHelper.cs (line 18)
15 /// <returns>An <see cref="int"/> that maps the HID usage value to a joystick axis.</returns>
16 public static int TranslateJoystickAxis(HidPage page, int usage)
17 {
18 switch (page)
19 {
20 case HidPage.GenericDesktop:
21 switch ((HidGenericDesktopUsage)usage)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\OpenTK.Input\Hid\HidHelper.cs (line 21)
18 switch (page)
19 {
20 case HidPage.GenericDesktop:
21 switch ((HidGenericDesktopUsage)usage)
22 {
23 case HidGenericDesktopUsage.X:
24 return 0;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 24 hits
📄 src\OpenTK.Input\Hid\HidHelper.cs (line 18)
15 /// <returns>An <see cref="int"/> that maps the HID usage value to a joystick axis.</returns>
16 public static int TranslateJoystickAxis(HidPage page, int usage)
17 {
18 switch (page)
19 {
20 case HidPage.GenericDesktop:
21 switch ((HidGenericDesktopUsage)usage)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\OpenTK.Input\Hid\HidHelper.cs (line 21)
18 switch (page)
19 {
20 case HidPage.GenericDesktop:
21 switch ((HidGenericDesktopUsage)usage)
22 {
23 case HidGenericDesktopUsage.X:
24 return 0;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 src\OpenTK.Windowing.Desktop\NativeWindow.cs (line 115)
112 {
113 if (Context == null)
114 {
115 throw new InvalidOperationException("Cannot control vsync when running with ContextAPI.NoAPI.");
116 }
117
118 return _vSync;
💬 An exception is thrown from the getter of property VSync (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\OpenTK.Windowing.Desktop\NativeWindow.cs (line 733)
730 case CursorModeValue.CursorCaptured:
731 return CursorState.Confined;
732 default:
733 throw new ArgumentOutOfRangeException();
734 }
735 }
736
💬 An exception is thrown from the getter of property CursorState (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS027 Exception thrown from Dispose 2 hits
📄 src\OpenTK.Windowing.Desktop\NativeWindow.cs (line 2054)
2051 }
2052 else
2053 {
2054 throw new GLFWException("You can only dispose windows on the main thread. The window needs to be disposed as it cannot safely be disposed in the finalizer.");
2055 }
2056 }
2057
💬 An exception is thrown from the Dispose(bool) method in type NativeWindow (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 src\OpenTK.Windowing.Desktop\NativeWindow.cs (line 2054)
2051 }
2052 else
2053 {
2054 throw new GLFWException("You can only dispose windows on the main thread. The window needs to be disposed as it cannot safely be disposed in the finalizer.");
2055 }
2056 }
2057
💬 An exception is thrown from the Dispose(bool) method in type NativeWindow (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS044 Attribute must specify [AttributeUsage] 2 hits
📄 src\OpenAL\OpenALGenerator\Program.cs (line 11)
8
9namespace OpenALGenerator
10{
11 class EntryPointAttribute : Attribute
12 {
13 public string EntryPoint;
14 public string OverloadName;
💬 EntryPointAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\OpenAL\OpenALGenerator\Program.cs (line 11)
8
9namespace OpenALGenerator
10{
11 class EntryPointAttribute : Attribute
12 {
13 public string EntryPoint;
14 public string OverloadName;
💬 EntryPointAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS046 Unbounded stackalloc 4 hits
📄 src\OpenTK.Windowing.Desktop\NativeWindow.cs (line 181)
178 unsafe
179 {
180 var images = value.Images;
181 Span<GCHandle> handles = stackalloc GCHandle[images.Length];
182 Span<GraphicsLibraryFramework.Image> glfwImages =
183 stackalloc GraphicsLibraryFramework.Image[images.Length];
184
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
📄 src\OpenTK.Windowing.Desktop\NativeWindow.cs (line 183)
180 var images = value.Images;
181 Span<GCHandle> handles = stackalloc GCHandle[images.Length];
182 Span<GraphicsLibraryFramework.Image> glfwImages =
183 stackalloc GraphicsLibraryFramework.Image[images.Length];
184
185 for (var i = 0; i < images.Length; i++)
186 {
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
SS049 Comparing strings without StringComparison 10 hits
📄 src\Generator.Bind\FuncProcessor.cs (line 708)
705 }
706
707 // Find out the necessary wrapper types.
708 if (p.CurrentType.ToLower() == "string" && p.Pointer == 0)
709 {
710 // char* -> IntPtr
711 // Due to a bug in the Mono runtime, we need
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\Generator.Bind\FuncProcessor.cs (line 720)
717 p.WrapperType |= WrapperTypes.StringParameter;
718 }
719
720 if (p.CurrentType.ToLower() == "string" && p.Pointer >= 1)
721 {
722 // string* -> [In] String[]
723 // [Out] StringBuilder[] parameter is not currently supported
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)

NAudio

736 total diagnostics across 13 rules

SS003 Integer divided by integer causing implicit rounding 302 hits
📄 NAudio.Core\Dsp\SmbPitchShifter.cs (line 62)
59 private float[] gOutFIFO = new float[MAX_FRAME_LENGTH];
60 private float[] gFFTworksp = new float[2*MAX_FRAME_LENGTH];
61 private float[] gLastPhase = new float[MAX_FRAME_LENGTH/2 + 1];
62 private float[] gSumPhase = new float[MAX_FRAME_LENGTH/2 + 1];
63 private float[] gOutputAccum = new float[2*MAX_FRAME_LENGTH];
64 private float[] gAnaFreq = new float[MAX_FRAME_LENGTH];
65 private float[] gAnaMagn = new float[MAX_FRAME_LENGTH];
💬 The operands in the divisive expression MAX_FRAME_LENGTH/2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 NAudio.Core\Dsp\SmbPitchShifter.cs (line 61)
58 private float[] gInFIFO = new float[MAX_FRAME_LENGTH];
59 private float[] gOutFIFO = new float[MAX_FRAME_LENGTH];
60 private float[] gFFTworksp = new float[2*MAX_FRAME_LENGTH];
61 private float[] gLastPhase = new float[MAX_FRAME_LENGTH/2 + 1];
62 private float[] gSumPhase = new float[MAX_FRAME_LENGTH/2 + 1];
63 private float[] gOutputAccum = new float[2*MAX_FRAME_LENGTH];
64 private float[] gAnaFreq = new float[MAX_FRAME_LENGTH];
💬 The operands in the divisive expression MAX_FRAME_LENGTH/2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 NAudio.Core\Wave\WaveFormats\WaveFormat.cs (line 286)
283 /// <returns>A hashcode</returns>
284 public override int GetHashCode()
285 {
286 return (int) waveFormatTag ^
287 (int) channels ^
288 sampleRate ^
289 averageBytesPerSecond ^
💬 GetHashCode() refers to mutable field waveFormatTag (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 NAudio.Core\Wave\WaveFormats\WaveFormat.cs (line 287)
284 public override int GetHashCode()
285 {
286 return (int) waveFormatTag ^
287 (int) channels ^
288 sampleRate ^
289 averageBytesPerSecond ^
290 (int) blockAlign ^
💬 GetHashCode() refers to mutable field channels (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS015 String placeholders in wrong order 2 hits
📄 NAudio.Midi\Midi\TempoEvent.cs (line 50)
47 /// <returns>String describing the tempo event</returns>
48 public override string ToString()
49 {
50 return String.Format("{0} {2}bpm ({1})",
51 base.ToString(),
52 microsecondsPerQuarterNote,
53 (60000000 / microsecondsPerQuarterNote));
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 NAudio.Midi\Midi\TempoEvent.cs (line 50)
47 /// <returns>String describing the tempo event</returns>
48 public override string ToString()
49 {
50 return String.Format("{0} {2}bpm ({1})",
51 base.ToString(),
52 microsecondsPerQuarterNote,
53 (60000000 / microsecondsPerQuarterNote));
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 244 hits
📄 NAudio.Core\Dsp\Complex.cs (line 6)
3 /// <summary>
4 /// Type to represent complex number
5 /// </summary>
6 public struct Complex
7 {
8 /// <summary>
9 /// Real Part
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Complex. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 NAudio.Core\Wave\SampleProviders\PanningSampleProvider.cs (line 107)
104 /// <summary>
105 /// Pair of floating point values, representing samples or multipliers
106 /// </summary>
107 public struct StereoSamplePair
108 {
109 /// <summary>
110 /// Left value
💬 Implement Equals(), GetHashCode() and ToString() methods on struct StereoSamplePair. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 8 hits
📄 NAudio.Asio\ASIODriverExt.cs (line 336)
333 private int AsioMessageCallBack(AsioMessageSelector selector, int value, IntPtr message, IntPtr opt)
334 {
335 // Check when this is called?
336 switch (selector)
337 {
338 case AsioMessageSelector.kAsioSelectorSupported:
339 AsioMessageSelector subValue = (AsioMessageSelector)Enum.ToObject(typeof(AsioMessageSelector), value);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 NAudio.Asio\ASIODriverExt.cs (line 340)
337 {
338 case AsioMessageSelector.kAsioSelectorSupported:
339 AsioMessageSelector subValue = (AsioMessageSelector)Enum.ToObject(typeof(AsioMessageSelector), value);
340 switch (subValue)
341 {
342 case AsioMessageSelector.kAsioEngineVersion:
343 return 1;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 34 hits
📄 NAudio.Core\Dsp\EnvelopeGenerator.cs (line 170)
167 /// <returns>A volume multiplier</returns>
168 public float Process()
169 {
170 switch (state)
171 {
172 case EnvelopeState.Idle:
173 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 NAudio.Asio\ASIOSampleConvertor.cs (line 28)
25 switch (asioType)
26 {
27 case AsioSampleType.Int32LSB:
28 switch (waveFormat.BitsPerSample)
29 {
30 case 16:
31 convertor = (is2Channels) ? ConvertorShortToInt2Channels : (SampleConvertor)ConvertorShortToIntGeneric;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 40 hits
📄 NAudio.Core\Wave\WaveStreams\WaveFileReader.cs (line 143)
140 return dataChunkLength / BlockAlign;
141 }
142 // n.b. if there is a fact chunk, you can use that to get the number of samples
143 throw new InvalidOperationException("Sample count is calculated only for the standard encodings");
144 }
145 }
146
💬 An exception is thrown from the getter of property SampleCount (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 NAudio.Core\Wave\WaveStreams\AiffFileReader.cs (line 182)
179 }
180 else
181 {
182 throw new FormatException("Sample count is calculated only for the standard encodings");
183 }
184 }
185 }
💬 An exception is thrown from the getter of property SampleCount (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS027 Exception thrown from Dispose 4 hits
📄 NAudio.WinMM\Compression\AcmStream.cs (line 245)
242 streamHandle = IntPtr.Zero;
243 if (result != MmResult.NoError)
244 {
245 throw new MmException(result, "acmStreamClose");
246 }
247
248 }
💬 An exception is thrown from the Dispose(bool) method in type AcmStream (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 NAudio.WinMM\Compression\AcmStream.cs (line 245)
242 streamHandle = IntPtr.Zero;
243 if (result != MmResult.NoError)
244 {
245 throw new MmException(result, "acmStreamClose");
246 }
247
248 }
💬 An exception is thrown from the Dispose(bool) method in type AcmStream (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS049 Comparing strings without StringComparison 4 hits
📄 NAudio.Core\Wave\WaveStreams\CueList.cs (line 263)
260
261 foreach (RiffChunk chunk in reader.ExtraChunks)
262 {
263 if (chunk.IdentifierAsString.ToLower() == "cue ")
264 {
265 cueChunkData = reader.GetChunkData(chunk);
266 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 NAudio.Core\Wave\WaveStreams\CueList.cs (line 267)
264 {
265 cueChunkData = reader.GetChunkData(chunk);
266 }
267 else if (chunk.IdentifierAsString.ToLower() == "list")
268 {
269 listChunkData = reader.GetChunkData(chunk);
270 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS050 Parameter assigned in constructor 2 hits
📄 NAudio.Core\Wave\WaveOutputs\DirectSoundOut.cs (line 115)
112 {
113 if (device == Guid.Empty)
114 {
115 device = DSDEVID_DefaultPlayback;
116 }
117 this.device = device;
118 this.desiredLatency = latency;
💬 Suspicious assignment of parameter device in constructor of DirectSoundOut (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
📄 NAudio.Core\Wave\WaveOutputs\DirectSoundOut.cs (line 115)
112 {
113 if (device == Guid.Empty)
114 {
115 device = DSDEVID_DefaultPlayback;
116 }
117 this.device = device;
118 this.desiredLatency = latency;
💬 Suspicious assignment of parameter device in constructor of DirectSoundOut (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
SS051 Locking on mutable reference 12 hits
📄 NAudio.Core\Wave\WaveOutputs\DirectSoundOut.cs (line 148)
145 notifyThread.Start();
146 }
147
148 lock (m_LockObject)
149 {
150 playbackState = PlaybackState.Playing;
151 }
💬 A lock was obtained on m_LockObject but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 NAudio.Core\Wave\WaveOutputs\DirectSoundOut.cs (line 181)
178 /// </summary>
179 public void Pause()
180 {
181 lock (m_LockObject)
182 {
183 playbackState = PlaybackState.Paused;
184 }
💬 A lock was obtained on m_LockObject but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 4 hits
📄 NAudio.Midi\Midi\MidiEventCollection.cs (line 209)
206 {
207 if (!MidiEvent.IsEndTrack(midiEvent))
208 {
209 trackEvents[0].Add(midiEvent);
210 eventsAdded = true;
211 }
212 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 NAudio.Midi\Midi\MidiFile.cs (line 204)
201 if ((noteOnEvent.Channel == offEvent.Channel) && (noteOnEvent.NoteNumber == offEvent.NoteNumber))
202 {
203 noteOnEvent.OffEvent = offEvent;
204 outstandingNoteOns.Remove(noteOnEvent);
205 found = true;
206 break;
207 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS066 Disposable field is not disposed 68 hits
📄 NAudio.Core\Wave\WaveOutputs\DirectSoundOut.cs (line 34)
31 private IDirectSound directSound = null;
32 private IDirectSoundBuffer primarySoundBuffer = null;
33 private IDirectSoundBuffer secondaryBuffer = null;
34 private EventWaitHandle frameEventWaitHandle1;
35 private EventWaitHandle frameEventWaitHandle2;
36 private EventWaitHandle endEventWaitHandle;
37 private Thread notifyThread;
💬 Disposable field frameEventWaitHandle1 in type DirectSoundOut is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 NAudio.Core\Wave\WaveOutputs\DirectSoundOut.cs (line 35)
32 private IDirectSoundBuffer primarySoundBuffer = null;
33 private IDirectSoundBuffer secondaryBuffer = null;
34 private EventWaitHandle frameEventWaitHandle1;
35 private EventWaitHandle frameEventWaitHandle2;
36 private EventWaitHandle endEventWaitHandle;
37 private Thread notifyThread;
38 private SynchronizationContext syncContext;
💬 Disposable field frameEventWaitHandle2 in type DirectSoundOut is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

cairoshell

724 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 72 hits
📄 Cairo Desktop\CairoDesktop.Common\Logging\Other\ManagedShellFileLoggerOptions.cs (line 13)
10 DateFormat = "MM-dd-yyyy";
11 FileExtension = "log";
12
13 var date = DateTime.Now.ToString(DateFormat);
14
15 LogFileName = $"{date}.{FileExtension}";
16 BackupLogFileName = $"{date}-Backup.{FileExtension}";
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Cairo Desktop\CairoDesktop.Common\Logging\Other\ManagedShellLogger.cs (line 44)
41 }
42
43 string message = GetCategoryPrefix(_category) + formatter(state, exception);
44 ShellLogger.OnLog(new LogEventArgs(logLevel.ToManagedShellLogSeverity(), message, exception, DateTime.Now));
45 }
46
47 private string GetCategoryPrefix(string category)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 48 hits
📄 Cairo Desktop\CairoDesktop.Taskbar\DwmThumbnail.xaml.cs (line 126)
123 if (size.x <= Rect.Width && size.y <= Rect.Height)
124 {
125 // do not scale
126 props.rcDestination.Top += (Rect.Height - size.y) / 2;
127 props.rcDestination.Left += (Rect.Width - size.x) / 2;
128 props.rcDestination.Right = props.rcDestination.Left + size.x;
129 props.rcDestination.Bottom = props.rcDestination.Top + size.y;
💬 The operands in the divisive expression (Rect.Height - size.y) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Cairo Desktop\CairoDesktop.Taskbar\DwmThumbnail.xaml.cs (line 127)
124 {
125 // do not scale
126 props.rcDestination.Top += (Rect.Height - size.y) / 2;
127 props.rcDestination.Left += (Rect.Width - size.x) / 2;
128 props.rcDestination.Right = props.rcDestination.Left + size.x;
129 props.rcDestination.Bottom = props.rcDestination.Top + size.y;
130 }
💬 The operands in the divisive expression (Rect.Width - size.x) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 8 hits
📄 Cairo Desktop\CairoDesktop.MenuBar\MenuBar.xaml.cs (line 94)
91 if (menuExtra != null)
92 {
93 MenuExtrasHost.Children.Add(menuExtra);
94 _loadedMenuExtras.Add(userControlMenuBarExtension, menuExtra);
95 }
96 }
97 catch (Exception ex)
💬 Type UserControlMenuBarExtension is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Cairo Desktop\CairoDesktop.MenuBar\MenuBar.xaml.cs (line 94)
91 if (menuExtra != null)
92 {
93 MenuExtrasHost.Children.Add(menuExtra);
94 _loadedMenuExtras.Add(userControlMenuBarExtension, menuExtra);
95 }
96 }
97 catch (Exception ex)
💬 Type UserControlMenuBarExtension is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 16 hits
📄 Cairo Desktop\CairoDesktop.AppGrabber\ApplicationInfo.cs (line 340)
337 public override int GetHashCode()
338 {
339 int hashCode = 0;
340 if (Name != null)
341 hashCode ^= Name.GetHashCode();
342 if (Path != null)
343 hashCode ^= Path.GetHashCode();
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Cairo Desktop\CairoDesktop.AppGrabber\ApplicationInfo.cs (line 341)
338 {
339 int hashCode = 0;
340 if (Name != null)
341 hashCode ^= Name.GetHashCode();
342 if (Path != null)
343 hashCode ^= Path.GetHashCode();
344 return hashCode;
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS011 OnPropertyChanged without nameof operator 112 hits
📄 Cairo Desktop\CairoDesktop.Common\NavigationManager.cs (line 27)
24 _currentIndex = value;
25
26 OnPropertyChanged("CurrentPath");
27 OnPropertyChanged("CanGoBack");
28 OnPropertyChanged("CanGoForward");
29 OnPropertyChanged("CurrentPathFriendly");
30 OnPropertyChanged("HomePathFriendly");
💬 OnPropertyChanged(CanGoBack) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
📄 Cairo Desktop\CairoDesktop.Common\NavigationManager.cs (line 28)
25
26 OnPropertyChanged("CurrentPath");
27 OnPropertyChanged("CanGoBack");
28 OnPropertyChanged("CanGoForward");
29 OnPropertyChanged("CurrentPathFriendly");
30 OnPropertyChanged("HomePathFriendly");
31 }
💬 OnPropertyChanged(CanGoForward) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 20 hits
📄 Cairo Desktop\CairoDesktop.Application\Structs\CairoCommandParameter.cs (line 3)
1namespace CairoDesktop.Application.Structs
2{
3 public struct CairoCommandParameter
4 {
5 public string Name;
6 public string Description;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CairoCommandParameter. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Cairo Desktop\CairoDesktop.Application\Structs\MenuBarDimensions.cs (line 3)
1namespace CairoDesktop.Application.Structs
2{
3 public struct MenuBarDimensions
4 {
5 /// <summary>
6 /// ABE_LEFT = 0,
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MenuBarDimensions. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 256 hits
📄 Cairo Desktop\CairoDesktop.Common\CommandLineParser.cs (line 67)
64 {
65 // Look for new parameters (-,/ or --) and a possible enclosed value (=,:)
66 paramElements = regexSplitter.Split(arg, 3);
67 switch (paramElements.Length)
68 {
69 // Found a value (for the last parameter found (space separator))
70 case 1:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Cairo Desktop\CairoDesktop.Common\Icon.xaml.cs (line 58)
55 {
56 if (e != null && !string.IsNullOrWhiteSpace(e.PropertyName))
57 {
58 switch (e.PropertyName)
59 {
60 case "DesktopLabelPosition":
61 case "DesktopIconSize":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 8 hits
📄 Cairo Desktop\CairoDesktop.DynamicDesktop\SupportingClasses\BingWallpaperClient.cs (line 119)
116 {
117 if (!_loadcalled)
118 {
119 throw new InvalidOperationException("Call the DownLoad() method first");
120 }
121
122 return new BitmapImage(new Uri(_tempfilename));
💬 An exception is thrown from the getter of property WPFPhotoOfTheDay (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Cairo Desktop\CairoDesktop.DynamicDesktop\SupportingClasses\BingWallpaperClient.cs (line 134)
131 {
132 if (!_loadcalled)
133 {
134 throw new InvalidOperationException("Call the DownLoad() method first");
135 }
136
137 return new Bitmap(_tempfilename);
💬 An exception is thrown from the getter of property WFPhotoOfTheDay (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS048 Locking on discouraged object (string, Type, this) 24 hits
📄 Cairo Desktop\CairoDesktop.Common\Helpers\RegistryChangeMonitor.cs (line 66)
63
64 public void Start()
65 {
66 lock (this)
67 {
68 if (_monitorThread == null)
69 {
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 Cairo Desktop\CairoDesktop.Common\Helpers\RegistryChangeMonitor.cs (line 83)
80
81 public void Stop()
82 {
83 lock (this)
84 {
85 Changed = null;
86 Error = null;
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 12 hits
📄 Cairo Desktop\CairoDesktop.AppGrabber\QuickLaunchManager.cs (line 50)
47 // it would be nice to cache this, but need to handle case of user adding/removing app via various means after first access
48 foreach (ApplicationInfo ai in _appGrabber.QuickLaunch)
49 {
50 if (ai.Target.ToLower() == window.WinFileName.ToLower() || (window.IsUWP && ai.Target == window.AppUserModelID))
51 {
52 return ai;
53 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Cairo Desktop\CairoDesktop.AppGrabber\ApplicationInfo.cs (line 287)
284 ai.Path = "appx:" + storeApp.AppUserModelId;
285 ai.Target = storeApp.AppUserModelId;
286 ai.IconColor = storeApp.IconColor;
287 ai.AllowRunAsAdmin = storeApp.EntryPoint?.ToLower() == "windows.fulltrustapplication" || storeApp.HostId?.ToLower() == "pwa";
288
289 return ai;
290 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 4 hits
📄 Cairo Desktop\CairoDesktop.AppGrabber\AppGrabberUI.xaml.cs (line 99)
96 string filter = "Programs and shortcuts|";
97 foreach (string ext in AppGrabberService.ExecutableExtensions)
98 {
99 filter += $"*{ext};";
100 }
101
102 filter = filter.Substring(0, filter.Length - 2);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Cairo Desktop\CairoDesktop.AppGrabber\AppGrabberUI.xaml.cs (line 99)
96 string filter = "Programs and shortcuts|";
97 foreach (string ext in AppGrabberService.ExecutableExtensions)
98 {
99 filter += $"*{ext};";
100 }
101
102 filter = filter.Substring(0, filter.Length - 2);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 144 hits
📄 Cairo Desktop\CairoDesktop.Common\Logging\Other\ManagedShellLoggerProvider.cs (line 17)
14 private readonly IOptionsMonitor<ManagedShellFileLoggerOptions> _options;
15 private readonly Settings cairoSettings;
16 private readonly ConcurrentDictionary<string, Lazy<ManagedShellLogger>> _loggers;
17 private readonly IDisposable _settingsChangeToken;
18 private ManagedShellFileLoggerOptions _settings;
19 private string _filename;
20 private FileLog _fileLog = null;
💬 Disposable field _settingsChangeToken in type ManagedShellLoggerProvider is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Cairo Desktop\CairoDesktop.Common\Logging\Other\ManagedShellLoggerProvider.cs (line 20)
17 private readonly IDisposable _settingsChangeToken;
18 private ManagedShellFileLoggerOptions _settings;
19 private string _filename;
20 private FileLog _fileLog = null;
21
22 public ManagedShellLoggerProvider(ManagedShellFileLoggerOptions settings, Settings cairoSettings)
23 {
💬 Disposable field _fileLog in type ManagedShellLoggerProvider is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Blog.Core

708 total diagnostics across 17 rules

SS001 Async method with void return type 50 hits
📄 Blog.Core.Tests\Repository_Test\MongoRepository_Base_Should.cs (line 38)
35
36
37 [Fact]
38 public async void Add_Test()
39 {
40 await baseRepository.AddAsync(new MongoTest { isDel = false, name = "test", time = DateTime.UtcNow });
41 }
💬 Method Add_Test is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Blog.Core.Tests\Service_Test\BlogArticleService_Should.cs (line 36)
33
34
35 [Fact]
36 public async void Get_Blogs_Test()
37 {
38 var data = await blogArticleServices.GetBlogs();
39
💬 Method Get_Blogs_Test is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 316 hits
📄 Blog.Core.Model\Models\AccessTrendLog.cs (line 25)
22 /// <summary>
23 /// 更新时间
24 /// </summary>
25 public DateTime UpdateTime { get; set; } = DateTime.Now;
26 }
27}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Blog.Core.Model\IDS4DbModels\ApplicationRole.cs (line 35)
32 /// <summary>
33 /// 创建时间
34 /// </summary>
35 public DateTime? CreateTime { get; set; } = DateTime.Now;
36 /// <summary>
37 /// 修改ID
38 /// </summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 48 hits
📄 Blog.Core.Common\Helper\Base32Helper.cs (line 67)
64 /// </exception>
65 public static byte[] FromBase32String(string str)
66 {
67 int numBytes = str.Length * 5 / 8;
68 byte[] bytes = new Byte[numBytes];
69
70 // all UPPERCASE chars
💬 The operands in the divisive expression str.Length * 5 / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Blog.Core.Common\Helper\Console\Table\TableExtension.cs (line 72)
69 if (string.IsNullOrWhiteSpace(titleStr)) return "";
70 //一行的宽度
71 int rowWide = columnWides.Sum() + columnWides.Count * 2 * columnBlankNum + columnWides.Count + 1;
72 int blankNum = (rowWide - titleStr.FullHalfLength()) / 2 - 1;
73 string tilte = $"{delimiterStr}{"".PadLeft(blankNum, ' ')}{titleStr}{"".PadLeft(blankNum, ' ')}{delimiterStr}";
74 if (tilte.FullHalfLength() != rowWide) tilte = tilte.Replace($" {delimiterStr}", $" {delimiterStr}");
75 return tilte;
💬 The operands in the divisive expression (rowWide - titleStr.FullHalfLength()) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS018 Switch does not handle all enum options 10 hits
📄 Blog.Core.Model\ApiResponse.cs (line 11)
8
9 public ApiResponse(StatusCode apiCode, string msg = null)
10 {
11 switch (apiCode)
12 {
13 case StatusCode.CODE401:
14 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Blog.Core.Common\DB\TenantUtil.cs (line 23)
20 {
21 //此处默认配置 Sqlite 地址
22 //实际业务中 也会有运维、系统管理员等来维护
23 switch (tenant.DbType.Value)
24 {
25 case DbType.Sqlite:
26 tenant.Connection = $"DataSource={Path.Combine(Environment.CurrentDirectory, tenant.ConfigId)}.db";
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 18 hits
📄 Blog.Core.Model\ApiResponse.cs (line 11)
8
9 public ApiResponse(StatusCode apiCode, string msg = null)
10 {
11 switch (apiCode)
12 {
13 case StatusCode.CODE401:
14 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Blog.Core.Common\DB\TenantUtil.cs (line 23)
20 {
21 //此处默认配置 Sqlite 地址
22 //实际业务中 也会有运维、系统管理员等来维护
23 switch (tenant.DbType.Value)
24 {
25 case DbType.Sqlite:
26 tenant.Connection = $"DataSource={Path.Combine(Environment.CurrentDirectory, tenant.ConfigId)}.db";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS032 Thread.Sleep used in async method 4 hits
📄 Blog.Core.Services\PayServices.cs (line 150)
147 case "Q":
148 int waittime = payResult.WAITTIME.ObjToInt();
149 if (waittime <= 0) waittime = 5;//如果需要等待默认等待5秒后再次查询
150 Thread.Sleep(waittime * 1000);
151 //轮询查询
152 messageModel = await PayCheck(payModel, 1);
153 break;
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 Blog.Core.Services\PayServices.cs (line 377)
374 case "Q":
375 int waittime = payResult.WAITTIME.ObjToInt();
376 if (waittime <= 0) waittime = 5;//如果需要等待默认等待5秒后再次查询
377 Thread.Sleep(waittime * 1000);
378 //改成轮询查询
379 messageModel = await PayCheck(payModel, ++times);
380 break;
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 58 hits
📄 Blog.Core.Serilog.Es\Sinks\TCP\TCPSocketWriter.cs (line 199)
196 {
197 if (_stream != null)
198 {
199 _stream.Dispose();
200 }
201
202 _disposed.SetResult(true);
💬 Async overload available for Stream.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Blog.Core.Common\Seed\DBSeed.cs (line 137)
134
135 if (!await myContext.Db.Queryable<BlogArticle>().AnyAsync())
136 {
137 myContext.GetEntityDB<BlogArticle>().InsertRange(
138 JsonHelper.ParseFormByJson<List<BlogArticle>>(
139 FileHelper.ReadFile(string.Format(SeedDataFolder, "BlogArticle"), Encoding.UTF8)));
140 Console.WriteLine("Table:BlogArticle created success!");
💬 Async overload available for SimpleClient.InsertRange (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 58 hits
📄 Blog.Core.Serilog.Es\NetworkLoggerConfigurationExtensions.cs (line 72)
69 {
70 try
71 {
72 var ipHostEntry = Dns.GetHostEntryAsync(uri).Result;
73 if (!ipHostEntry.AddressList.Any())
74 return null;
75 return ipHostEntry.AddressList.First();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Blog.Core.Common\Helper\HttpHelper.cs (line 22)
19 string result = string.Empty;
20 Uri getUrl = new Uri(serviceAddress);
21 Httpclient.Timeout = new TimeSpan(0, 0, 60);
22 result = await Httpclient.GetAsync(serviceAddress).Result.Content.ReadAsStringAsync();
23 return result;
24 }
25 catch (Exception e)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS037 HttpClient instantiated directly 8 hits
📄 Blog.Core.Common\Helper\HttpHelper.cs (line 13)
10 /// </summary>
11 public class HttpHelper
12 {
13 public static readonly HttpClient Httpclient = new HttpClient();
14
15 public static async Task<string> GetAsync(string serviceAddress)
16 {
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 Blog.Core.Common\Helper\WeChatHelper.cs (line 56)
53 public async static Task<WeChatApiDto> UploadMedia(string token, string type, string fileName, Stream inputStream)
54 {
55 var url = $"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={token}&type={type}";
56 using var client = new HttpClient();
57 using HttpContent content = new StreamContent(inputStream);
58 var httpResponse = await client.PostAsync(url, content);
59 var txt = await httpResponse.Content.ReadAsStringAsync();
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS040 Unused result on immutable object 4 hits
📄 Blog.Core.Common\Helper\SM\SM4Helper.cs (line 67)
64 for (int i = matchCol.Count - 1; i >= 0; i--)
65 {
66 Match item = matchCol[i];
67 cipherText.Remove(item.Index, item.Length);
68 }
69 }
70 return cipherText;
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
📄 Blog.Core.Extensions\ServiceExtensions\SqlsugarSetup.cs (line 138)
135 {
136 foreach (var param in paramArr)
137 {
138 sql.Replace(param.ParameterName, param.Value.ObjToString());
139 }
140
141 return sql;
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
SS041 Unnecessary enumerable materialization 6 hits
📄 Blog.Core.Gateway\Controllers\UserController.cs (line 27)
24 return new MessageModel<List<ClaimDto>>()
25 {
26 success = true,
27 response = (_user.GetClaimsIdentity().ToList()).Select(d =>
28 new ClaimDto
29 {
30 Type = d.Type,
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 Blog.Core.Api\Controllers\ValuesController.cs (line 125)
122 return new MessageModel<List<ClaimDto>>()
123 {
124 success = true,
125 response = (_user.GetClaimsIdentity().ToList()).Select(d =>
126 new ClaimDto
127 {
128 Type = d.Type,
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS048 Locking on discouraged object (string, Type, this) 16 hits
📄 Blog.Core.Serilog.Es\Sinks\TCP\TCPSocketWriter.cs (line 287)
284
285 public void Enqueue(T obj)
286 {
287 lock (this)
288 {
289 if (IsCompleted)
290 {
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 Blog.Core.Serilog.Es\Sinks\TCP\TCPSocketWriter.cs (line 306)
303
304 public void CompleteAdding()
305 {
306 lock (this)
307 {
308 IsCompleted = true;
309 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 30 hits
📄 Blog.Core.Serilog.Es\NetworkLoggerConfigurationExtensions.cs (line 97)
94 }
95 if (uri.Port == 0)
96 throw new UriFormatException("Uri port cannot be 0");
97 if (!(uri.Scheme.ToLower() == "tcp" || uri.Scheme.ToLower() == "tls"))
98 throw new UriFormatException("Uri scheme must be tcp or tls");
99 return uri;
100 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Blog.Core.Serilog.Es\NetworkLoggerConfigurationExtensions.cs (line 97)
94 }
95 if (uri.Port == 0)
96 throw new UriFormatException("Uri port cannot be 0");
97 if (!(uri.Scheme.ToLower() == "tcp" || uri.Scheme.ToLower() == "tls"))
98 throw new UriFormatException("Uri scheme must be tcp or tls");
99 return uri;
100 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 8 hits
📄 Blog.Core.Serilog.Es\Formatters\JsonConfigUtils.cs (line 34)
31 /// <returns></returns>
32 public static T GetAppSettings<T>(string AppSettingsFileName, string key) where T : class, new()
33 {
34 lock (__Lock__)
35 {
36 if (Configuration == null)
37 {
💬 A lock was obtained on __Lock__ but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Ocelot.Provider.Nacos\NacosClient\LoadBalance\WeightRoundRobinLBStrategy.cs (line 47)
44
45 var instanceId = string.Empty;
46
47 lock (obj)
48 {
49 if (_pos >= tagInstanceIdList.Count)
50 _pos = 0;
💬 A lock was obtained on obj but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 34 hits
📄 Blog.Core.Common\Helper\CCBPayUtil.cs (line 271)
268 string text = "";
269 for (int i = 0; i < array.Length; i++)
270 {
271 text += array[i].ToString("x2");
272 }
273 return text;
274 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Blog.Core.Common\DB\Aop\SqlsugarAop.cs (line 157)
154 string key = "【SQL参数】:";
155 foreach (var param in pars)
156 {
157 key += $"{param.ParameterName}:{param.Value}\n";
158 }
159
160 return key;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 Blog.Core.EventBus\EventBusKafka\KafkaConsumerHostService.cs (line 123)
120
121 if (_subsManager.HasSubscriptionsForEvent(eventName))
122 {
123 using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME))
124 {
125 var subscriptions = _subsManager.GetHandlersForEvent(eventName);
126 foreach (var subscription in subscriptions)
💬 ILifetimeScope can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Blog.Core.EventBus\RabbitMQPersistent\EventBusRabbitMQ.cs (line 320)
317
318 if (_subsManager.HasSubscriptionsForEvent(eventName))
319 {
320 using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME))
321 {
322 var subscriptions = _subsManager.GetHandlersForEvent(eventName);
323 foreach (var subscription in subscriptions)
💬 ILifetimeScope can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 32 hits
📄 Blog.Core.Serilog.Es\Sinks\TCP\TCPSocketWriter.cs (line 53)
50 {
51 private readonly FixedSizeQueue<string> _eventQueue;
52 private readonly ExponentialBackoffTcpReconnectionPolicy _reconnectPolicy = new ExponentialBackoffTcpReconnectionPolicy();
53 private readonly CancellationTokenSource _tokenSource; // Must be private or Dispose will not function properly.
54 private readonly TaskCompletionSource<bool> _disposed = new TaskCompletionSource<bool>();
55
56 private Stream _stream;
💬 Disposable field _tokenSource in type TcpSocketWriter is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Blog.Core.Serilog.Es\Sinks\TCP\TCPSocketWriter.cs (line 56)
53 private readonly CancellationTokenSource _tokenSource; // Must be private or Dispose will not function properly.
54 private readonly TaskCompletionSource<bool> _disposed = new TaskCompletionSource<bool>();
55
56 private Stream _stream;
57
58 /// <summary>
59 /// Event that is invoked when reconnecting after a TCP session is dropped fails.
💬 Disposable field _stream in type TcpSocketWriter is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

CsvHelper

674 total diagnostics across 9 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 76 hits
No source samples extracted
SS003 Integer divided by integer causing implicit rounding 42 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 42 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 42 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 310 hits
No source samples extracted
SS019 Switch is missing default label 24 hits
No source samples extracted
SS033 Async overload is available 48 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 62 hits
No source samples extracted
SS066 Disposable field is not disposed 28 hits
No source samples extracted

btcpayserver

662 total diagnostics across 17 rules

SS001 Async method with void return type 4 hits
📄 BTCPayServer.Tests\WalletTests.cs (line 353)
350 await s.GoToWalletSend();
351
352 // ReSharper disable once AsyncVoidMethod
353 async void PasteBIP21(object sender, IDialog e)
354 {
355 await e.AcceptAsync(bip21);
356 }
💬 Method PasteBIP21 is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 BTCPayServer.Tests\PlaywrightTester.cs (line 926)
923 {
924 // Handle the alert dialog in Playwright
925 // ReSharper disable once AsyncVoidMethod
926 async void Callback(object? sender, IDialog e)
927 => await e.AcceptAsync(text);
928 Page.Dialog += Callback;
929 try
💬 Method Callback is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 BTCPayServer.Client\JsonConverters\WordlistJsonConverter.cs (line 50)
47 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
48 {
49 if (value is Wordlist wl)
50 writer.WriteValue(_WordlistsReverse[wl]);
51 }
52
53 readonly static Dictionary<string, Wordlist> _Wordlists;
💬 Type Wordlist is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 BTCPayServer.Tests\PayJoinTests.cs (line 116)
113 var inputs = new[] { 1m };
114 var result = await controller.SelectUTXO(network, utxos, inputs, paymentAmount, otherOutputs);
115 Assert.Equal(PayJoinEndpointController.PayjoinUtxoSelectionType.HeuristicBased, result.selectionType);
116 Assert.Contains(result.selectedUTXO, utxo => utxos.Contains(utxo));
117
118 //no matter what here, no good selection, it seems that payment with 1 utxo generally makes payjoin coin selection unperformant
119 utxos = new[] { FakeUTXO(0.3m), FakeUTXO(0.7m) };
💬 Type UTXO is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 6 hits
📄 BTCPayServer.Common\SynchronizationContextRemover.cs (line 7)
4
5namespace BTCPayServer
6{
7 public struct SynchronizationContextRemover : INotifyCompletion
8 {
9 public bool IsCompleted => SynchronizationContext.Current == null;
10
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SynchronizationContextRemover. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 BTCPayServer.Common\Logging\ConsoleLogger.cs (line 310)
307 }
308 }
309
310 private struct ConsoleColors
311 {
312 public ConsoleColors(ConsoleColor? foreground, ConsoleColor? background)
313 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ConsoleColors. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 6 hits
📄 BTCPayServer.Rating\RateRules.cs (line 413)
410 public override void VisitBinaryExpression(BinaryExpressionSyntax node)
411 {
412 base.VisitBinaryExpression(node);
413 switch (node.Kind())
414 {
415 case SyntaxKind.AddExpression:
416 case SyntaxKind.MultiplyExpression:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 BTCPayServer.Rating\RateRules.cs (line 321)
318
319
320 bool invalid = false;
321 switch (node.Kind())
322 {
323 case SyntaxKind.AddExpression:
324 case SyntaxKind.MultiplyExpression:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 16 hits
📄 BTCPayServer.Client\JsonConverters\NumericStringJsonConverter.cs (line 56)
53
54 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
55 {
56 switch (value)
57 {
58 case null:
59 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 BTCPayServer.Client\BTCPayServerClient.StoreRatesConfiguration.cs (line 18)
15 }
16
17 private string GetRateConfigPath(string storeId, bool? fallback)
18 => fallback switch
19 {
20 null => $"api/v1/stores/{storeId}/rates/configuration",
21 true => $"api/v1/stores/{storeId}/rates/configuration/fallback",
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 BTCPayServer.Rating\MultiValueDictionary.cs (line 939)
936 switch (state)
937 {
938 case EnumerationState.BeforeFirst:
939 throw new InvalidOperationException(("Properties.Resources.InvalidOperation_EnumNotStarted"));
940 case EnumerationState.AfterLast:
941 throw new InvalidOperationException(("Properties.Resources.InvalidOperation_EnumEnded"));
942 default:
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 BTCPayServer.Rating\MultiValueDictionary.cs (line 941)
938 case EnumerationState.BeforeFirst:
939 throw new InvalidOperationException(("Properties.Resources.InvalidOperation_EnumNotStarted"));
940 case EnumerationState.AfterLast:
941 throw new InvalidOperationException(("Properties.Resources.InvalidOperation_EnumEnded"));
942 default:
943 return current;
944 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS032 Thread.Sleep used in async method 8 hits
📄 BTCPayServer.Tests\FastTests.cs (line 1284)
1281 await fetch.UpdateIfNecessary(default);
1282 spy.AssertNotHit();
1283 fetch.RefreshRate = TimeSpan.FromSeconds(1.0);
1284 Thread.Sleep(1020);
1285 fetchedRate = await fetcher.FetchRate(CurrencyPair.Parse("BTC_USD"), rateRules, null, default);
1286 spy.AssertNotHit();
1287 fetch.ValidatyTime = TimeSpan.FromSeconds(1.0);
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 BTCPayServer.Tests\FastTests.cs (line 1291)
1288 await fetch.UpdateIfNecessary(default);
1289 spy.AssertHit();
1290 await fetch.GetRatesAsync(default);
1291 Thread.Sleep(1000);
1292 await Assert.ThrowsAsync<InvalidOperationException>(() => fetch.GetRatesAsync(default));
1293 }
1294
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 290 hits
📄 BTCPayServer.Common\MultiProcessingQueue.cs (line 95)
92 {
93 queues = _Queues.Select(c => c.Value).ToArray();
94 }
95 cts.Cancel();
96 var delay = Task.Delay(-1, cancellationToken);
97 foreach (var q in queues)
98 {
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 BTCPayServer.PluginPacker\Program.cs (line 54)
51 {
52 File.Delete(outputFile + ".btcpay");
53 }
54 ZipFile.CreateFromDirectory(directory, outputFile + ".btcpay", CompressionLevel.Optimal, false);
55 await File.WriteAllTextAsync(outputFile + ".btcpay.json", json);
56
57 var sha256sums = new StringBuilder();
💬 Async overload available for ZipFile.CreateFromDirectory (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 166 hits
📄 BTCPayServer.Abstractions\Services\PluginHookFilter.cs (line 12)
9
10 public Task<object> Execute(object args)
11 {
12 return Execute(args is T args1 ? args1 : default).ContinueWith(task => task.Result as object);
13 }
14
15 public abstract Task<T> Execute(T arg);
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 BTCPayServer.Tests\CrowdfundTests.cs (line 53)
50 Assert.Equal(appType, vm.SelectedAppType);
51 Assert.Null(vm.AppName);
52 vm.AppName = "test";
53 var redirect = Assert.IsType<RedirectResult>(apps.CreateApp(user.StoreId, vm).Result);
54 Assert.EndsWith("/settings/crowdfund", redirect.Url);
55 var appList = Assert.IsType<ListAppsViewModel>(Assert.IsType<ViewResult>(apps.ListApps(user.StoreId).Result).Model);
56 var app = appList.Apps[0];
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 10 hits
📄 BTCPayServer.Tests\BitpayTests.cs (line 247)
244
245 var k = new Key();
246 var bitpay = new Bitpay(k, tester.PayTester.ServerUri);
247 bitpay.AuthorizeClient(new PairingCode(storeController.GeneratedPairingCode)).Wait();
248 Assert.True(await bitpay.TestAccessAsync(Facade.Merchant));
249 Assert.True(await bitpay.TestAccessAsync(Facade.PointOfSale));
250 // Same with a new instance
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 BTCPayServer.Tests\FastTests.cs (line 1714)
1711 Assert.True(new[] { true, true, true, false }.SequenceEqual(jobs));
1712 Assert.Equal(1, client.GetExecutingCount());
1713
1714 Assert.False(waitJobsFinish.Wait(1));
1715 Assert.False(waitJobsFinish.IsCompletedSuccessfully);
1716
1717 await mockDelay.Advance(TimeSpan.FromSeconds(1.0));
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS037 HttpClient instantiated directly 78 hits
📄 BTCPayServer.Rating\Providers\HitBTCRateProvider.cs (line 13)
10 public class HitBTCRateProvider(HttpClient httpClient) : IRateProvider
11 {
12 public RateSourceInfo RateSourceInfo => new("hitbtc", "HitBTC", "https://api.hitbtc.com/api/2/public/ticker");
13 private readonly HttpClient _httpClient = httpClient ?? new HttpClient();
14
15 public async Task<PairRate[]> GetRatesAsync(CancellationToken cancellationToken)
16 {
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 BTCPayServer.Rating\Providers\KrakenExchangeRateProvider.cs (line 33)
30 }
31
32 HttpClient _LocalClient;
33 static readonly HttpClient _Client = new HttpClient();
34 string[] _Symbols = Array.Empty<string>();
35 DateTimeOffset? _LastSymbolUpdate = null;
36 readonly Dictionary<string, string> _TickerMapping = new Dictionary<string, string>()
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS041 Unnecessary enumerable materialization 4 hits
📄 BTCPayServer.Tests\CSVTester.cs (line 16)
13 var lines = text.Split("\r\n").ToList();
14 var headers = lines[0].Split(',');
15 _indexes = headers.Select((h,i) => (h,i)).ToDictionary(h => h.h, h => h.i);
16 _lines = lines.Skip(1).ToList().Select(l => l.Split(',')).ToList();
17 }
18}
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 BTCPayServer.Tests\FastTests.cs (line 2441)
2438 {
2439 var result = new JObject();
2440
2441 foreach (var property in original.Properties().ToList().OrderBy(p => p.Name))
2442 {
2443 var value = property.Value as JObject;
2444
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 2 hits
📄 BTCPayServer.Tests\OutputPathAttribute.cs (line 5)
2
3namespace BTCPayServer.Tests
4{
5 public class OutputPathAttribute : Attribute
6 {
7 public OutputPathAttribute(string builtPath)
8 {
💬 OutputPathAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 BTCPayServer.Tests\OutputPathAttribute.cs (line 5)
2
3namespace BTCPayServer.Tests
4{
5 public class OutputPathAttribute : Attribute
6 {
7 public OutputPathAttribute(string builtPath)
8 {
💬 OutputPathAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS051 Locking on mutable reference 10 hits
📄 BTCPayServer.Common\MultiProcessingQueue.cs (line 40)
37 {
38 get
39 {
40 lock (_Queues)
41 {
42 Cleanup();
43 return _Queues.Count;
💬 A lock was obtained on _Queues but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 BTCPayServer.Common\MultiProcessingQueue.cs (line 51)
48 bool stopped;
49 public void Enqueue(string queueName, ProcessingAction act)
50 {
51 lock (_Queues)
52 {
53retry:
54 if (stopped)
💬 A lock was obtained on _Queues but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 2 hits
📄 BTCPayServer.Client\BTCPayServerClient.cs (line 180)
177 {
178 foreach (var item in (IEnumerable)keyValuePair.Value)
179 {
180 uriBuilder.Query = uriBuilder.Query + Uri.EscapeDataString(keyValuePair.Key) + "=" +
181 Uri.EscapeDataString(item.ToString()) + "&";
182 }
183 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 BTCPayServer.Client\BTCPayServerClient.cs (line 180)
177 {
178 foreach (var item in (IEnumerable)keyValuePair.Value)
179 {
180 uriBuilder.Query = uriBuilder.Query + Uri.EscapeDataString(keyValuePair.Key) + "=" +
181 Uri.EscapeDataString(item.ToString()) + "&";
182 }
183 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 34 hits
📄 BTCPayServer.Tests\DatabaseTester.cs (line 57)
54
55 public async Task MigrateAsync()
56 {
57 using var ctx = CreateContext();
58 await EnsureCreatedAsync();
59 await ctx.Database.MigrateAsync();
60 }
💬 ApplicationDbContext can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 BTCPayServer.Tests\DatabaseTester.cs (line 72)
69
70 public async Task MigrateUntil(string migration = null)
71 {
72 using var ctx = CreateContext();
73 var db = ctx.Database.GetDbConnection();
74 await EnsureCreatedAsync();
75 var migrations = ctx.Database.GetMigrations().ToArray();
💬 ApplicationDbContext can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 18 hits
📄 BTCPayServer.Common\Logging\ConsoleLogger.cs (line 347)
344 {
345 private const int _maxQueuedMessages = 1024;
346
347 private readonly BlockingCollection<LogMessageEntry> _messageQueue = new BlockingCollection<LogMessageEntry>(_maxQueuedMessages);
348 private readonly Task _outputTask;
349
350 public IConsole Console;
💬 Disposable field _messageQueue in type ConsoleLoggerProcessor is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 BTCPayServer.Common\Logging\ConsoleLogger.cs (line 348)
345 private const int _maxQueuedMessages = 1024;
346
347 private readonly BlockingCollection<LogMessageEntry> _messageQueue = new BlockingCollection<LogMessageEntry>(_maxQueuedMessages);
348 private readonly Task _outputTask;
349
350 public IConsole Console;
351
💬 Disposable field _outputTask in type ConsoleLoggerProcessor is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

LiteDB

646 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 78 hits
📄 LiteDB\Client\Storage\LiteFileInfo.cs (line 29)
26 public int Chunks { get; internal set; } = 0;
27
28 [BsonField("uploadDate")]
29 public DateTime UploadDate { get; internal set; } = DateTime.Now;
30
31 [BsonField("metadata")]
32 public BsonDocument Metadata { get; set; } = new BsonDocument();
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 LiteDB\Engine\FileReader\FileReaderError.cs (line 13)
10 /// </summary>
11 internal class FileReaderError
12 {
13 public DateTime Created { get; } = DateTime.Now;
14 public FileOrigin Origin { get; set; }
15 public long Position { get; set; }
16 public uint? PageID { get; set; }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 44 hits
📄 LiteDB\Document\ObjectId.cs (line 135)
132
133 for (var i = 0; i < 24; i += 2)
134 {
135 bytes[i / 2] = Convert.ToByte(value.Substring(i, 2), 16);
136 }
137
138 return bytes;
💬 The operands in the divisive expression i / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 LiteDB\Engine\Disk\DiskService.cs (line 125)
122 /// The result is used to prevent infinite loops in case of problems with pointers
123 /// Each page support max of 255 items. Use 10 pages offset (avoid empty disk)
124 /// </summary>
125 public uint MAX_ITEMS_COUNT => (uint)(((_dataLength + _logLength) / PAGE_SIZE) + 10) * byte.MaxValue;
126
127 /// <summary>
128 /// When a page are requested as Writable but not saved in disk, must be discard before release
💬 The operands in the divisive expression (_dataLength + _logLength) / PAGE_SIZE are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 LiteDB.Tests\Mapper\LinqBsonExpression_Tests.cs (line 218)
215
216 // contains
217 TestExpr<User>(x => x.PhoneNumbers.Contains(1234), "PhoneNumbers ANY = @p0", 1234);
218 TestExpr<User>(x => x.Phones2.Contains(new Phone { Number = 1 }), "Phones2 ANY = { Number: @p0 }", 1);
219
220 // negated contains
221 TestExpr<User>(x => !x.PhoneNumbers.Contains(1234), "(PhoneNumbers ANY = @p0) = false", 1234);
💬 Type Phone is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 LiteDB.Tests\Mapper\LinqBsonExpression_Tests.cs (line 222)
219
220 // negated contains
221 TestExpr<User>(x => !x.PhoneNumbers.Contains(1234), "(PhoneNumbers ANY = @p0) = false", 1234);
222 TestExpr<User>(x => !x.Phones2.Contains(new Phone { Number = 1 }), "(Phones2 ANY = { Number: @p0 }) = false", 1);
223
224 // fixed position with filter expression
225 TestExpr<User>(x => x.Phones.First(p => p.Number == 1), "FIRST(FILTER($.Phones=>(@.Number=@p0)))", 1);
💬 Type Phone is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 LiteDB\Engine\Structures\PagePosition.cs (line 41)
38 unchecked
39 {
40 int hash = 17;
41 hash = hash * 23 + (int)this.PageID;
42 hash = hash * 23 + (int)this.Position;
43 return hash;
44 }
💬 GetHashCode() refers to mutable field PageID (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 LiteDB\Engine\Structures\PagePosition.cs (line 42)
39 {
40 int hash = 17;
41 hash = hash * 23 + (int)this.PageID;
42 hash = hash * 23 + (int)this.Position;
43 return hash;
44 }
45 }
💬 GetHashCode() refers to mutable field Position (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 18 hits
📄 LiteDB\Document\DataReader\BsonDataReader.cs (line 111)
108 catch (Exception ex)
109 {
110 _state.Handle(ex);
111 throw ex;
112 }
113 }
114 else
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 LiteDB\Engine\Query\QueryExecutor.cs (line 139)
136 catch (Exception ex)
137 {
138 _state.Handle(ex);
139 throw ex;
140 }
141
142 while (read)
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 24 hits
📄 LiteDB\Utils\Extensions\LinqExtensions.cs (line 76)
73 }
74 }
75
76 internal struct LastItem<T>
77 {
78 public T Item { get; set; }
79 public bool IsLast { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct LastItem. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 LiteDB\Utils\Result.cs (line 12)
9 /// <summary>
10 /// Implement a generic result structure with value and exception. This value can be partial value (like BsonDocument/Array)
11 /// </summary>
12 internal struct Result<T>
13 where T : class
14 {
15 public T Value;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Result. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 24 hits
📄 LiteDB\Document\Json\JsonReader.cs (line 73)
70 internal BsonValue ReadValue(Token token)
71 {
72 var value = token.Value;
73 switch (token.Type)
74 {
75 case TokenType.String: return value;
76 case TokenType.OpenBrace: return this.ReadObject();
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 LiteDB\Document\Expression\Methods\Math.cs (line 18)
15 /// </summary>
16 public static BsonValue ABS(BsonValue value)
17 {
18 switch (value.Type)
19 {
20 case BsonType.Int32: return Math.Abs(value.AsInt32);
21 case BsonType.Int64: return Math.Abs(value.AsInt64);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 206 hits
📄 LiteDB\Client\Mapper\Linq\TypeResolver\ConvertResolver.cs (line 16)
13 {
14 public string ResolveMethod(MethodInfo method)
15 {
16 switch (method.Name)
17 {
18 case "ToInt32": return "INT32(@0)";
19 case "ToInt64": return "INT64(@0)";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 LiteDB\Client\Mapper\Linq\TypeResolver\DateTimeResolver.cs (line 16)
13 {
14 public string ResolveMethod(MethodInfo method)
15 {
16 switch (method.Name)
17 {
18 // instance methods
19 case "AddYears": return "DATEADD('y', @0, #)";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS044 Attribute must specify [AttributeUsage] 38 hits
📄 LiteDB\Client\Mapper\Attributes\BsonIgnoreAttribute.cs (line 9)
6 /// <summary>
7 /// Indicate that property will not be persist in Bson serialization
8 /// </summary>
9 public class BsonIgnoreAttribute : Attribute
10 {
11 }
12}
💬 BsonIgnoreAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 LiteDB\Client\Mapper\Attributes\BsonRefAttribute.cs (line 9)
6 /// <summary>
7 /// Indicate that field are not persisted inside this document but it's a reference for another document (DbRef)
8 /// </summary>
9 public class BsonRefAttribute : Attribute
10 {
11 public string Collection { get; set; }
12
💬 BsonRefAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 10 hits
📄 LiteDB\Client\Mapper\BsonMapper.GetEntityMapper.cs (line 213)
210 MemberMapper mi = null;
211 foreach (MemberMapper member in mapper.Members)
212 {
213 if (member.MemberName.ToLower() == par.Name.ToLower() && member.DataType == par.ParameterType)
214 {
215 mi = member;
216 break;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 LiteDB\Client\Mapper\BsonMapper.GetEntityMapper.cs (line 213)
210 MemberMapper mi = null;
211 foreach (MemberMapper member in mapper.Members)
212 {
213 if (member.MemberName.ToLower() == par.Name.ToLower() && member.DataType == par.ParameterType)
214 {
215 mi = member;
216 break;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 2 hits
📄 LiteDB.Shell\Shell\InputCommand.cs (line 46)
43 Console.Write("| ");
44
45 var line = this.ReadLine();
46 cmd += Environment.NewLine + line;
47 }
48 }
49
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 LiteDB.Shell\Shell\InputCommand.cs (line 46)
43 Console.Write("| ");
44
45 var line = this.ReadLine();
46 cmd += Environment.NewLine + line;
47 }
48 }
49
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 186 hits
📄 LiteDB\Engine\Sort\SortService.cs (line 23)
20 /// </summary>
21 internal class SortService : IDisposable
22 {
23 private readonly SortDisk _disk;
24
25 private readonly List<SortContainer> _containers = new List<SortContainer>();
26 private readonly int _containerSize;
💬 Disposable field _disk in type SortService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 LiteDB\Engine\Disk\Serializer\BufferWriter.cs (line 14)
11 /// </summary>
12 internal class BufferWriter : IDisposable
13 {
14 private readonly IEnumerator<BufferSlice> _source;
15
16 private BufferSlice _current;
17 private int _currentPosition = 0; // position in _current
💬 Disposable field _source in type BufferWriter is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

QRCoder

602 total diagnostics across 4 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 14 hits
📄 QRCoder\PayloadGenerator\BezahlCode.cs (line 217)
214 _currency = currency;
215
216 if (executionDate == null)
217 _executionDate = DateTime.Now;
218 else
219 {
220 if (DateTime.Today.Ticks > executionDate.Value.Ticks)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 QRCoder\PayloadGenerator\BezahlCode.cs (line 217)
214 _currency = currency;
215
216 if (executionDate == null)
217 _executionDate = DateTime.Now;
218 else
219 {
220 if (DateTime.Today.Ticks > executionDate.Value.Ticks)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 420 hits
📄 QRCoder\ASCIIQRCode.cs (line 54)
51 //to keep the QR code as square as possible.
52 var quietZonesModifier = (drawQuietZones ? 0 : 8);
53 var quietZonesOffset = (int)(quietZonesModifier * 0.5);
54 var adjustmentValueForNumberOfCharacters = darkColorString.Length / 2 != 1 ? darkColorString.Length / 2 : 0;
55 var verticalNumberOfRepeats = repeatPerModule + adjustmentValueForNumberOfCharacters;
56 var sideLength = (QrCodeData.ModuleMatrix.Count - quietZonesModifier) * verticalNumberOfRepeats;
57 var qrCode = new string[sideLength];
💬 The operands in the divisive expression darkColorString.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 QRCoder\ASCIIQRCode.cs (line 54)
51 //to keep the QR code as square as possible.
52 var quietZonesModifier = (drawQuietZones ? 0 : 8);
53 var quietZonesOffset = (int)(quietZonesModifier * 0.5);
54 var adjustmentValueForNumberOfCharacters = darkColorString.Length / 2 != 1 ? darkColorString.Length / 2 : 0;
55 var verticalNumberOfRepeats = repeatPerModule + adjustmentValueForNumberOfCharacters;
56 var sideLength = (QrCodeData.ModuleMatrix.Count - quietZonesModifier) * verticalNumberOfRepeats;
57 var qrCode = new string[sideLength];
💬 The operands in the divisive expression darkColorString.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 154 hits
📄 QRCoder\QRCodeGenerator\AlignmentPattern.cs (line 9)
6 /// Represents the alignment pattern used in QR codes, which helps ensure the code remains readable even if it is somewhat distorted.
7 /// Each QR code version has its own specific alignment pattern locations which this struct encapsulates.
8 /// </summary>
9 private struct AlignmentPattern
10 {
11 /// <summary>
12 /// The version of the QR code. Higher versions have more complex and numerous alignment patterns.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct AlignmentPattern. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 QRCoder\QRCodeGenerator\AlignmentPattern.cs (line 9)
6 /// Represents the alignment pattern used in QR codes, which helps ensure the code remains readable even if it is somewhat distorted.
7 /// Each QR code version has its own specific alignment pattern locations which this struct encapsulates.
8 /// </summary>
9 private struct AlignmentPattern
10 {
11 /// <summary>
12 /// The version of the QR code. Higher versions have more complex and numerous alignment patterns.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct AlignmentPattern. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS066 Disposable field is not disposed 14 hits
📄 QRCoder\PngByteQRCode.cs (line 172)
169 Indexed = 3
170 }
171
172 private MemoryStream _stream = new MemoryStream();
173
174 public void Dispose()
175 {
💬 Disposable field _stream in type PngBuilder is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 QRCoder\PngByteQRCode.cs (line 172)
169 Indexed = 3
170 }
171
172 private MemoryStream _stream = new MemoryStream();
173
174 public void Dispose()
175 {
💬 Disposable field _stream in type PngBuilder is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Akka.NET

590 total diagnostics across 16 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 16 hits
No source samples extracted
SS003 Integer divided by integer causing implicit rounding 70 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 20 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 112 hits
No source samples extracted
SS015 String placeholders in wrong order 4 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 116 hits
No source samples extracted
SS018 Switch does not handle all enum options 16 hits
No source samples extracted
SS019 Switch is missing default label 80 hits
No source samples extracted
SS023 Exception thrown from property getter 56 hits
No source samples extracted
SS034 Accessing Task.Result without await 48 hits
No source samples extracted
SS046 Unbounded stackalloc 8 hits
No source samples extracted
SS047 LINQ traversal before filter 4 hits
No source samples extracted
SS048 Locking on discouraged object (string, Type, this) 4 hits
No source samples extracted
SS052 [ThreadStatic] field with initializer 8 hits
No source samples extracted
SS058 String concatenated in a loop 8 hits
No source samples extracted
SS066 Disposable field is not disposed 20 hits
No source samples extracted

FastEndpoints

588 total diagnostics across 17 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 58 hits
No source samples extracted
SS003 Integer divided by integer causing implicit rounding 14 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 34 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 94 hits
No source samples extracted
SS018 Switch does not handle all enum options 6 hits
No source samples extracted
SS019 Switch is missing default label 130 hits
No source samples extracted
SS024 Exception thrown from static constructor 18 hits
No source samples extracted
SS033 Async overload is available 106 hits
No source samples extracted
SS037 HttpClient instantiated directly 20 hits
No source samples extracted
SS044 Attribute must specify [AttributeUsage] 8 hits
No source samples extracted
SS047 LINQ traversal before filter 6 hits
No source samples extracted
SS053 Pointless collection ToString() 10 hits
No source samples extracted
SS056 HttpRequest.Form read synchronously 30 hits
No source samples extracted
SS057 Collection manipulated during traversal 18 hits
No source samples extracted
SS058 String concatenated in a loop 6 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 6 hits
No source samples extracted
SS066 Disposable field is not disposed 24 hits
No source samples extracted

lively

586 total diagnostics across 11 rules

SS001 Async method with void return type 6 hits
📄 src\Lively\Lively.Common\Extensions\TaskExtensions.cs (line 11)
8 {
9 //Ref: https://www.youtube.com/watch?v=O1Tx-k4Vao0
10 [System.Diagnostics.CodeAnalysis.SuppressMessage("Major Bug", "S3168:\"async\" methods should not return \"void\"", Justification = "Error is handled as event")]
11 public async static void Await(this Task task, Action completedCallBack, Action<Exception> errorCallBack)
12 {
13 try
14 {
💬 Method Await is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Lively\Lively.Common.Services\HardwareUsageService.cs (line 79)
76 }
77 }
78
79 private async void HWMonitorLoop()
80 {
81 try
82 {
💬 Method HWMonitorLoop is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 20 hits
📄 src\Lively\Lively.Common.Services\GithubUpdaterService.cs (line 59)
56
57 private void RetryTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
58 {
59 if ((DateTime.Now - LastCheckTime).TotalMilliseconds > (Status != AppUpdateStatus.error ? fetchDelayRepeat : fetchDelayError))
60 {
61 _ = CheckUpdate(0);
62 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Lively\Lively.Common.Services\GithubUpdaterService.cs (line 100)
97 Debug.WriteLine("Update fetch error:" + e.ToString());
98 Status = AppUpdateStatus.error;
99 }
100 LastCheckTime = DateTime.Now;
101
102 UpdateChecked?.Invoke(this,
103 new AppUpdaterEventArgs(Status,
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 110 hits
📄 src\Lively\Lively.ML\Helpers\ImageUtil.cs (line 21)
18 var pixels = image.GetPixels();
19 for (int i = 0; i < floatArray.Length; i++)
20 {
21 pixels.SetPixel(i % width, i / width, new byte[] { (byte)(floatArray[i] * Quantum.Max), (byte)(floatArray[i] * Quantum.Max), (byte)(floatArray[i] * Quantum.Max) });
22 }
23 return image;
24 }
💬 The operands in the divisive expression i / width are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Lively\Lively.Common\Helpers\Hardware\SystemInfo.cs (line 129)
126 public static long GetTotalInstalledMemory()
127 {
128 GetPhysicallyInstalledSystemMemory(out long memKb);
129 return (memKb / 1024);
130 }
131 }
132}
💬 The operands in the divisive expression memKb / 1024 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 src\Lively\Lively\Commandline\CommandHandler.cs (line 199)
196
197 // Select a random wallpaper that is Not already used and Not the same as the current wallpaper on this screen.
198 var newWallpaper =
199 wallpapers.FirstOrDefault(x => (currentWallpaper == null || x.LivelyInfoFolderPath != currentWallpaper.Model.LivelyInfoFolderPath) && !usedWallpapers.Contains(x))
200 // Fallback if all match currentWallpaper
201 ?? wallpapers.FirstOrDefault(x => !usedWallpapers.Contains(x))
202 // Fallback to the first wallpaper if all are used
💬 Type LibraryModel is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Lively\Lively\Commandline\CommandHandler.cs (line 201)
198 var newWallpaper =
199 wallpapers.FirstOrDefault(x => (currentWallpaper == null || x.LivelyInfoFolderPath != currentWallpaper.Model.LivelyInfoFolderPath) && !usedWallpapers.Contains(x))
200 // Fallback if all match currentWallpaper
201 ?? wallpapers.FirstOrDefault(x => !usedWallpapers.Contains(x))
202 // Fallback to the first wallpaper if all are used
203 ?? wallpapers.First();
204
💬 Type LibraryModel is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 32 hits
📄 src\Lively\Lively.Common\Helpers\Pinvoke\DwmThumbnailWrapper.cs (line 97)
94 #region native
95
96 [StructLayout(LayoutKind.Sequential)]
97 internal struct DWM_THUMBNAIL_PROPERTIES
98 {
99 public int dwFlags;
100 public RECT rcDestination;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DWM_THUMBNAIL_PROPERTIES. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Lively\Lively.Common\Helpers\Shell\ThumbnailUtil.cs (line 86)
83 }
84
85 [StructLayout(LayoutKind.Sequential)]
86 internal struct NativeSize
87 {
88 private int width;
89 private int height;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NativeSize. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 28 hits
📄 src\Lively\Lively\Views\WindowMsg\RawInputMsgWindow.xaml.cs (line 96)
93 break;
94 }
95
96 switch (mouse.Mouse.Buttons)
97 {
98 case Linearstar.Windows.RawInput.Native.RawMouseButtonFlags.LeftButtonDown:
99 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Lively\Lively\Core\Wallpapers\WebWebView2.cs (line 265)
262 }
263
264 // Process message
265 switch (obj.Type)
266 {
267 case MessageType.msg_hwnd:
268 if (!isInitialized)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 182 hits
📄 src\Lively\Lively.Common\Factories\WallpaperLibraryFactory.cs (line 183)
180 if (!metadata.IsAbsolutePath)
181 return;
182
183 switch (metadata.Type)
184 {
185 case WallpaperType.video:
186 case WallpaperType.gif:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Lively\Lively.Common\Helpers\LivelyPropertyUtil.cs (line 102)
99 continue;
100
101 var value = localized.Value;
102 switch (control.Type)
103 {
104 case "dropdown":
105 case "scalerDropdown":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 6 hits
📄 src\Lively\Lively.Gallery.Client\GalleryClient.cs (line 92)
89 _server.Routes.Static.Add(WatsonWebserver.HttpMethod.GET, "signin-oidc", GoogleCallback);
90 break;
91 }
92 _server.Start();
93
94 LinkUtil.OpenBrowser(
95 provider switch
💬 Async overload available for Server.Start (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Lively\Lively\Helpers\CaptureScreen.cs (line 140)
137 // Optionally optimize the images (images should have the same size).
138 collection.Optimize();
139 // Save image to disk.
140 collection.Write(savePath);
141 }
142 }
143 finally
💬 Async overload available for MagickImageCollection.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 36 hits
📄 src\Lively\Lively\Core\Wallpapers\WebWebView2.cs (line 191)
188 process.BeginOutputReadLine();
189
190 await tcsProcessWait.Task;
191 if (tcsProcessWait.Task.Result is not null)
192 throw tcsProcessWait.Task.Result;
193 }
194 catch (Exception)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Lively\Lively\Core\Wallpapers\WebWebView2.cs (line 192)
189
190 await tcsProcessWait.Task;
191 if (tcsProcessWait.Task.Result is not null)
192 throw tcsProcessWait.Task.Result;
193 }
194 catch (Exception)
195 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS059 IAsyncDisposable not disposed asynchronously 26 hits
📄 src\Lively\Lively.Common.Services\HttpDownloadService.cs (line 27)
24 if (!string.IsNullOrEmpty(directory))
25 Directory.CreateDirectory(directory);
26
27 using var stream = File.Create(filePath);
28 await DownloadFileAsync(url, stream, cancellationToken, (downloadedBytes, totalBytes) =>
29 {
30 var downloadedInMB = Math.Truncate(ByteToMegabyte(downloadedBytes));
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Lively\Lively.Common.Services\HttpDownloadService.cs (line 80)
77 if (progressCallback != null)
78 {
79 long length = response.Content.Headers.ContentLength ?? -1;
80 using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
81 byte[] buffer = new byte[4096];
82 int read;
83 int totalRead = 0;
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 128 hits
📄 src\Lively\Lively.ML\DepthEstimate\MiDaS.cs (line 17)
14 public class MiDaS : IDepthEstimate
15 {
16 public string ModelPath { get; private set; }
17 private InferenceSession session;
18 private string inputName;
19 private int width, height;
20 private bool disposedValue;
💬 Disposable field session in type MiDaS is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Lively\Lively.Grpc.Client\DisplayManagerClient.cs (line 27)
24 public System.Drawing.Rectangle VirtulScreenBounds { get; private set; }
25
26 private readonly DisplayService.DisplayServiceClient client;
27 private readonly SemaphoreSlim displayChangedLock = new SemaphoreSlim(1, 1);
28 private readonly CancellationTokenSource cancellationTokeneDisplayChanged;
29 private readonly Task displayChangedTask;
30 private bool disposedValue;
💬 Disposable field displayChangedLock in type DisplayManagerClient is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

netmq

582 total diagnostics across 14 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 44 hits
📄 src\NetMQ.Tests\PgmTests.cs (line 284)
281
282 monitor.Closed += (sender, args) => closed.Set();
283
284 var time = DateTime.Now;
285
286 sub.Unbind(address);
287
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\NetMQ.Tests\RequestWithRetryTests.cs (line 27)
24 using (var server = new ResponseSocket(address))
25 {
26 progressSubscriber.SubscribeToAnyTopic();
27 var progressProactor = new NetMQProactor(progressSubscriber, (socket, message) => Debug.WriteLine("C: {0} {1:ss.fff}", message[0].ConvertToString(), DateTime.Now));
28
29 var serverProactor = new NetMQProactor(server, (socket, message) =>
30 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 72 hits
📄 src\NetMQ\Core\Utils\Clock.cs (line 90)
87
88 if (tsc == 0)
89 {
90 return NowUs() / 1000;
91 }
92
93 if (tsc - s_lastTsc <= Config.ClockPrecision / 2 && tsc >= s_lastTsc)
💬 The operands in the divisive expression NowUs() / 1000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\NetMQ\Core\Utils\Clock.cs (line 93)
90 return NowUs() / 1000;
91 }
92
93 if (tsc - s_lastTsc <= Config.ClockPrecision / 2 && tsc >= s_lastTsc)
94 {
95 return s_lastTime;
96 }
💬 The operands in the divisive expression Config.ClockPrecision / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 144 hits
📄 src\NetMQ\Core\Utils\Proactor.cs (line 74)
71 public void AddSocket(AsyncSocket socket, IProactorEvents proactorEvents)
72 {
73 var item = new Item(proactorEvents);
74 m_sockets.Add(socket, item);
75
76 m_completionPort.AssociateSocket(socket, item);
77 AdjustLoad(1);
💬 Type AsyncSocket is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\NetMQ\Core\Utils\Proactor.cs (line 84)
81 {
82 AdjustLoad(-1);
83
84 var item = m_sockets[socket];
85 m_sockets.Remove(socket);
86 item.Cancelled = true;
87 }
💬 Type AsyncSocket is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 96 hits
📄 src\NetMQ\RoutingKey.cs (line 118)
115 {
116 unchecked
117 {
118 int remainder = bytes.Length & 3;
119 int alignedLength = bytes.Length - remainder;
120
121 uint hash = 0;
💬 GetHashCode() refers to mutable field bytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\NetMQ\RoutingKey.cs (line 119)
116 unchecked
117 {
118 int remainder = bytes.Length & 3;
119 int alignedLength = bytes.Length - remainder;
120
121 uint hash = 0;
122
💬 GetHashCode() refers to mutable field bytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 18 hits
📄 src\NetMQ\Core\Command.cs (line 27)
24 /// <summary>
25 /// Defines a command sent between threads.
26 /// </summary>
27 internal struct Command
28 {
29 /// <summary>
30 /// Create a new Command object for the given destination, type, and optional argument.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Command. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\NetMQ\NetMQBeacon.cs (line 534)
531 /// <summary>
532 /// Contents of a message received from a beacon.
533 /// </summary>
534 public struct BeaconMessage
535 {
536 /// <summary>
537 /// THe beacon content as a byte array.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BeaconMessage. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 24 hits
📄 src\NetMQ\Core\Patterns\Router.cs (line 186)
183 {
184 T Get<T>() => optval is T v ? v : throw new ArgumentException($"Option {option} value must be of type {typeof(T).Name}.");
185
186 switch (option)
187 {
188 case ZmqSocketOption.RouterRawSocket:
189 m_rawSocket = Get<bool>();
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\NetMQ\Core\Patterns\XPub.cs (line 227)
224 {
225 T Get<T>() => optionValue is T v ? v : throw new ArgumentException($"Option {option} value must be of type {typeof(T).Name}.");
226
227 switch (option)
228 {
229 case ZmqSocketOption.XpubVerbose:
230 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 90 hits
📄 src\NetMQ\Core\Address.cs (line 115)
112 {
113 if (Resolved != null)
114 {
115 switch (Protocol)
116 {
117 case TcpProtocol: return Resolved!.ToString()!;
118 case IpcProtocol: return Resolved!.ToString()!;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\NetMQ\RoutingKey.cs (line 142)
139 uint k = 0;
140
141 // determine how many bytes we have left to work with based on length
142 switch (remainder)
143 {
144 case 3:
145 k ^= (uint)bytes[alignedLength + 2] << 16;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS027 Exception thrown from Dispose 12 hits
📄 src\NetMQ\NetMQPoller.cs (line 708)
705 // Attempting to dispose from the poller thread would cause a deadlock.
706 // Throw an exception to improve the debugging experience.
707 if (IsPollerThread)
708 throw new InvalidOperationException("Cannot dispose poller from the poller thread.");
709
710 if (Interlocked.CompareExchange(ref m_disposeState, (int)DisposeState.Disposing, (int)DisposeState.Undisposed) != (int)DisposeState.Undisposed)
711 return;
💬 An exception is thrown from the Dispose() method in type NetMQPoller (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 src\NetMQ\NetMQPoller.cs (line 731)
728 foreach (var socket in m_sockets)
729 {
730 if (socket.IsDisposed)
731 throw new NetMQException($"Invalid state detected: {nameof(NetMQPoller)} contains a disposed {nameof(NetMQSocket)}. Sockets must be either removed before being disposed, or disposed after the poller is disposed.");
732 socket.EventsChanged -= OnSocketEventsChanged;
733 }
734
💬 An exception is thrown from the Dispose() method in type NetMQPoller (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS032 Thread.Sleep used in async method 4 hits
📄 src\NetMQ.Tests\NetMQMonitorTests.cs (line 68)
65 using (var monitor = new NetMQMonitor(rep, "inproc://foo", SocketEvents.Closed))
66 {
67 var task = monitor.StartAsync();
68 Thread.Sleep(200);
69 Assert.Equal(TaskStatus.Running, task.Status);
70 monitor.Stop();
71 var completedTask = await Task.WhenAny(task, Task.Delay(1000));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 src\NetMQ.Tests\NetMQMonitorTests.cs (line 68)
65 using (var monitor = new NetMQMonitor(rep, "inproc://foo", SocketEvents.Closed))
66 {
67 var task = monitor.StartAsync();
68 Thread.Sleep(200);
69 Assert.Equal(TaskStatus.Running, task.Status);
70 monitor.Stop();
71 var completedTask = await Task.WhenAny(task, Task.Delay(1000));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 12 hits
📄 src\NetMQ.Tests\ClientServer.cs (line 146)
143
144 for (int i = 0; i < 15000; i++)
145 {
146 client.Send("0");
147 }
148
149 // Send the end message to both of the threads
💬 Async overload available for SendThreadSafeSocketExtensions.Send (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\NetMQ.Tests\ClientServer.cs (line 150)
147 }
148
149 // Send the end message to both of the threads
150 client.Send("1");
151 client.Send("1");
152
153 await Task.WhenAll(t1, t2);
💬 Async overload available for SendThreadSafeSocketExtensions.Send (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 12 hits
📄 src\NetMQ\NetMQPoller.cs (line 752)
749 object ISynchronizeInvoke.EndInvoke(IAsyncResult result)
750 {
751 var task = (Task<object>)result;
752 return task.Result;
753 }
754
755 object? ISynchronizeInvoke.Invoke(Delegate method, object?[]? args)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\NetMQ\NetMQPoller.cs (line 762)
759
760 var task = new Task<object?>(() => method.DynamicInvoke(args));
761 task.Start(this);
762 return task.Result;
763 }
764
765 bool ISynchronizeInvoke.InvokeRequired => !CanExecuteTaskInline;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS051 Locking on mutable reference 12 hits
📄 src\NetMQ\Core\MailboxSafe.cs (line 62)
59
60 public void Send(Command cmd)
61 {
62 lock (m_sync)
63 {
64 m_commandPipe.Write(ref cmd, false);
65 bool ok = m_commandPipe.Flush();
💬 A lock was obtained on m_sync but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\NetMQ\Core\SocketBase.cs (line 1197)
1194 m_handle = ((Mailbox)m_mailbox).Handle;
1195 else
1196 {
1197 lock (m_threadSafeSync)
1198 {
1199 m_reaperSignaler = new Signaler();
1200 m_handle = m_reaperSignaler.Handle;
💬 A lock was obtained on m_threadSafeSync but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 6 hits
📄 src\NetMQ\NetMQCertificate.cs (line 49)
46 UInt32 divisor = 85 * 85 * 85 * 85;
47 while (divisor != 0)
48 {
49 dest += Encoder[(int)(value / divisor % 85)];
50 divisor /= 85;
51 }
52 value = 0;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\NetMQ\NetMQCertificate.cs (line 49)
46 UInt32 divisor = 85 * 85 * 85 * 85;
47 while (divisor != 0)
48 {
49 dest += Encoder[(int)(value / divisor % 85)];
50 divisor /= 85;
51 }
52 value = 0;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 36 hits
📄 src\NetMQ\Core\Mechanisms\CurveMechanismBase.cs (line 26)
23
24 protected UInt64 m_nonce;
25 protected UInt64 m_peerNonce;
26 protected Curve25519XSalsa20Poly1305? m_box;
27
28 protected CurveMechanismBase(SessionBase session, Options options,
29 string encodeNoncePrefix, string decodeNoncePrefix) : base(session, options)
💬 Disposable field m_box in type CurveMechanismBase is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\NetMQ\NetMQSocket.cs (line 25)
22 private EventHandler<NetMQSocketEventArgs>? m_sendReady;
23 private int m_isClosed;
24
25 private NetMQRuntime? m_runtime;
26
27 internal enum DefaultAction
28 {
💬 Disposable field m_runtime in type NetMQSocket is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

MassTransit

548 total diagnostics across 12 rules

SS003 Integer divided by integer causing implicit rounding 70 hits
No source samples extracted
SS007 [Flags] enum values are not powers of two 10 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 162 hits
No source samples extracted
SS018 Switch does not handle all enum options 4 hits
No source samples extracted
SS019 Switch is missing default label 28 hits
No source samples extracted
SS022 Exception thrown from implicit operator 20 hits
No source samples extracted
SS033 Async overload is available 24 hits
No source samples extracted
SS034 Accessing Task.Result without await 30 hits
No source samples extracted
SS044 Attribute must specify [AttributeUsage] 10 hits
No source samples extracted
SS046 Unbounded stackalloc 10 hits
No source samples extracted
SS048 Locking on discouraged object (string, Type, this) 140 hits
No source samples extracted
SS066 Disposable field is not disposed 40 hits
No source samples extracted

SharpZipLib

544 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 30 hits
📄 src\ICSharpCode.SharpZipLib\Zip\ZipEntryFactory.cs (line 366)
363 #region Instance Fields
364
365 private INameTransform nameTransform_;
366 private DateTime fixedDateTime_ = DateTime.Now;
367 private TimeSetting timeSetting_ = TimeSetting.LastWriteTime;
368 private bool isUnicodeText_;
369
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\ICSharpCode.SharpZipLib\Core\StreamUtils.cs (line 226)
223
224 bool copying = true;
225
226 DateTime marker = DateTime.Now;
227 long processed = 0;
228 long target = 0;
229
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 150 hits
📄 src\ICSharpCode.SharpZipLib\BZip2\BZip2Constants.cs (line 110)
107 /// <summary>
108 /// Backend constant
109 /// </summary>
110 public const int MaximumSelectors = (2 + (900000 / GroupSize));
111
112 /// <summary>
113 /// Backend constant
💬 The operands in the divisive expression 900000 / GroupSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\ICSharpCode.SharpZipLib\Zip\Compression\DeflaterConstants.cs (line 84)
81 /// <summary>
82 /// Internal compression engine constant
83 /// </summary>
84 public const int HASH_SHIFT = (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH;
85
86 /// <summary>
87 /// Internal compression engine constant
💬 The operands in the divisive expression (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 src\ICSharpCode.SharpZipLib\Tar\TarEntry.cs (line 160)
157 /// <returns>A Hash code for the current <see cref="Object"/></returns>
158 public override int GetHashCode()
159 {
160 return Name.GetHashCode();
161 }
162
163 /// <summary>
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\ICSharpCode.SharpZipLib\Tar\TarHeader.cs (line 684)
681 /// <returns>A hash code for the current object.</returns>
682 public override int GetHashCode()
683 {
684 return Name.GetHashCode();
685 }
686
687 /// <summary>
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 18 hits
📄 src\ICSharpCode.SharpZipLib\BZip2\BZip2OutputStream.cs (line 2026)
2023 return b;
2024 }
2025
2026 private struct StackElement
2027 {
2028 public int ll;
2029 public int hh;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct StackElement. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\ICSharpCode.SharpZipLib\Zip\ZipFormat.cs (line 36)
33 }
34 }
35
36 internal struct EntryPatchData
37 {
38 public long SizePatchOffset { get; set; }
39
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EntryPatchData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 12 hits
📄 src\ICSharpCode.SharpZipLib\Zip\FastZip.cs (line 691)
688 // (it might have been set up by the entry factory, and if so we let that take precedence)
689 if (!string.IsNullOrEmpty(Password) && entry.AESEncryptionStrength == 0)
690 {
691 switch (EntryEncryptionMethod)
692 {
693 case ZipEncryptionMethod.AES128:
694 entry.AESKeySize = 128;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\ICSharpCode.SharpZipLib\Zip\ZipInputStream.cs (line 699)
696
697 bool finished = false;
698
699 switch (method)
700 {
701 case CompressionMethod.Deflated:
702 count = base.Read(buffer, offset, count);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 66 hits
📄 src\ICSharpCode.SharpZipLib\BZip2\BZip2InputStream.cs (line 301)
298 }
299
300 int retChar = currentChar;
301 switch (currentState)
302 {
303 case RAND_PART_B_STATE:
304 SetupRandPartB();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\ICSharpCode.SharpZipLib\BZip2\BZip2OutputStream.cs (line 1768)
1765 zPend--;
1766 while (true)
1767 {
1768 switch (zPend % 2)
1769 {
1770 case 0:
1771 szptr[wr] = (short)BZip2Constants.RunA;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 84 hits
📄 src\ICSharpCode.SharpZipLib\Core\ExactMemoryPool.cs (line 51)
48 T[] array = this.array;
49 if (array == null)
50 {
51 throw new ObjectDisposedException(nameof(ExactMemoryPoolBuffer));
52 }
53
54 return new Memory<T>(array).Slice(0, size);
💬 An exception is thrown from the getter of property Memory (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\ICSharpCode.SharpZipLib\Tar\TarArchive.cs (line 276)
273 {
274 if (isDisposed)
275 {
276 throw new ObjectDisposedException("TarArchive");
277 }
278
279 return asciiTranslate;
💬 An exception is thrown from the getter of property AsciiTranslate (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 6 hits
📄 src\ICSharpCode.SharpZipLib\Zip\Compression\InflaterHuffmanTree.cs (line 68)
65 }
66 catch (Exception)
67 {
68 throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal");
69 }
70 }
71
💬 An exception is thrown from InflaterHuffmanTree its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 src\ICSharpCode.SharpZipLib\Zip\Compression\InflaterHuffmanTree.cs (line 68)
65 }
66 catch (Exception)
67 {
68 throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal");
69 }
70 }
71
💬 An exception is thrown from InflaterHuffmanTree its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS033 Async overload is available 74 hits
📄 src\ICSharpCode.SharpZipLib\GZip\GzipOutputStream.cs (line 169)
166 }
167 else
168 {
169 WriteHeader();
170 }
171 }
172
💬 Async overload available for GZipOutputStream.WriteHeader (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\ICSharpCode.SharpZipLib\GZip\GzipOutputStream.cs (line 184)
181 }
182 else
183 {
184 base.Write(buffer, offset, count);
185 }
186 }
187
💬 Async overload available for DeflaterOutputStream.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS051 Locking on mutable reference 24 hits
📄 src\ICSharpCode.SharpZipLib\Zip\ZipFile.cs (line 1179)
1176 /// <returns>The offset of the entries data in the file</returns>
1177 private long TestLocalHeader(ZipEntry entry, HeaderTest tests)
1178 {
1179 lock (baseStream_)
1180 {
1181 bool testHeader = (tests & HeaderTest.Header) != 0;
1182 bool testData = (tests & HeaderTest.Extract) != 0;
💬 A lock was obtained on baseStream_ but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\ICSharpCode.SharpZipLib\Zip\ZipFile.cs (line 3448)
3445
3446 if (IsStreamOwner && (baseStream_ != null))
3447 {
3448 lock (baseStream_)
3449 {
3450 baseStream_.Dispose();
3451 }
💬 A lock was obtained on baseStream_ but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 src\ICSharpCode.SharpZipLib\Core\StreamUtils.cs (line 289)
286
287 internal static async Task WriteProcToStreamAsync(this Stream targetStream, Action<Stream> writeProc, CancellationToken ct)
288 {
289 using (var ms = new MemoryStream())
290 {
291 await WriteProcToStreamAsync(targetStream, ms, writeProc, ct).ConfigureAwait(false);
292 }
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\ICSharpCode.SharpZipLib\Zip\ZipOutputStream.cs (line 913)
910 /// <inheritdoc cref="Finish"/>>
911 public override async Task FinishAsync(CancellationToken ct)
912 {
913 using (var ms = new MemoryStream())
914 {
915 if (entries == null)
916 {
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 60 hits
📄 src\ICSharpCode.SharpZipLib\Tar\TarOutputStream.cs (line 602)
599 /// <summary>
600 /// the destination stream for the archive contents
601 /// </summary>
602 protected Stream outputStream;
603
604 /// <summary>
605 /// name encoding
💬 Disposable field outputStream in type TarOutputStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\ICSharpCode.SharpZipLib\Encryption\ZipAESStream.cs (line 51)
48 // total length of block + auth code
49 private const int BLOCK_AND_AUTH = CRYPTO_BLOCK_SIZE + AUTH_CODE_LENGTH;
50
51 private Stream _stream;
52 private ZipAESTransform _transform;
53 private byte[] _slideBuffer;
54 private int _slideBufStartPos;
💬 Disposable field _stream in type ZipAESStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

LiteMonitor

542 total diagnostics across 11 rules

SS001 Async method with void return type 10 hits
📄 src\UI\Settings\TaskbarPage.cs (line 61)
58 PopulateFonts();
59 }
60
61 private async void PopulateFonts()
62 {
63 if (_cbFont == null || _cbFont.Inner.Items.Count > 5) return;
64
💬 Method PopulateFonts is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\UI\Settings\SystemHardwarPage.cs (line 48)
45 }
46
47 // 将 PopulateAsyncData 改为“批量处理”模式
48 private async void PopulateAsyncData()
49 {
50 try
51 {
💬 Method PopulateAsyncData is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 98 hits
📄 LiteMonitor.Updater\Program.cs (line 301)
298 try
299 {
300 File.AppendAllText(Path.Combine(dir, "update_error.log"),
301 DateTime.Now + " " + msg + Environment.NewLine);
302 }
303 catch { }
304 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\System\HardwareMonitor.cs (line 45)
42 private long _tickCounter = 0;
43 private double _secondAccumulator = 0;
44 private long _secondsCounter = 0;
45 private DateTime _lastTrafficTime = DateTime.Now;
46 #endregion
47
48 #region Public Properties
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 102 hits
📄 src\Core\UIUtils.cs (line 87)
84 // Cache eviction policy
85 if (_brushCache.Count >= MAX_BRUSH_CACHE)
86 {
87 var keysToRemove = _brushCache.Keys.Take(_brushCache.Count / 2).ToList();
88 foreach (var k in keysToRemove)
89 {
90 if (_brushCache.TryGetValue(k, out var oldBrush))
💬 The operands in the divisive expression _brushCache.Count / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\UI\HorizontalLayout.cs (line 59)
56
57 var s = _settings.GetStyle();
58 int pad = _padding;
59 int padV = _padding / 2;
60 bool isTaskbarSingle = (_mode == LayoutMode.Taskbar && _settings.TaskbarSingleLine);
61 bool isHorizontalSingle = (_mode == LayoutMode.Horizontal && _settings.HorizontalSingleLine);
62
💬 The operands in the divisive expression _padding / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 8 hits
📄 src\UI\Settings\MonitorPage.cs (line 456)
453 var newVisibleList = uiRows.Select(r => r.Config).ToList();
454
455 var fullList = _workingList.OrderBy(x => x.TaskbarSortIndex).ToList();
456 var oldVisibleList = fullList.Where(x => newVisibleList.Contains(x)).ToList();
457
458 var lcs = GetLCS(oldVisibleList, newVisibleList);
459 var anchors = new HashSet<MonitorItemConfig>(lcs);
💬 Type MonitorItemConfig is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\UI\Settings\MonitorPage.cs (line 464)
461 var backbone = new List<MonitorItemConfig>();
462 foreach (var item in fullList)
463 {
464 if (!newVisibleList.Contains(item) || anchors.Contains(item))
465 {
466 backbone.Add(item);
467 }
💬 Type MonitorItemConfig is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 8 hits
📄 src\Core\Settings.cs (line 156)
153 public List<PluginInstanceConfig> PluginInstances { get; set; } = new List<PluginInstanceConfig>();
154
155 // ★★★ [新增] 极简样式封装(复制到 Settings 类里) ★★★
156 public struct TBStyle {
157 public string Font; public float Size; public bool Bold;
158 public int Gap; public int Inner; public int VOff;
159 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TBStyle. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\System\HardwareServices\FpsCounter.cs (line 95)
92 /// 内部结构体:一次采样的记录
93 /// 存储某段时间内的帧数和持续时间
94 /// </summary>
95 private struct FrameSample
96 {
97 public int Count; // 这一段收到的帧数
98 public double Duration; // 这一段花费的时间(秒)
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FrameSample. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 2 hits
📄 src\Plugins\PluginProcessor.cs (line 98)
95
96 string val = context[src];
97
98 switch (t.Function)
99 {
100 case "regex_replace":
101 val = ApplyRegexReplace(val, t, context);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Plugins\PluginProcessor.cs (line 98)
95
96 string val = context[src];
97
98 switch (t.Function)
99 {
100 case "regex_replace":
101 val = ApplyRegexReplace(val, t, context);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 6 hits
📄 src\Core\NetworkSpeedTester.cs (line 281)
278 catch (TaskCanceledException) { }
279
280 // 取消所有任务
281 cts.Cancel();
282
283 // 优化点3:增加 Task.WhenAll 的等待时限,避免卡死在收尾阶段
284 try
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Core\NetworkSpeedTester.cs (line 404)
401 }
402 catch (TaskCanceledException) { }
403
404 cts.Cancel();
405
406 // 优化点3:增加 Task.WhenAll 的等待时限
407 try
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 12 hits
📄 src\UI\Settings\SystemHardwarPage.cs (line 87)
84 }
85
86 // 3. 瞬间填入所有数据 (因为布局被挂起,用户看不见中间过程)
87 FillSync(_cbDisk, taskDisks.Result, Config.PreferredDisk);
88 FillSync(_cbNet, taskNets.Result, Config.PreferredNetwork);
89 FillSync(_cbMobo, taskMobo.Result, Config.PreferredMoboTemp);
90
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\UI\Settings\SystemHardwarPage.cs (line 88)
85
86 // 3. 瞬间填入所有数据 (因为布局被挂起,用户看不见中间过程)
87 FillSync(_cbDisk, taskDisks.Result, Config.PreferredDisk);
88 FillSync(_cbNet, taskNets.Result, Config.PreferredNetwork);
89 FillSync(_cbMobo, taskMobo.Result, Config.PreferredMoboTemp);
90
91 // Fan 的数据是复用的
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS049 Comparing strings without StringComparison 26 hits
📄 src\UI\UpdateDialog.cs (line 38)
35
36 private CancellationTokenSource? _cts;
37 private Stopwatch _speedWatch;
38 private bool IsChinese => _settings?.Language?.ToLower() == "zh";
39
40 public UpdateDialog(DownloadContext context, Settings settings)
41 {
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\System\UpdateChecker.cs (line 134)
131 var sortedUrls = await GetSortedZipUrls(latest);
132
133 // ---- 加载设置并弹出更新窗口 ----
134 bool isZh = settings?.Language?.ToLower() == "zh";
135
136 var context = new DownloadContext
137 {
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS059 IAsyncDisposable not disposed asynchronously 14 hits
📄 src\System\UpdateChecker.cs (line 287)
284 if (!resp.IsSuccessStatusCode)
285 return (url, 0);
286
287 using var stream = await resp.Content.ReadAsStreamAsync();
288
289 byte[] testBuf = new byte[32 * 1024];
290 int read = await stream.ReadAsync(testBuf, 0, testBuf.Length);
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Core\NetworkSpeedTester.cs (line 132)
129 continue;
130 }
131
132 using var stream = await resp.Content.ReadAsStreamAsync();
133 var sw = Stopwatch.StartNew();
134
135 // 持续读取直到竞速时间结束
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 256 hits
📄 src\UI\Controls\LiteUI.cs (line 431)
428
429 public class LiteColorInput : Panel
430 {
431 public LiteUnderlineInput Input;
432 public LiteColorPicker Picker;
433 public string HexValue { get => Input.Inner.Text; set { Input.Inner.Text = value; Picker.SetHex(value); } }
434
💬 Disposable field Input in type LiteColorInput is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\UI\Controls\LiteUI.cs (line 432)
429 public class LiteColorInput : Panel
430 {
431 public LiteUnderlineInput Input;
432 public LiteColorPicker Picker;
433 public string HexValue { get => Input.Inner.Text; set { Input.Inner.Text = value; Picker.SetHex(value); } }
434
435 public LiteColorInput(string initialHex)
💬 Disposable field Picker in type LiteColorInput is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

libgit2sharp

540 total diagnostics across 10 rules

SS003 Integer divided by integer causing implicit rounding 6 hits
📄 LibGit2Sharp.Tests\FilterFixture.cs (line 351)
348 }
349
350 int len = count * sizeof(char);
351 int cnt = len / sizeof(long);
352
353 fixed (char* c1 = array1, c2 = array2)
354 {
💬 The operands in the divisive expression len / sizeof(long) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 LibGit2Sharp.Tests\FilterFixture.cs (line 351)
348 }
349
350 int len = count * sizeof(char);
351 int cnt = len / sizeof(long);
352
353 fixed (char* c1 = array1, c2 = array2)
354 {
💬 The operands in the divisive expression len / sizeof(long) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 72 hits
📄 LibGit2Sharp\Worktree.cs (line 117)
114 /// <returns>A 32-bit signed integer hash code.</returns>
115 public override int GetHashCode()
116 {
117 return equalityHelper.GetHashCode(this);
118 }
119
120 /// <summary>
💬 GetHashCode() refers to mutable field equalityHelper (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 LibGit2Sharp\BlameHunk.cs (line 153)
150 /// <returns>A 32-bit signed integer hash code.</returns>
151 public override int GetHashCode()
152 {
153 return equalityHelper.GetHashCode();
154 }
155
156 /// <summary>
💬 GetHashCode() refers to mutable field equalityHelper (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS015 String placeholders in wrong order 6 hits
📄 LibGit2Sharp.Tests\FetchFixture.cs (line 126)
123 {
124 repo.Network.Remotes.Add(remoteName, url);
125
126 string refSpec = string.Format("refs/heads/{2}:refs/remotes/{0}/{1}", remoteName, localBranchName, remoteBranchName);
127
128 // Set up structures for the expected results
129 // and verifying the RemoteUpdateTips callback.
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 LibGit2Sharp.Tests\FetchFixture.cs (line 126)
123 {
124 repo.Network.Remotes.Add(remoteName, url);
125
126 string refSpec = string.Format("refs/heads/{2}:refs/remotes/{0}/{1}", remoteName, localBranchName, remoteBranchName);
127
128 // Set up structures for the expected results
129 // and verifying the RemoteUpdateTips callback.
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 278 hits
📄 LibGit2Sharp\SignatureInfo.cs (line 8)
5 /// <summary>
6 /// Structure for holding a signature extracted from a commit or a tag
7 /// </summary>
8 public struct SignatureInfo
9 {
10 /// <summary>
11 /// The signature data, PGP/GPG or otherwise.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SignatureInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 LibGit2Sharp\RebaseOperationImpl.cs (line 201)
198 }
199 }
200
201 private struct RebaseProgress
202 {
203 public long current;
204 public long total;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RebaseProgress. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 20 hits
📄 LibGit2Sharp\Diff.cs (line 604)
601 RenameLimit = (UIntPtr)similarityOptions.RenameLimit,
602 };
603
604 switch (similarityOptions.RenameDetectionMode)
605 {
606 case RenameDetectionMode.Exact:
607 opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY |
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 LibGit2Sharp\Core\GitCheckoutOptsWrapper.cs (line 64)
61 {
62 CheckoutStrategy flags = default(CheckoutStrategy);
63
64 switch (fileConflictStrategy)
65 {
66 case CheckoutFileConflictStrategy.Ours:
67 flags = CheckoutStrategy.GIT_CHECKOUT_USE_OURS;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 34 hits
📄 LibGit2Sharp\Diff.cs (line 604)
601 RenameLimit = (UIntPtr)similarityOptions.RenameLimit,
602 };
603
604 switch (similarityOptions.RenameDetectionMode)
605 {
606 case RenameDetectionMode.Exact:
607 opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY |
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 LibGit2Sharp\Diff.cs (line 631)
628 opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_REMOVE_UNMODIFIED;
629 }
630
631 switch (similarityOptions.WhitespaceMode)
632 {
633 case WhitespaceMode.DontIgnoreWhitespace:
634 opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 20 hits
📄 LibGit2Sharp\Core\WriteStream.cs (line 29)
26 set { throw new InvalidOperationException(); }
27 }
28
29 public override long Length { get { throw new InvalidOperationException(); } }
30
31 public override void Flush()
32 { }
💬 An exception is thrown from the getter of property Length (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 LibGit2Sharp\GlobalSettings.cs (line 178)
175 {
176 if (!nativeLibraryPathAllowed)
177 {
178 throw new LibGit2SharpException("Querying the native hint path is only supported on .NET Framework and .NET Core platforms");
179 }
180
181 return nativeLibraryPath ?? nativeLibraryDefaultPath;
💬 An exception is thrown from the getter of property NativeLibraryPath (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 4 hits
📄 LibGit2Sharp.Tests\FilterFixture.cs (line 206)
203
204 foreach (var file in files)
205 {
206 string readAllText = File.ReadAllText(file.FullName);
207 Assert.Equal(decodedInput, readAllText);
208 }
209 }
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 LibGit2Sharp.Tests\FilterFixture.cs (line 206)
203
204 foreach (var file in files)
205 {
206 string readAllText = File.ReadAllText(file.FullName);
207 Assert.Equal(decodedInput, readAllText);
208 }
209 }
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS041 Unnecessary enumerable materialization 60 hits
📄 LibGit2Sharp.Tests\FilterBranchFixture.cs (line 30)
27 [Fact]
28 public void CanRewriteHistoryWithoutChangingCommitMetadata()
29 {
30 var originalRefs = repo.Refs.ToList().OrderBy(r => r.CanonicalName);
31 var commits = repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = repo.Refs }).ToArray();
32
33 // Noop header rewriter
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 LibGit2Sharp.Tests\FilterBranchFixture.cs (line 43)
40
41 AssertSucceedingButNotError();
42
43 Assert.Equal(originalRefs, repo.Refs.ToList().OrderBy(r => r.CanonicalName));
44 Assert.Equal(commits, repo.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = repo.Refs }).ToArray());
45 }
46
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS066 Disposable field is not disposed 40 hits
📄 LibGit2Sharp\CommitLog.cs (line 110)
107
108 private class CommitEnumerator : IEnumerator<Commit>
109 {
110 private readonly Repository repo;
111 private readonly RevWalkerHandle handle;
112 private ObjectId currentOid;
113
💬 Disposable field repo in type CommitEnumerator is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 LibGit2Sharp\CommitLog.cs (line 111)
108 private class CommitEnumerator : IEnumerator<Commit>
109 {
110 private readonly Repository repo;
111 private readonly RevWalkerHandle handle;
112 private ObjectId currentOid;
113
114 public CommitEnumerator(Repository repo, CommitFilter filter)
💬 Disposable field handle in type CommitEnumerator is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Jackett

540 total diagnostics across 20 rules

SS001 Async method with void return type 4 hits
📄 src\Jackett.Common\Services\UpdateService.cs (line 65)
62 locker.Set();
63 }
64
65 private async void UpdateWorkerThread()
66 {
67 var delayHours = 1; // first check after 1 hour (for users not running jackett 24/7)
68 while (true)
💬 Method UpdateWorkerThread is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Jackett.Common\Services\UpdateService.cs (line 65)
62 locker.Set();
63 }
64
65 private async void UpdateWorkerThread()
66 {
67 var delayHours = 1; // first check after 1 hour (for users not running jackett 24/7)
68 while (true)
💬 Method UpdateWorkerThread is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 188 hits
📄 src\DateTimeRoutines\DateTimeRoutines.cs (line 150)
147 get => DefaultDateIsNow ? DateTime.Now : _DefaultDate;
148 }
149
150 private static DateTime _DefaultDate = DateTime.Now;
151
152 /// <summary>
153 /// If true then DefaultDate property is ignored and DefaultDate is always DateTime.Now
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\DateTimeRoutines\DateTimeRoutines.cs (line 147)
144 _DefaultDate = value;
145 DefaultDateIsNow = false;
146 }
147 get => DefaultDateIsNow ? DateTime.Now : _DefaultDate;
148 }
149
150 private static DateTime _DefaultDate = DateTime.Now;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 72 hits
📄 src\Jackett.Common\Extensions\ListExtensions.cs (line 9)
6 public static class ListExtensions
7 {
8 public static List<List<T>> ChunkBy<T>(this List<T> source, int chunkSize) => source
9 .Select((x, i) => new { Index = i, Value = x }).GroupBy(x => x.Index / chunkSize)
10 .Select(x => x.Select(v => v.Value).ToList()).ToList();
11 }
12}
💬 The operands in the divisive expression x.Index / chunkSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Jackett.Common\Utils\DateTimeUtil.cs (line 42)
39 {
40 var date = dt.ToUniversalTime();
41 var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
42 var ts = ticks / TimeSpan.TicksPerSecond;
43 return ts;
44 }
45
💬 The operands in the divisive expression ticks / TimeSpan.TicksPerSecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 src\Jackett.Common\Indexers\Meta\BaseMetaIndexer.cs (line 107)
104 var unorderedResult = aggregateTask.Result.SelectMany(r => r.Releases);
105 var resultFilters = resultFilterProvider.FiltersForQuery(query);
106 var filteredResults = resultFilters.Select(async f => await f.FilterResults(unorderedResult)).SelectMany(t => t.Result);
107 var uniqueFilteredResults = filteredResults.Distinct();
108 var orderedResults = uniqueFilteredResults.OrderByDescending(r => r.Gain);
109 // Limiting the response size might be interesting for use-cases where there are
110 // tons of trackers configured in Jackett. For now just use the limit param if
💬 Type ReleaseInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Jackett.Common\Indexers\Meta\BaseMetaIndexer.cs (line 107)
104 var unorderedResult = aggregateTask.Result.SelectMany(r => r.Releases);
105 var resultFilters = resultFilterProvider.FiltersForQuery(query);
106 var filteredResults = resultFilters.Select(async f => await f.FilterResults(unorderedResult)).SelectMany(t => t.Result);
107 var uniqueFilteredResults = filteredResults.Distinct();
108 var orderedResults = uniqueFilteredResults.OrderByDescending(r => r.Gain);
109 // Limiting the response size might be interesting for use-cases where there are
110 // tons of trackers configured in Jackett. For now just use the limit param if
💬 Type ReleaseInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 4 hits
📄 src\Jackett.Common\Models\TorznabCategory.cs (line 39)
36
37 // Get Hash code should be calculated off read only properties.
38 // ID is not readonly
39 public override int GetHashCode() => ID;
40
41 public TorznabCategory CopyWithoutSubCategories() => new TorznabCategory(ID, Name);
42 }
💬 GetHashCode() refers to mutable property ID (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Jackett.Common\Models\TorznabCategory.cs (line 39)
36
37 // Get Hash code should be calculated off read only properties.
38 // ID is not readonly
39 public override int GetHashCode() => ID;
40
41 public TorznabCategory CopyWithoutSubCategories() => new TorznabCategory(ID, Name);
42 }
💬 GetHashCode() refers to mutable property ID (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 src\Jackett.Common\Services\ImdbResolver.cs (line 10)
7
8namespace Jackett.Common.Services
9{
10 public struct Movie
11 {
12 public string Title;
13 public string Year;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Movie. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Jackett.Common\Services\ImdbResolver.cs (line 10)
7
8namespace Jackett.Common.Services
9{
10 public struct Movie
11 {
12 public string Title;
13 public string Year;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Movie. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 32 hits
📄 src\DateTimeRoutines\DateTimeRoutines.cs (line 513)
510 var indexOfDate = m.Index;
511 var lengthOfDate = m.Length;
512
513 switch (m.Groups["month"].Value)
514 {
515 case "Jan":
516 case "JAN":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\DateTimeRoutines\DateTimeRoutines.cs (line 513)
510 var indexOfDate = m.Index;
511 var lengthOfDate = m.Length;
512
513 switch (m.Groups["month"].Value)
514 {
515 case "Jan":
516 case "JAN":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS032 Thread.Sleep used in async method 8 hits
📄 src\Jackett.Common\Utils\Clients\HttpWebClient2.cs (line 209)
206 // it shoudln't include service unavailable..only if we have this redirect header.
207 responseMessage.StatusCode = System.Net.HttpStatusCode.Redirect;
208 redirtime = int.Parse(value.Substring(0, end));
209 System.Threading.Thread.Sleep(redirtime * 1000);
210 }
211 }
212 }
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 src\Jackett.Common\Utils\Clients\HttpWebClient.cs (line 187)
184 // it shoudln't include service unavailable..only if we have this redirect header.
185 response.StatusCode = System.Net.HttpStatusCode.Redirect;
186 redirtime = int.Parse(value.Substring(0, end));
187 System.Threading.Thread.Sleep(redirtime * 1000);
188 }
189 }
190 }
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 8 hits
📄 src\Jackett.Common\Services\UpdateService.cs (line 281)
278 if (isWindows)
279 {
280 var zipPath = Path.Combine(tempDir, "Update.zip");
281 File.WriteAllBytes(zipPath, data.ContentBytes);
282 var fastZip = new FastZip();
283 fastZip.ExtractZip(zipPath, tempDir, null);
284 }
💬 Async overload available for File.WriteAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Jackett.Common\Services\UpdateService.cs (line 288)
285 else
286 {
287 var gzPath = Path.Combine(tempDir, "Update.tar.gz");
288 File.WriteAllBytes(gzPath, data.ContentBytes);
289 Stream inStream = File.OpenRead(gzPath);
290 Stream gzipStream = new GZipInputStream(inStream);
291
💬 Async overload available for File.WriteAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 64 hits
📄 src\Jackett.Common\Utils\Extensions.cs (line 37)
34 var continuation = anyTask.ContinueWith((_) =>
35 {
36 var completedTasks = tasks.Where(t => t.Status == TaskStatus.RanToCompletion);
37 var results = completedTasks.Select(t => t.Result);
38 return results;
39 });
40
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Jackett.Common\Indexers\Meta\BaseMetaIndexer.cs (line 80)
77 IEnumerable<Task<IndexerResult>> supportedTasks = indexers.Where(i => i.CanHandleQuery(query)).Select(i => i.ResultsForQuery(query, true)).ToList(); // explicit conversion to List to execute LINQ query
78
79 var fallbackStrategies = fallbackStrategyProvider.FallbackStrategiesForQuery(query);
80 var fallbackQueries = fallbackStrategies.Select(async f => await f.FallbackQueries()).SelectMany(t => t.Result);
81 var fallbackTasks = fallbackQueries.SelectMany(q => indexers.Where(i => !i.CanHandleQuery(query) && i.CanHandleQuery(q)).Select(i => i.ResultsForQuery(q, true)));
82 var tasks = supportedTasks.Concat(fallbackTasks).ToList(); // explicit conversion to List to execute LINQ query
83
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 8 hits
📄 src\Jackett.Common\Indexers\Definitions\Wolfmax4K.cs (line 148)
145 if (data == null)
146 return new List<ReleaseInfo>();
147
148 return data.Values().Select(item => ExtractReleaseInfo(item as JObject, query)).ToList()
149 .Where(x => x != null);
150 }
151 catch (Exception ex)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\Jackett.Common\Indexers\Definitions\Wolfmax4K.cs (line 148)
145 if (data == null)
146 return new List<ReleaseInfo>();
147
148 return data.Values().Select(item => ExtractReleaseInfo(item as JObject, query)).ToList()
149 .Where(x => x != null);
150 }
151 catch (Exception ex)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 src\Jackett.Common\JackettProtectedAttribute.cs (line 5)
2
3namespace Jackett.Common
4{
5 public class JackettProtectedAttribute : Attribute
6 {
7 }
8}
💬 JackettProtectedAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\Jackett.Common\JackettProtectedAttribute.cs (line 5)
2
3namespace Jackett.Common
4{
5 public class JackettProtectedAttribute : Attribute
6 {
7 }
8}
💬 JackettProtectedAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS047 LINQ traversal before filter 4 hits
📄 src\Jackett.Common\Models\IndexerConfig\ConfigurationData.cs (line 65)
62
63 private IEnumerable<ConfigurationItem> GetAllConfigurationItems()
64 {
65 var properties = GetType()
66 .GetProperties()
67 .Where(p => p.CanRead)
68 .Where(p => p.PropertyType.IsSubclassOf(typeof(ConfigurationItem)))
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 src\Jackett.Common\Models\IndexerConfig\ConfigurationData.cs (line 65)
62
63 private IEnumerable<ConfigurationItem> GetAllConfigurationItems()
64 {
65 var properties = GetType()
66 .GetProperties()
67 .Where(p => p.CanRead)
68 .Where(p => p.PropertyType.IsSubclassOf(typeof(ConfigurationItem)))
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS049 Comparing strings without StringComparison 16 hits
📄 src\Jackett.Common\Indexers\Definitions\BroadcasTheNet.cs (line 326)
323 DownloadVolumeFactor = 0, // ratioless
324 UploadVolumeFactor = 1,
325 MinimumRatio = 1,
326 MinimumSeedTime = btnResult.Category.ToUpperInvariant() == "SEASON" ? 432000 : 86400 // 120 hours for seasons and 24 hours for episodes
327 };
328
329 if (btnResult.SeriesBanner.IsNotNullOrWhiteSpace())
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\Jackett.Common\Indexers\Definitions\MTeamTp.cs (line 242)
239 {
240 if (jsonResponse != null &&
241 jsonResponse.Message.IsNotNullOrWhiteSpace() &&
242 jsonResponse.Message.ToUpperInvariant() != "SUCCESS")
243 {
244 throw new Exception($"Invalid response received from M-Team. Response from API: {jsonResponse.Message}");
245 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 16 hits
📄 src\Jackett.Common\Services\LogCacheService.cs (line 20)
17 {
18 get
19 {
20 lock (_Logs)
21 {
22 return _Logs.ToList();
23 }
💬 A lock was obtained on _Logs but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\Jackett.Common\Services\LogCacheService.cs (line 31)
28
29 private static void AddLog(LogEventInfo logEvent, string logMessage)
30 {
31 lock (_Logs)
32 {
33 _Logs.Insert(0, new CachedLog
34 {
💬 A lock was obtained on _Logs but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS053 Pointless collection ToString() 12 hits
📄 src\Jackett.Common\Indexers\Definitions\CardigannIndexer.cs (line 2256)
2253 }
2254 else
2255 {
2256 value = release.Category.ToString();
2257 }
2258
2259 break;
💬 .ToString() was called on a collection which results in impractical output (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS053-PointlessCollectionToString.md)
📄 src\Jackett.Common\Indexers\Definitions\CardigannIndexer.cs (line 2281)
2278 }
2279 else
2280 {
2281 value = release.Category.ToString();
2282 }
2283
2284 break;
💬 .ToString() was called on a collection which results in impractical output (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS053-PointlessCollectionToString.md)
SS057 Collection manipulated during traversal 4 hits
📄 src\Jackett.Common\Indexers\Definitions\CardigannIndexer.cs (line 1826)
1823 CurrentRow.Append(MergeRow.ChildNodes.ToArray());
1824 }
1825 }
1826 Rows.RemoveRange(i + 1, After);
1827 }
1828 }
1829
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\Jackett.Common\Indexers\Definitions\CardigannIndexer.cs (line 1826)
1823 CurrentRow.Append(MergeRow.ChildNodes.ToArray());
1824 }
1825 }
1826 Rows.RemoveRange(i + 1, After);
1827 }
1828 }
1829
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 80 hits
📄 src\Jackett.Common\Utils\ParseUtil.cs (line 93)
90 continue;
91 }
92
93 extractedLong += c;
94 }
95
96 return CoerceLong(extractedLong);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Jackett.Common\Indexers\Definitions\BroadcasTheNet.cs (line 335)
332
333 if (posterUrl.StartsWith("//"))
334 {
335 posterUrl = "https:" + posterUrl;
336 }
337
338 release.Poster = new Uri(posterUrl);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 src\Jackett.Common\Indexers\Definitions\Wolfmax4K.cs (line 547)
544
545 var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
546
547 using var msDecrypt = new MemoryStream(cipherText);
548 using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
549 using var srDecrypt = new StreamReader(csDecrypt);
550
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Jackett.Common\Indexers\Definitions\Wolfmax4K.cs (line 548)
545 var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
546
547 using var msDecrypt = new MemoryStream(cipherText);
548 using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
549 using var srDecrypt = new StreamReader(csDecrypt);
550
551 return await srDecrypt.ReadToEndAsync();
💬 CryptoStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 4 hits
📄 src\Jackett.Service\Service.cs (line 16)
13 public partial class Service : ServiceBase
14 {
15 private readonly IProcessService processService;
16 private Process consoleProcess;
17 private readonly Logger logger;
18 private bool serviceStopInitiated;
19
💬 Disposable field consoleProcess in type Service is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Jackett.Tray\Main.cs (line 27)
24 private readonly ISerializeService serializeService;
25 private readonly IConfigurationService configurationService;
26 private readonly ServerConfig serverConfig;
27 private Process consoleProcess;
28 private readonly Logger logger;
29 private bool closeApplicationInitiated;
30
💬 Disposable field consoleProcess in type Main is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

MelonLoader

528 total diagnostics across 14 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 40 hits
📄 MelonLoader.Bootstrap\Logging\MelonLogger.cs (line 77)
74 }
75
76 var latestPath = Path.Combine(LoaderConfig.Current.Loader.BaseDirectory, "MelonLoader", "Latest.log");
77 var cachedPath = Path.Combine(logsDir, $"{DateTime.Now:%y-%M-%d_%H-%m-%s}.log");
78
79 MelonDebug.Log("Opening stream to latest log");
80 try
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 MelonLoader.Bootstrap\Logging\MelonLogger.cs (line 142)
139
140 public static void Log(ColorARGB msgColor, ReadOnlySpan<char> msg, ReadOnlySpan<char> strippedMessage)
141 {
142 var time = DateTime.Now.ToString(timeFormat);
143
144 LogToFiles($"[{time}] {strippedMessage}");
145
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 112 hits
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\BZip2\BZip2Constants.cs (line 113)
110 /// <summary>
111 /// Backend constant
112 /// </summary>
113 public const int MaximumSelectors = (2 + (900000 / GroupSize));
114
115 /// <summary>
116 /// Backend constant
💬 The operands in the divisive expression 900000 / GroupSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\Compression\DeflaterConstants.cs (line 85)
82 /// <summary>
83 /// Internal compression engine constant
84 /// </summary>
85 public const int HASH_SHIFT = (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH;
86
87 /// <summary>
88 /// Internal compression engine constant
💬 The operands in the divisive expression (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 34 hits
📄 MelonLoader\InternalUtils\DependencyGraph.cs (line 91)
88 {
89 if (nameLookup.TryGetValue(dependency.Name, out Vertex dependencyVertex))
90 {
91 if (!melonVertex.dependencies.Contains(dependencyVertex))
92 melonVertex.dependencies.Add(dependencyVertex);
93 if (!dependencyVertex.dependents.Contains(melonVertex))
94 dependencyVertex.dependents.Add(melonVertex);
💬 Type Vertex is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 MelonLoader\InternalUtils\DependencyGraph.cs (line 93)
90 {
91 if (!melonVertex.dependencies.Contains(dependencyVertex))
92 melonVertex.dependencies.Add(dependencyVertex);
93 if (!dependencyVertex.dependents.Contains(melonVertex))
94 dependencyVertex.dependents.Add(melonVertex);
95 }
96 else if (!TryLoad(dependency)
💬 Type Vertex is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 28 hits
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Tar\TarEntry.cs (line 160)
157 /// <returns>A Hash code for the current <see cref="Object"/></returns>
158 public override int GetHashCode()
159 {
160 return Name.GetHashCode();
161 }
162
163 /// <summary>
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 MelonLoader\BackwardsCompatibility\Harmony\Patch.cs (line 43)
40 public MethodInfo GetMethod(MethodBase original) => patchWrapper.GetMethod(original);
41 public override bool Equals(object obj) => patchWrapper.Equals(obj);
42 public int CompareTo(object obj) => patchWrapper.CompareTo(obj);
43 public override int GetHashCode() => patchWrapper.GetHashCode();
44 }
45}
💬 GetHashCode() refers to mutable field patchWrapper (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 76 hits
📄 MelonLoader.Bootstrap\Logging\ColorARGB.cs (line 7)
4namespace MelonLoader.Logging;
5
6[StructLayout(LayoutKind.Sequential)]
7public readonly struct ColorARGB : IEquatable<ColorARGB>
8{
9 private readonly uint value;
10
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ColorARGB. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 MelonLoader.Bootstrap\RuntimeHandlers\Mono\MonoLib.cs (line 267)
264 }
265
266 [StructLayout(LayoutKind.Sequential)]
267 public unsafe struct AssemblyName
268 {
269 public nint Name;
270
💬 Implement Equals(), GetHashCode() and ToString() methods on struct AssemblyName. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 16 hits
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\FastZip.cs (line 664)
661 // (it might have been set up by the entry factory, and if so we let that take precedence)
662 if (!string.IsNullOrEmpty(Password) && entry.AESEncryptionStrength == 0)
663 {
664 switch (EntryEncryptionMethod)
665 {
666 case ZipEncryptionMethod.AES128:
667 entry.AESKeySize = 128;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\ZipOutputStream.cs (line 787)
784
785 size += count;
786
787 switch (curMethod)
788 {
789 case CompressionMethod.Deflated:
790 base.Write(buffer, offset, count);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 72 hits
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\Compression\Deflater.cs (line 481)
478
479 if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0))
480 {
481 switch (state)
482 {
483 case BUSY_STATE:
484 // We need more input now
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\BZip2\BZip2InputStream.cs (line 302)
299 }
300
301 int retChar = currentChar;
302 switch (currentState)
303 {
304 case RAND_PART_B_STATE:
305 SetupRandPartB();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 60 hits
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Tar\TarArchive.cs (line 277)
274 {
275 if (isDisposed)
276 {
277 throw new ObjectDisposedException("TarArchive");
278 }
279
280 return asciiTranslate;
💬 An exception is thrown from the getter of property AsciiTranslate (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Tar\TarArchive.cs (line 348)
345 {
346 if (isDisposed)
347 {
348 throw new ObjectDisposedException("TarArchive");
349 }
350
351 return rootPath;
💬 An exception is thrown from the getter of property RootPath (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 4 hits
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\Compression\InflaterHuffmanTree.cs (line 69)
66 }
67 catch (Exception)
68 {
69 throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal");
70 }
71 }
72
💬 An exception is thrown from InflaterHuffmanTree its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\Compression\InflaterHuffmanTree.cs (line 69)
66 }
67 catch (Exception)
68 {
69 throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal");
70 }
71 }
72
💬 An exception is thrown from InflaterHuffmanTree its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 MelonLoader\BackwardsCompatibility\Harmony\Attributes.cs (line 41)
38 }
39
40 [Obsolete("Harmony.HarmonyAttribute is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyAttribute instead. This will be removed in a future update.", true)]
41 public class HarmonyAttribute : HarmonyLib.HarmonyAttribute { }
42
43 [Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead. This will be removed in a future update.", true)]
44 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Method, AllowMultiple = true)]
💬 HarmonyAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 MelonLoader\BackwardsCompatibility\Harmony\Attributes.cs (line 41)
38 }
39
40 [Obsolete("Harmony.HarmonyAttribute is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyAttribute instead. This will be removed in a future update.", true)]
41 public class HarmonyAttribute : HarmonyLib.HarmonyAttribute { }
42
43 [Obsolete("Harmony.HarmonyPatch is Only Here for Compatibility Reasons. Please use HarmonyLib.HarmonyPatch instead. This will be removed in a future update.", true)]
44 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Method, AllowMultiple = true)]
💬 HarmonyAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS051 Locking on mutable reference 32 hits
📄 MelonLoader\Preferences\IO\Watcher.cs (line 76)
73 return;
74 }
75
76 lock (SyncLock)
77 {
78 DateTime lastWriteUtc = System.IO.File.GetLastWriteTimeUtc(PrefFile.FilePath);
79 if (lastWriteUtc > LastReadTimeUtc)
💬 A lock was obtained on SyncLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 MelonLoader\Resolver\AssemblyResolveInfo.cs (line 33)
30
31 public void SetVersionSpecific(Version version, Assembly assembly = null)
32 {
33 lock (Versions)
34 Versions[version] = assembly;
35 }
36 public Assembly GetVersionSpecific(Version version)
💬 A lock was obtained on Versions but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 8 hits
📄 MelonLoader\Melons\Events\MelonEvent.cs (line 52)
49 var act = actions[b];
50 if (a.priority < act.priority)
51 {
52 actions.Insert(b, a);
53 UpdateEnumerator();
54 return;
55 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 MelonLoader\Melons\Events\MelonEvent.cs (line 98)
95 continue;
96
97 any = true;
98 actions.RemoveAt(a);
99 if (act.melonAssembly != null)
100 MelonDebug.Msg($"MelonAssembly '{act.melonAssembly.Assembly.GetName().Name}' unsubscribed with {act.del.Method.Name}");
101 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 MelonLoader.Bootstrap\RuntimeHandlers\Il2Cpp\DotnetInstaller.cs (line 53)
50 {
51 Directory.CreateDirectory(Path.GetDirectoryName(installerPath)!);
52
53 using var str = File.Create(installerPath);
54 await resp.Content.CopyToAsync(str);
55 }
56 catch
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 MelonLoader.Bootstrap\RuntimeHandlers\Il2Cpp\DotnetInstaller.cs (line 53)
50 {
51 Directory.CreateDirectory(Path.GetDirectoryName(installerPath)!);
52
53 using var str = File.Create(installerPath);
54 await resp.Content.CopyToAsync(str);
55 }
56 catch
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 40 hits
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\ZipFile.cs (line 4392)
4389
4390 #region Instance Fields
4391
4392 private ZipFile zipFile_;
4393 private Stream baseStream_;
4394 private readonly long start_;
4395 private readonly long length_;
💬 Disposable field zipFile_ in type PartialInputStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 MelonLoader\BackwardsCompatibility\ICSharpCode\SharpZipLib\Zip\ZipFile.cs (line 4393)
4390 #region Instance Fields
4391
4392 private ZipFile zipFile_;
4393 private Stream baseStream_;
4394 private readonly long start_;
4395 private readonly long length_;
4396 private long readPos_;
💬 Disposable field baseStream_ in type PartialInputStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Ombi

520 total diagnostics across 19 rules

SS001 Async method with void return type 2 hits
📄 src\Ombi.Helpers\OmbiQuartz.cs (line 34)
31 Init();
32 }
33
34 private async void Init()
35 {
36 _scheduler = await new StdSchedulerFactory().GetScheduler();
37 }
💬 Method Init is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Ombi.Helpers\OmbiQuartz.cs (line 34)
31 Init();
32 }
33
34 private async void Init()
35 {
36 _scheduler = await new StdSchedulerFactory().GetScheduler();
37 }
💬 Method Init is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 224 hits
📄 src\Ombi.Notifications.Templates\NewsletterTemplate.cs (line 43)
40 sb.Replace(SubjectKey, subject);
41 sb.Replace(TableLocation, tableHtml);
42 sb.Replace(IntroText, intro);
43 sb.Replace(DateKey, DateTime.Now.ToString("f"));
44 sb.Replace(AppUrl, applicationUrl);
45 sb.Replace(Logo, string.IsNullOrEmpty(logo) ? OmbiLogo : logo);
46 sb.Replace(Unsubscribe, string.IsNullOrEmpty(unsubscribeLink) ? string.Empty : unsubscribeLink);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Ombi.Notifications.Templates\EmailBasicTemplate.cs (line 36)
33 var sb = new StringBuilder(File.ReadAllText(TemplateLocation));
34 sb.Replace(SubjectKey, subject);
35 sb.Replace(BodyKey, body);
36 sb.Replace(DateKey, DateTime.Now.ToString("f"));
37 sb.Replace(Poster, GetPosterContent(imgsrc, url));
38 sb.Replace(Logo, string.IsNullOrEmpty(logo) ? OmbiLogo : logo);
39
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 10 hits
📄 src\Ombi.Helpers\PaginationHelper.cs (line 13)
10 {
11 var result = new List<PagesToLoad>();
12
13 var firstPage = currentlyLoaded / maxItemsPerPage + 1;
14 var startPos = currentlyLoaded % maxItemsPerPage + 1;
15
16 var lastItemIndex = currentlyLoaded + toTake - 1;
💬 The operands in the divisive expression currentlyLoaded / maxItemsPerPage are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Ombi.Helpers\PaginationHelper.cs (line 17)
14 var startPos = currentlyLoaded % maxItemsPerPage + 1;
15
16 var lastItemIndex = currentlyLoaded + toTake - 1;
17 var lastPage = lastItemIndex / maxItemsPerPage + 1;
18 var stopPos = lastItemIndex % maxItemsPerPage + 1;
19
20 while (currentlyLoaded >= maxItemsPerPage)
💬 The operands in the divisive expression lastItemIndex / maxItemsPerPage are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 72 hits
📄 src\Ombi.Core\Engine\RecentlyAddedEngine.cs (line 221)
218 {
219 foreach (var emby in embyMovies)
220 {
221 model.Add(new RecentlyAddedMovieModel
222 {
223 Id = emby.Id,
224 ImdbId = emby.ImdbId,
💬 Type RecentlyAddedMovieModel is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Ombi.Core\Engine\RecentlyAddedEngine.cs (line 253)
250 {
251 foreach (var plex in plexMovies)
252 {
253 model.Add(new RecentlyAddedMovieModel
254 {
255 Id = plex.Id,
256 ImdbId = plex.ImdbId,
💬 Type RecentlyAddedMovieModel is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 4 hits
📄 src\Ombi.Helpers.Tests\CacheServiceTests.cs (line 343)
340
341 public override int GetHashCode()
342 {
343 return HashCode.Combine(Id, Name);
344 }
345 }
346 }
💬 GetHashCode() refers to mutable property Id (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Ombi.Helpers.Tests\CacheServiceTests.cs (line 343)
340
341 public override int GetHashCode()
342 {
343 return HashCode.Combine(Id, Name);
344 }
345 }
346 }
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS018 Switch does not handle all enum options 2 hits
📄 src\Ombi\Controllers\V2\RequestsController.cs (line 213)
210 [HttpPost("reprocess/{type}/{requestId}/{is4K}")]
211 public async Task<IActionResult> ReProcessRequest(RequestType type, int requestId, bool? is4K)
212 {
213 switch (type)
214 {
215 case RequestType.TvShow:
216 return Ok(await _tvRequestEngine.ReProcessRequest(requestId, false, HttpContext.RequestAborted));
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Ombi\Controllers\V2\RequestsController.cs (line 213)
210 [HttpPost("reprocess/{type}/{requestId}/{is4K}")]
211 public async Task<IActionResult> ReProcessRequest(RequestType type, int requestId, bool? is4K)
212 {
213 switch (type)
214 {
215 case RequestType.TvShow:
216 return Ok(await _tvRequestEngine.ReProcessRequest(requestId, false, HttpContext.RequestAborted));
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 18 hits
📄 src\Ombi.Core\Services\RequestLimitService.cs (line 155)
152 int count = 0;
153 DateTime oldestRequestedAt = DateTime.Now;
154 DateTime nextRequest = DateTime.Now;
155 switch (type)
156 {
157 case RequestLimitType.Day:
158 count = limit - await log.CountAsync(x => x.RequestDate >= now.Date);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Ombi.Core\Services\RequestLimitService.cs (line 260)
257 };
258 }
259
260 switch (user.EpisodeRequestLimitType)
261 {
262 case RequestLimitType.Day:
263
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 34 hits
📄 src\Ombi.Core.Tests\Engine\CalendarEngineTests.cs (line 20)
17 [TestFixture]
18 public class CalendarEngineTests
19 {
20 public Mock<IMovieRequestRepository> MovieRepo { get; set; }
21 public Mock<ITvRequestRepository> TvRepo { get; set; }
22 public CalendarEngine CalendarEngine { get; set; }
23
💬 Method set_MovieRepo might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 src\Ombi.Core.Tests\Engine\CalendarEngineTests.cs (line 21)
18 public class CalendarEngineTests
19 {
20 public Mock<IMovieRequestRepository> MovieRepo { get; set; }
21 public Mock<ITvRequestRepository> TvRepo { get; set; }
22 public CalendarEngine CalendarEngine { get; set; }
23
24 [SetUp]
💬 Method set_TvRepo might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS023 Exception thrown from property getter 4 hits
📄 src\Ombi.Api.External\NotificationServices\GroupMe\Models\GroupMeResponse.cs (line 36)
33 case GroupMeStatusCode.ServiceUnavailable:
34 return false;
35 default:
36 throw new ArgumentOutOfRangeException(nameof(GroupMeStatusCode));
37 }
38 }
39 }
💬 An exception is thrown from the getter of property Successful (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Ombi.Core\Models\Search\V2\CalendarViewModel.cs (line 28)
25 case RequestType.Album:
26 return "#797979";
27 default:
28 throw new ArgumentOutOfRangeException();
29 }
30 }
31 }
💬 An exception is thrown from the getter of property BorderColor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 38 hits
📄 src\Ombi.Store\Repository\BaseRepository.cs (line 50)
47
48 public async Task AddRange(IEnumerable<T> content, bool save = true)
49 {
50 _db.AddRange(content);
51 if (save)
52 {
53 await InternalSaveChanges();
💬 Async overload available for DbSet.AddRange (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Ombi.Store\Repository\EmbyContentRepository.cs (line 90)
87
88 public override async Task AddRange(IEnumerable<IMediaServerEpisode> content)
89 {
90 Db.EmbyEpisode.AddRange((IEnumerable<EmbyEpisode>)content);
91 await InternalSaveChanges();
92 }
93
💬 Async overload available for DbSet.AddRange (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS037 HttpClient instantiated directly 4 hits
📄 src\Ombi.Api.External\NotificationServices\Mattermost\Models\MattermostClient.cs (line 21)
18 public class MatterhookClient
19 {
20 private readonly Uri _webhookUrl;
21 private readonly HttpClient _httpClient = new HttpClient();
22
23 /// <summary>
24 /// Create a new Mattermost Client
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 src\Ombi\Program.cs (line 136)
133 }
134
135 await SortOutBaseUrl(baseUrl, settingsDb, ombiSettingsContent);
136 var httpClient = new HttpClient();
137 // Create minimal dependencies for migration code (no caching needed during migration)
138 var nullCache = new NullCacheService();
139 var stubEnvironment = new StubHostEnvironment();
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS040 Unused result on immutable object 2 hits
📄 src\Ombi.Api.External\ExternalApis\CouchPotato\CouchPotatoApi.cs (line 70)
67 request.AddQueryString("status",string.Join(",", status));
68 request.OnBeforeDeserialization = json =>
69 {
70 json.Replace("[]", "{}");
71 };
72 return await _api.Request<CouchPotatoMovies>(request);
73 }
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
📄 src\Ombi.Api.External\ExternalApis\CouchPotato\CouchPotatoApi.cs (line 70)
67 request.AddQueryString("status",string.Join(",", status));
68 request.OnBeforeDeserialization = json =>
69 {
70 json.Replace("[]", "{}");
71 };
72 return await _api.Request<CouchPotatoMovies>(request);
73 }
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 src\Ombi.Schedule\Jobs\Ombi\NewsletterJob.cs (line 334)
331 private HashSet<LidarrAlbumCache> GetMusicContent(IExternalRepository<LidarrAlbumCache> repository, bool test)
332 {
333
334 var lidarrContent = repository.GetAll().AsNoTracking().ToList().Where(x => x.FullyAvailable);
335
336 HashSet<LidarrAlbumCache> albumsToSend;
337 if (test)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\Ombi.Schedule\Jobs\Ombi\NewsletterJob.cs (line 334)
331 private HashSet<LidarrAlbumCache> GetMusicContent(IExternalRepository<LidarrAlbumCache> repository, bool test)
332 {
333
334 var lidarrContent = repository.GetAll().AsNoTracking().ToList().Where(x => x.FullyAvailable);
335
336 HashSet<LidarrAlbumCache> albumsToSend;
337 if (test)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 src\Ombi.Api\Attribute\JsonPluralNameAttribute.cs (line 5)
2
3namespace Ombi.Api
4{
5 public class JsonPropertyNameBasedOnItemClassAttribute : Attribute
6 {
7 }
8
💬 JsonPropertyNameBasedOnItemClassAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\Ombi.Api\Attribute\JsonPluralNameAttribute.cs (line 9)
6 {
7 }
8
9 public class JsonPluralNameAttribute : Attribute
10 {
11 public string PluralName { get; set; }
12 public JsonPluralNameAttribute(string pluralName)
💬 JsonPluralNameAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 2 hits
📄 src\Ombi\Controllers\V1\External\TesterController.cs (line 340)
337
338 private async Task<OmbiUser> GetCurrentUserAsync()
339 {
340 return await UserManager.Users.FirstOrDefaultAsync(x => x.NormalizedUserName == UserPrinciple.Identity.Name.ToUpper());
341 }
342
343 /// <summary>
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\Ombi\Controllers\V1\External\TesterController.cs (line 340)
337
338 private async Task<OmbiUser> GetCurrentUserAsync()
339 {
340 return await UserManager.Users.FirstOrDefaultAsync(x => x.NormalizedUserName == UserPrinciple.Identity.Name.ToUpper());
341 }
342
343 /// <summary>
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS057 Collection manipulated during traversal 6 hits
📄 src\Ombi.Core\Engine\Demo\DemoTvSearchEngine.cs (line 47)
44 {
45 if (!_demoLists.TvShows.Contains(searchResult[i].show?.externals?.thetvdb ?? 0))
46 {
47 searchResult.RemoveAt(i);
48 }
49 }
50
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\Ombi.Core\Engine\Demo\DemoMovieSearchEngine.cs (line 46)
43 {
44 if (!_demoLists.Movies.Contains(result[i].Id))
45 {
46 result.RemoveAt(i);
47 }
48 }
49 if(result.Count > 0)
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 6 hits
📄 src\Ombi.Api.External\NotificationServices\Mattermost\Models\MattermostClient.cs (line 103)
100 outMessages.Add(CloneMessage(inMessage));
101 }
102
103 outMessages[msgCount].Text += $"{line}\r\n";
104 }
105
106 //Length of text on the last (or first if only one) inMessage.
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Ombi.Api.External\NotificationServices\Mattermost\Models\MattermostClient.cs (line 140)
137 outMessages[msgCount].Attachments = new List<MattermostAttachment> { CloneAttachment(att) };
138 }
139
140 outMessages[msgCount].Attachments[attIndex].Text += $"{line}\r\n";
141 }
142 }
143 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 44 hits
📄 src\Ombi.Schedule\Jobs\Radarr\RadarrSync.cs (line 45)
42 {
43 _logger.LogInformation("[RadarrSync] Starting Radarr cache sync - clearing existing cache");
44 // Let's remove the old cached data
45 using var tran = await _ctx.Database.BeginTransactionAsync();
46 await _ctx.Database.ExecuteSqlRawAsync("DELETE FROM RadarrCache");
47 await tran.CommitAsync();
48 _logger.LogInformation("[RadarrSync] RadarrCache cleared");
💬 IDbContextTransaction can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Ombi.Schedule\Jobs\Couchpotato\CouchPotatoSync.cs (line 82)
79 await strat.ExecuteAsync(async () =>
80 {
81 // Let's remove the old cached data
82 using var tran = await _ctx.Database.BeginTransactionAsync();
83 await _ctx.Database.ExecuteSqlRawAsync("DELETE FROM CouchPotatoCache");
84 await tran.CommitAsync();
85 });
💬 IDbContextTransaction can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 42 hits
📄 src\Ombi.Hubs\NotificationHub.cs (line 16)
13
14public class NotificationHub : Hub
15{
16 private readonly OmbiUserManager _userManager;
17 public static readonly ConcurrentDictionary<string, NotificationHubUser> UsersOnline = new();
18
19 public NotificationHub(OmbiUserManager userManager)
💬 Disposable field _userManager in type NotificationHub is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Ombi.Schedule\Jobs\Ombi\NewsletterJob.cs (line 76)
73 private readonly IMovieDbApi _movieApi;
74 private readonly IEmailProvider _email;
75 private readonly ISettingsService<CustomizationSettings> _customizationSettings;
76 private readonly INotificationTemplatesRepository _templateRepo;
77 private readonly ISettingsService<EmailNotificationSettings> _emailSettings;
78 private readonly ISettingsService<NewsletterSettings> _newsletterSettings;
79 private readonly ISettingsService<OmbiSettings> _ombiSettings;
💬 Disposable field _templateRepo in type NewsletterJob is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

P

492 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 8 hits
📄 Src\PCompiler\CompilerCore\Backend\PObserve\Constants.cs (line 74)
71 private static readonly string rawFFIBanner = $@"
72P <-> Java Foreign Function Interface Stubs
73
74This file was auto-generated on {DateTime.Now.ToLongDateString()} at {DateTime.Now.ToLongTimeString()}.
75
76Please separate each generated class into its own .java file (detailed throughout the file), filling
77in the body of each function definition as necessary for your project's business logic.
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Src\PCompiler\CompilerCore\Backend\PObserve\Constants.cs (line 74)
71 private static readonly string rawFFIBanner = $@"
72P <-> Java Foreign Function Interface Stubs
73
74This file was auto-generated on {DateTime.Now.ToLongDateString()} at {DateTime.Now.ToLongTimeString()}.
75
76Please separate each generated class into its own .java file (detailed throughout the file), filling
77in the body of each function definition as necessary for your project's business logic.
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 18 hits
📄 Src\PChecker\CheckerCore\SystematicTesting\Strategies\Feedback\Coverage\BehavioralObserver.cs (line 52)
49 }
50 scoreSum += score;
51 }
52 return scoreSum/AllTimeline.Count;
53 }
54
55 public static void PrintTimeline(List<(VectorTime, Event, EventType)> timeline)
💬 The operands in the divisive expression scoreSum/AllTimeline.Count are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Src\PChecker\CheckerCore\SystematicTesting\Strategies\Feedback\Generator\Utils.cs (line 15)
12 public static RandomChoices<T> MutateRandomChoices<T> (RandomChoices<T> randomChoices, int meanMutationCount, int meanMutationSize, System.Random random)
13 where T: IConvertible
14 {
15 meanMutationCount = Math.Max(Math.Min(randomChoices.Data.Count / 3, meanMutationCount), 1);
16 meanMutationSize = Math.Max(Math.Min(randomChoices.Data.Count / 3, meanMutationSize), 1);
17 RandomChoices<T> newChoices = new RandomChoices<T>(randomChoices);
18 int mutations = SampleGeometric(1.0f / meanMutationCount, random.NextDouble());
💬 The operands in the divisive expression randomChoices.Data.Count / 3 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 248 hits
📄 Src\PChecker\CheckerCore\SystematicTesting\Operations\TaskOperation.cs (line 85)
82 internal void OnWaitTask(SystemTasks.Task task)
83 {
84 Debug.WriteLine("<ScheduleDebug> Operation '{0}' is waiting for task '{1}'.", Id, task.Id);
85 JoinDependencies.Add(task);
86 Status = AsyncOperationStatus.BlockedOnWaitAll;
87 Scheduler.ScheduleNextEnabledOperation(AsyncOperationType.Join);
88 IsAwaiterControlled = false;
💬 Type Task is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Src\PChecker\CheckerCore\SystematicTesting\Operations\TaskOperation.cs (line 101)
98 if (!task.IsCompleted)
99 {
100 Debug.WriteLine("<ScheduleDebug> Operation '{0}' is waiting for task '{1}'.", Id, task.Id);
101 JoinDependencies.Add(task.UncontrolledTask);
102 }
103 }
104
💬 Type Task is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 12 hits
📄 Src\PChecker\CheckerCore\Runtime\Values\PMachineValue.cs (line 14)
11 }
12 }
13
14 public class PMachineValue : IPValue
15 {
16 public PMachineValue(StateMachineId machine, List<string> permissions)
17 {
💬 Equals() and GetHashcode() must be implemented together on PMachineValue (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 Src\PChecker\CheckerCore\Runtime\Values\PSeq.cs (line 9)
6
7namespace PChecker.Runtime.Values
8{
9 public sealed class PSeq : IPMutableValue, IReadOnlyList<IPValue>
10 {
11 private readonly List<IPValue> values = new List<IPValue>();
12
💬 Equals() and GetHashcode() must be implemented together on PSeq (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 38 hits
📄 Src\PChecker\CheckerCore\Runtime\VectorTime.cs (line 115)
112 public override int GetHashCode()
113 {
114 int hash = 17;
115 foreach (var entry in Clock)
116 {
117 hash = hash * 31 + entry.Key.GetHashCode();
118 hash = hash * 31 + entry.Value.GetHashCode();
💬 GetHashCode() refers to mutable property Clock (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Src\PChecker\CheckerCore\SystematicTesting\Traces\ScheduleStep.cs (line 125)
122 /// <summary>
123 /// Returns the hash code for this instance.
124 /// </summary>
125 public override int GetHashCode() => Index.GetHashCode();
126 }
127}
💬 GetHashCode() refers to mutable field Index (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 26 hits
📄 Src\PChecker\CheckerCore\Tasks\AsyncTaskMethodBuilder.cs (line 22)
19 /// <remarks>This type is intended for compiler use rather than use directly in code.</remarks>
20 [EditorBrowsable(EditorBrowsableState.Never)]
21 [StructLayout(LayoutKind.Auto)]
22 public struct AsyncTaskMethodBuilder
23 {
24 /// <summary>
25 /// Responsible for controlling the execution of tasks during systematic testing.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct AsyncTaskMethodBuilder. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Src\PChecker\CheckerCore\Tasks\AsyncTaskMethodBuilder.cs (line 171)
168 /// <remarks>This type is intended for compiler use rather than use directly in code.</remarks>
169 [EditorBrowsable(EditorBrowsableState.Never)]
170 [StructLayout(LayoutKind.Auto)]
171 public struct AsyncTaskMethodBuilder<TResult>
172 {
173 /// <summary>
174 /// Responsible for controlling the execution of tasks during systematic testing.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct AsyncTaskMethodBuilder. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 50 hits
📄 Src\PChecker\CheckerCore\Runtime\Logging\JsonWriter.cs (line 252)
249 // Always update the local machine count by one on any event.
250 _contextVcMap[machine][machine] += 1;
251
252 switch (logType)
253 {
254 // On send event, hash the string containing information about the target machine to be sent to, the event name, and payload
255 // This is used as an unique id necessary to correctly update the vector clock for the right machine-event-payload combo that
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Src\PCompiler\CompilerCore\Backend\Stately\StatelyCodeGenerator.cs (line 38)
35 private void WriteDecl(CompilationContext context, StringWriter output, IPDecl decl)
36 {
37 //string declName;
38 switch (decl)
39 {
40 case Machine machine:
41 if (!machine.IsSpec)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 6 hits
📄 Src\PChecker\CheckerCore\Tasks\TaskCompletionSource.cs (line 105)
102 }
103 else if (Status is TaskStatus.Faulted)
104 {
105 throw Exception;
106 }
107
108 return Result;
💬 An exception is thrown from the getter of property Task (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Src\PCompiler\CompilerCore\Backend\PObserve\TypeManager.cs (line 36)
33 {
34 if (_unboxedType == null)
35 {
36 throw new Exception($"TypeName not implemented for {GetType()}");
37 }
38
39 return _unboxedType;
💬 An exception is thrown from the getter of property TypeName (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 10 hits
📄 Src\PChecker\CheckerCore\ExhaustiveEngine.cs (line 148)
145 switch (proc.ExitCode)
146 {
147 case 0:
148 _logger.WriteLine("... Checker run finished.");
149 break;
150 case 2:
151 _logger.WriteLine("... Checker found a bug.");
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Src\PChecker\CheckerCore\ExhaustiveEngine.cs (line 151)
148 _logger.WriteLine("... Checker run finished.");
149 break;
150 case 2:
151 _logger.WriteLine("... Checker found a bug.");
152 break;
153 case 3:
154 _logger.WriteLine("... Checker timed out.");
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 6 hits
📄 Src\PChecker\CheckerCore\Tasks\Task.cs (line 697)
694 {
695 if (TaskController is null)
696 {
697 return UncontrolledTask.Result;
698 }
699
700 return TaskController.WaitTaskCompletes(this);
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Src\PChecker\CheckerCore\SystematicTesting\TaskController.cs (line 258)
255 {
256 var resultTask = funcWithGenericTaskResult();
257 OnWaitTask(operationId, resultTask);
258 return resultTask.Result;
259 }
260 else if (work is Func<TResult> funcWithGenericResult)
261 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 Src\PCompiler\CompilerCore\TypeChecker\ParamAssignment.cs (line 156)
153 public static void IterateAssignments(SafetyTest safety, List<Variable> globalParams,
154 Action<Dictionary<Variable, IPExpr>> generateTestCode)
155 {
156 var indexArr = safety.ParamExprMap.ToList()
157 .Zip(Enumerable.Repeat(0, safety.ParamExprMap.Count), (x, y) => (x.Key, y)).ToArray();
158 var universe = safety.ParamExprMap.ToDictionary(kv => kv.Key, kv => kv.Value.Count);
159 var assignmentIndices = new List<Dictionary<string, int>>();
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 Src\PCompiler\CompilerCore\TypeChecker\ParamAssignment.cs (line 156)
153 public static void IterateAssignments(SafetyTest safety, List<Variable> globalParams,
154 Action<Dictionary<Variable, IPExpr>> generateTestCode)
155 {
156 var indexArr = safety.ParamExprMap.ToList()
157 .Zip(Enumerable.Repeat(0, safety.ParamExprMap.Count), (x, y) => (x.Key, y)).ToArray();
158 var universe = safety.ParamExprMap.ToDictionary(kv => kv.Key, kv => kv.Value.Count);
159 var assignmentIndices = new List<Dictionary<string, int>>();
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS053 Pointless collection ToString() 2 hits
📄 Tst\UnitTests\Core\TestCaseFactory.cs (line 95)
92 : new CompileSuccessValidator();
93
94 var tempDirName =
95 Directory.CreateDirectory(Path.Combine(testTempBaseDir.FullName, output.ToString(), testName));
96 return new CompilerTestCase(tempDirName, runner, validator);
97 }
98 }
💬 .ToString() was called on a collection which results in impractical output (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS053-PointlessCollectionToString.md)
📄 Tst\UnitTests\Core\TestCaseFactory.cs (line 95)
92 : new CompileSuccessValidator();
93
94 var tempDirName =
95 Directory.CreateDirectory(Path.Combine(testTempBaseDir.FullName, output.ToString(), testName));
96 return new CompilerTestCase(tempDirName, runner, validator);
97 }
98 }
💬 .ToString() was called on a collection which results in impractical output (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS053-PointlessCollectionToString.md)
SS057 Collection manipulated during traversal 6 hits
📄 Src\PCompiler\CompilerCore\Backend\PEx\TransformASTPass.cs (line 462)
459 replacement.Scope = entry.Value.Scope;
460 foreach (var local in entry.Value.LocalVariables) replacement.AddLocalVariable(local);
461 foreach (var i in entry.Value.CreatesInterfaces) replacement.AddCreatesInterface(i);
462 foreach (var param in entry.Value.Signature.Parameters) replacement.Signature.Parameters.Add(param);
463 replacement.Signature.ReturnType = entry.Value.Signature.ReturnType;
464 foreach (var callee in entry.Value.Callees) replacement.AddCallee(callee);
465 replacement.Body = (CompoundStmt)ReplaceVars(entry.Value.Body, varMap);
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 Src\PCompiler\CompilerCore\Backend\PEx\TransformASTPass.cs (line 580)
577 transformedFunction.CanRaiseEvent = function.CanRaiseEvent;
578 transformedFunction.CanChangeState = function.CanChangeState;
579 transformedFunction.IsNondeterministic = function.IsNondeterministic;
580 foreach (var param in function.Signature.Parameters) transformedFunction.Signature.Parameters.Add(param);
581 transformedFunction.Signature.ReturnType = function.Signature.ReturnType;
582 return transformedFunction;
583 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 58 hits
📄 Src\PChecker\CheckerCore\Runtime\Values\PTuple.cs (line 221)
218 var retStr = "<";
219 for (var i = 0; i < fieldValues.Count; i++)
220 {
221 retStr += fieldNames[i] + ":" + fieldValues[i] + ", ";
222 }
223
224 retStr += ">";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Src\PChecker\CheckerCore\Runtime\Values\PTuple.cs (line 234)
231 for (var i = 0; i < fieldValues.Count; i++)
232 {
233 var v = fieldValues[i] == null ? "null" : fieldValues[i].ToEscapedString();
234 retStr += fieldNames[i] + ":" + v + ", ";
235 }
236
237 retStr += ">";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 2 hits
📄 Src\PChecker\CheckerCore\SystematicTesting\OperationScheduler.cs (line 286)
283 /// <returns>True if the operation was successfully registered, else false if it already exists.</returns>
284 internal bool RegisterOperation(AsyncOperation op)
285 {
286 if (OperationMap.Count == 0)
287 {
288 ScheduledOperation = op;
289 }
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 Src\PChecker\CheckerCore\SystematicTesting\OperationScheduler.cs (line 286)
283 /// <returns>True if the operation was successfully registered, else false if it already exists.</returns>
284 internal bool RegisterOperation(AsyncOperation op)
285 {
286 if (OperationMap.Count == 0)
287 {
288 ScheduledOperation = op;
289 }
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)

puppeteer-sharp

484 total diagnostics across 8 rules

SS003 Integer divided by integer causing implicit rounding 20 hits
📄 lib\PuppeteerSharp\PredefinedNetworkConditions.cs (line 17)
14 [NetworkConditions.Slow3G] = new NetworkConditions
15 {
16 // ~500Kbps down
17 Download = ((500 * 1000) / 8) * 0.8,
18
19 // ~500Kbps up
20 Upload = ((500 * 1000) / 8) * 0.8,
💬 The operands in the divisive expression (500 * 1000) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 lib\PuppeteerSharp\PredefinedNetworkConditions.cs (line 20)
17 Download = ((500 * 1000) / 8) * 0.8,
18
19 // ~500Kbps up
20 Upload = ((500 * 1000) / 8) * 0.8,
21
22 // 400ms RTT
23 Latency = 400 * 5,
💬 The operands in the divisive expression (500 * 1000) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 8 hits
📄 lib\PuppeteerSharp\Cdp\FrameManager.cs (line 142)
139
140 internal async Task AddExposedFunctionBindingAsync(Binding binding)
141 {
142 _bindings.Add(binding);
143 await Task.WhenAll(
144 GetFrames().Select(frame => ((CdpFrame)frame).AddExposedFunctionBindingAsync(binding))).ConfigureAwait(false);
145 }
💬 Type Binding is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 lib\PuppeteerSharp\PageAccessibility\Accessibility.cs (line 153)
150 children.AddRange(SerializeTree(child, whitelistedNodes));
151 }
152
153 if (whitelistedNodes?.Contains(node) == false)
154 {
155 return children.ToArray();
156 }
💬 Type AXNode is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 172 hits
📄 lib\PuppeteerSharp\BoundingBox.cs (line 83)
80
81 /// <inheritdoc/>
82 public override int GetHashCode()
83 => X.GetHashCode() * 397
84 ^ Y.GetHashCode() * 397
85 ^ Width.GetHashCode() * 397
86 ^ Height.GetHashCode() * 397;
💬 GetHashCode() refers to mutable property X (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 lib\PuppeteerSharp\BoundingBox.cs (line 84)
81 /// <inheritdoc/>
82 public override int GetHashCode()
83 => X.GetHashCode() * 397
84 ^ Y.GetHashCode() * 397
85 ^ Width.GetHashCode() * 397
86 ^ Height.GetHashCode() * 397;
87
💬 GetHashCode() refers to mutable property Y (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS023 Exception thrown from property getter 4 hits
📄 lib\PuppeteerSharp\QueryHandlers\QueryHandler.cs (line 51)
48
49 if (string.IsNullOrEmpty(QuerySelectorAll))
50 {
51 throw new PuppeteerException("Cannot create default query selector");
52 }
53
54 const string querySelector = @"async (node, selector, PuppeteerUtil) => {
💬 An exception is thrown from the getter of property QuerySelector (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 lib\PuppeteerSharp\QueryHandlers\QueryHandler.cs (line 51)
48
49 if (string.IsNullOrEmpty(QuerySelectorAll))
50 {
51 throw new PuppeteerException("Cannot create default query selector");
52 }
53
54 const string querySelector = @"async (node, selector, PuppeteerUtil) => {
💬 An exception is thrown from the getter of property QuerySelector (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS034 Accessing Task.Result without await 52 hits
📄 lib\PuppeteerSharp\Cdp\CdpFrame.cs (line 163)
160 await completedTask.ConfigureAwait(false);
161
162 return completedTask == navigationResponseTask
163 ? navigationResponseTask.Result
164 : null;
165 }
166
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 lib\PuppeteerSharp\Cdp\CdpPageTarget.cs (line 54)
51 _ = InitializedTaskWrapper.Task.ContinueWith(
52 async initializedTask =>
53 {
54 var success = initializedTask.Result;
55 if (success != InitializationStatus.Success)
56 {
57 return;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS057 Collection manipulated during traversal 20 hits
📄 lib\PuppeteerSharp\Bidi\ExposableFunction.cs (line 156)
153 var contexts = new List<BrowsingContext> { _frame.BrowsingContext };
154 for (var i = 0; i < contexts.Count; i++)
155 {
156 contexts.AddRange(contexts[i].Children);
157 }
158
159 // Add preload script only to the top-level context (for future navigations).
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 lib\PuppeteerSharp\Bidi\ExposableFunction.cs (line 435)
432 return frame;
433 }
434
435 frames.AddRange(frame.ChildFrames.OfType<BidiFrame>());
436 }
437
438 return null;
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 8 hits
📄 lib\PuppeteerSharp\ExecutionContext.cs (line 172)
169 {
170 var location = $"{callframe.Url}:{callframe.LineNumber}:{callframe.ColumnNumber}";
171 var functionName = string.IsNullOrEmpty(callframe.FunctionName) ? "<anonymous>" : callframe.FunctionName;
172 message += $"\n at ${functionName} (${location})";
173 }
174 }
175
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 lib\PuppeteerSharp\Cdp\CdpPage.cs (line 1337)
1334 {
1335 var location = $"{callFrame.Url}:{callFrame.LineNumber}:{callFrame.ColumnNumber}";
1336 var functionName = callFrame.FunctionName ?? "<anonymous>";
1337 message += $"\n at {functionName} ({location})";
1338 }
1339
1340 return message;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 200 hits
📄 lib\PuppeteerSharp\Bidi\BidiPage.cs (line 86)
83 }
84
85 /// <inheritdoc />
86 public override IBrowserContext BrowserContext { get; }
87
88 /// <inheritdoc />
89 public override CDPSession Client { get; }
💬 Disposable field BrowserContext in type BidiPage is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 lib\PuppeteerSharp\Bidi\BidiPage.cs (line 137)
134 internal TaskQueue RequestInterceptionQueue => _requestInterceptionQueue;
135
136 /// <inheritdoc />
137 protected override Browser Browser { get; }
138
139 private Task ClosedTask
140 {
💬 Disposable field Browser in type BidiPage is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Inveigh

472 total diagnostics across 7 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 78 hits
📄 Inveigh\Protocols\Quiddity\Quiddity\Listeners\HTTPListener.cs (line 125)
122 TcpClient tcpClient = tcpListener.EndAcceptTcpClient(tcpAsync);
123 string sourceIP = ((IPEndPoint)(tcpClient.Client.RemoteEndPoint)).Address.ToString();
124
125 if (type.Equals("Proxy") && tcpSessionTable.ContainsKey(sourceIP) && DateTime.Compare((DateTime)tcpSessionTable[sourceIP], DateTime.Now) > 0)
126 {
127 tcpClient.Client.Close();
128 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Inveigh\Support\Control.cs (line 123)
120 {
121 Program.consoleList.Clear();
122 Program.enabledConsoleOutput = true;
123 Output.Queue(String.Format("[+] Inveigh exited at {0}", DateTime.Now.ToString("s")));
124 Output.ProcessOutput();
125 Output.ProcessFileOutput();
126 Sniffer.isRunning = false;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 6 hits
📄 Inveigh\Support\Output.cs (line 141)
138 public static void OutputCommand(string description, string[] headings, IList<string> list, ConsoleColor color)
139 {
140 Console.ForegroundColor = color;
141 int padLeft = (Console.WindowWidth - description.Length) / 2;
142 int padRight = padLeft;
143 int pad = Console.WindowWidth - description.Length - padLeft - padRight;
144 padRight += pad;
💬 The operands in the divisive expression (Console.WindowWidth - description.Length) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Inveigh\Support\Output.cs (line 141)
138 public static void OutputCommand(string description, string[] headings, IList<string> list, ConsoleColor color)
139 {
140 Console.ForegroundColor = color;
141 int padLeft = (Console.WindowWidth - description.Length) / 2;
142 int padRight = padLeft;
143 int pad = Console.WindowWidth - description.Length - padLeft - padRight;
144 padRight += pad;
💬 The operands in the divisive expression (Console.WindowWidth - description.Length) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS015 String placeholders in wrong order 4 hits
📄 Inveigh\Listeners\HTTPListener.cs (line 33)
30
31 protected override void OutputRequestMethod(string protocol, string listenerPort, string clientIP, string clientPort, string uri, string method)
32 {
33 Output.Queue(String.Format("[.] [{0}] {1}({2}) {3} request from {5}:{6} for {4}", Output.Timestamp(), protocol, listenerPort, method, uri, clientIP, clientPort));
34 }
35
36 protected override void OutputNTLM(string protocol, string listenerPort, string clientIP, string clientPort, string user, string domain, string host, string ntlmChallenge, string ntlmResponseHash, string lmResponseHash)
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 Inveigh\Listeners\HTTPListener.cs (line 33)
30
31 protected override void OutputRequestMethod(string protocol, string listenerPort, string clientIP, string clientPort, string uri, string method)
32 {
33 Output.Queue(String.Format("[.] [{0}] {1}({2}) {3} request from {5}:{6} for {4}", Output.Timestamp(), protocol, listenerPort, method, uri, clientIP, clientPort));
34 }
35
36 protected override void OutputNTLM(string protocol, string listenerPort, string clientIP, string clientPort, string user, string domain, string host, string ntlmChallenge, string ntlmResponseHash, string lmResponseHash)
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS019 Switch is missing default label 120 hits
📄 Inveigh\Protocols\Quiddity\Quiddity\Listeners\DHCPv6Listener.cs (line 128)
125 byte msgType = 0;
126 string leaseIP = "";
127
128 switch (packet.Message.MsgType)
129 {
130 case 1:
131 msgType = 2;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Inveigh\Protocols\Quiddity\Quiddity\Protocols\LDAP\LDAPMessage.cs (line 60)
57 public byte[] Encode(int type)
58 {
59
60 switch (type)
61 {
62
63 case 3:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS049 Comparing strings without StringComparison 78 hits
📄 Inveigh\Protocols\Quiddity\Quiddity\Protocols\MDNS\MDNSChecker.cs (line 75)
72 public bool QuestionIsAllowed(string question)
73 {
74
75 if (!Utilities.ArrayIsNullOrEmpty(this.Questions) && !Array.Exists(this.Questions, element => element == question.ToUpper()))
76 {
77 return false;
78 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Inveigh\Protocols\Quiddity\Quiddity\Protocols\DNS\DNSChecker.cs (line 187)
184 service = "GC";
185 }
186
187 if (!Utilities.ArrayIsNullOrEmpty(this.Services) && (!Array.Exists(this.Services, element => element == service.ToUpper())))
188 {
189 return false;
190 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 144 hits
📄 Inveigh\Support\Output.cs (line 57)
54 public static void Queue(string Output)
55 {
56
57 lock (Program.outputList)
58 {
59 Program.outputList.Add(Output);
60 }
💬 A lock was obtained on outputList but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Inveigh\Support\Output.cs (line 567)
564 if (Program.enabledFileOutput && (!Program.enabledFileUnique || !isUnique))
565 {
566
567 lock (Program.ntlmv2FileList)
568 {
569 Program.ntlmv2FileList.Add(challengeResponse);
570 }
💬 A lock was obtained on ntlmv2FileList but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 42 hits
📄 Inveigh\Protocols\Quiddity\Quiddity\Protocols\DNS\DNSQuestion.cs (line 120)
117 int hostnameSegmentLength = hostnameLength;
118 byte[] hostnameSegment = new byte[hostnameSegmentLength];
119 Buffer.BlockCopy(this.QName, (index + 1), hostnameSegment, 0, hostnameSegmentLength);
120 hostname += Encoding.UTF8.GetString(hostnameSegment);
121 index += hostnameLength + 1;
122 hostnameLength = this.QName[index];
123 i++;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Inveigh\Protocols\Quiddity\Quiddity\Protocols\DNS\DNSQuestion.cs (line 127)
124
125 if (hostnameLength > 0)
126 {
127 hostname += ".";
128 }
129
130 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

OpenUtau

470 total diagnostics across 17 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 6 hits
📄 OpenUtau.Core\Classic\VoicebankFiles.cs (line 101)
98 }
99
100 public void ReleaseSourceTemp() {
101 var expire = DateTime.Now - TimeSpan.FromDays(7);
102 string path = PathManager.Inst.CachePath;
103 Log.Information($"ReleaseSourceTemp {path}");
104 Directory.EnumerateFiles(path, "*.*", SearchOption.TopDirectoryOnly)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 OpenUtau.Core\Util\TimeAxis.cs (line 44)
41 public long Timestamp { get; private set; }
42
43 public void BuildSegments(UProject project) {
44 Timestamp = DateTime.Now.ToFileTimeUtc();
45 timeSigSegments.Clear();
46 for (var i = 0; i < project.timeSignatures.Count; ++i) {
47 var timesig = project.timeSignatures[i];
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 192 hits
📄 OpenUtau.Core\VocalShaper\VSVocoder.cs (line 41)
38 public VSVocoder(int fs, double frameMs, double noiseTimeSec = 5)
39 {
40 samplesPerSec = fs;
41 halfSameplesPerSec = samplesPerSec / 2;
42 hopSize = (int)(frameMs / 1000 * samplesPerSec);
43 frameSize = 2 * hopSize;
44 halfWinLen = VSMath.Min2N(hopSize);
💬 The operands in the divisive expression samplesPerSec / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 OpenUtau.Core\Audio\MiniAudioOutput.cs (line 139)
136 eof = true;
137 }
138 Marshal.Copy(temp, 0, (IntPtr)buffer, samples);
139 currentTimeMs += n / channels * 1000.0 / sampleRate;
140 }
141
142 public long GetPosition() {
💬 The operands in the divisive expression n / channels are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 20 hits
📄 OpenUtau.Core\Api\PhonemizerRunner.cs (line 58)
55 toRun.Add(request);
56 }
57 foreach (var request in toRun) {
58 parts.Add(request.part);
59 }
60 for (int i = toRun.Count - 1; i >= 0; i--) {
61 if (parts.Remove(toRun[i].part)) {
💬 Type UVoicePart is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 OpenUtau.Core\Api\PhonemizerRunner.cs (line 76)
73
74 void SendResponse(PhonemizerResponse response) {
75 Task.Factory.StartNew(_ => {
76 if (DocManager.Inst.Project.parts.Contains(response.part)) {
77 response.part.SetPhonemizerResponse(response);
78 }
79 DocManager.Inst.Project.Validate(new ValidateOptions {
💬 Type UPart is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 2 hits
📄 OpenUtau.Core\Ustx\USinger.cs (line 215)
212
213 }
214
215 public class USinger : INotifyPropertyChanged, IEquatable<USinger> {
216 protected static readonly List<UOto> emptyOtos = new List<UOto>();
217
218 public virtual string Id { get; }
💬 Equals() and GetHashcode() must be implemented together on USinger (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 OpenUtau.Core\Ustx\USinger.cs (line 215)
212
213 }
214
215 public class USinger : INotifyPropertyChanged, IEquatable<USinger> {
216 protected static readonly List<UOto> emptyOtos = new List<UOto>();
217
218 public virtual string Id { get; }
💬 Equals() and GetHashcode() must be implemented together on USinger (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS013 Rethrow exception without losing stacktrace 4 hits
📄 OpenUtau.Core\Classic\WorldlineResampler.cs (line 34)
31 $"<translate:errors.failed.synth.cutoffbeforeoffset>\n{item.phone.phoneme}",
32 e);
33 }
34 throw e;
35 }
36 }
37
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 OpenUtau.Core\Classic\WorldlineRenderer.cs (line 109)
106 $"<translate:errors.failed.synth.cutoffbeforeoffset>\n{item.phone.phoneme}",
107 e);
108 }
109 throw e;
110 }
111 }
112 int frames = (int)Math.Ceiling(result.estimatedLengthMs / frameMs);
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 88 hits
📄 OpenUtau.Core\Api\G2pDictionaryData.cs (line 6)
3 /// Data class used to deserialize yaml dictionary.
4 /// </summary>
5 public class G2pDictionaryData {
6 public struct SymbolData {
7 public string symbol;
8 public string type;
9 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SymbolData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 OpenUtau.Core\Api\G2pDictionaryData.cs (line 11)
8 public string type;
9 }
10
11 public struct Entry {
12 public string grapheme;
13 public string[] phonemes;
14 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Entry. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 OpenUtau.Core\Classic\UstNote.cs (line 112)
109 var pby = new List<string>();
110 var pbm = new List<string>();
111 for (var i = 0; i < points.Count; ++i) {
112 switch (points[i].shape) {
113 case PitchPointShape.o:
114 pbm.Add("r");
115 break;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 OpenUtau.Core\Classic\UstNote.cs (line 112)
109 var pby = new List<string>();
110 var pbm = new List<string>();
111 for (var i = 0; i < points.Count; ++i) {
112 switch (points[i].shape) {
113 case PitchPointShape.o:
114 pbm.Add("r");
115 break;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 14 hits
📄 OpenUtau.Core\Classic\Presamp.cs (line 92)
89 if (TryGetLinesFromIniBrocks(blocks, "[ALIAS]", out List<IniLine> alias)) {
90 foreach (IniLine line in alias) {
91 var parts = line.line.Split('=');
92 switch (parts[0]) {
93 case "VCV":
94 AliasRules.VCV = parts[1];
95 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 OpenUtau.Core\Voicevox\VoicevoxRenderer.cs (line 280)
277 int correction = 0;
278 var flag = phrase.phones[i].flags.FirstOrDefault(f => f.Item3.Equals(DUCM));
279 if (flag != null) {
280 switch (flag.Item1) {
281 case VoicevoxUtils.ON:
282 correction = 1;
283 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 12 hits
📄 OpenUtau.Core\Voicevox\VoicevoxClient.cs (line 22)
19 Log.Information($"VoicevoxProcess sending {request}");
20 var response = client.SendAsync(request);
21 Log.Information($"VoicevoxProcess received");
22 string str = response.Result.Content.ReadAsStringAsync().Result;
23 //May not fit json format
24 if (!str.StartsWith("{") || !str.EndsWith("}")) {
25 str = "{ \"json\":" + str + "}";
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 OpenUtau.Core\Voicevox\VoicevoxClient.cs (line 22)
19 Log.Information($"VoicevoxProcess sending {request}");
20 var response = client.SendAsync(request);
21 Log.Information($"VoicevoxProcess received");
22 string str = response.Result.Content.ReadAsStringAsync().Result;
23 //May not fit json format
24 if (!str.StartsWith("{") || !str.EndsWith("}")) {
25 str = "{ \"json\":" + str + "}";
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS040 Unused result on immutable object 4 hits
📄 OpenUtau.Core\Classic\PluginLoader.cs (line 30)
27 if (s.Length != 2) {
28 s = line.Split(new char[] { ':' });
29 }
30 Array.ForEach(s, temp => temp.Trim());
31 if (s.Length == 2) {
32 s[0] = s[0].ToLowerInvariant();
33 if (s[0] == "name") {
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
📄 OpenUtau.Core\Classic\VoicebankLoader.cs (line 134)
131 if (s.Length < 2) {
132 s = line.Split(':', 2);
133 }
134 Array.ForEach(s, temp => temp.Trim());
135 if (s.Length == 2) {
136 s[0] = s[0].ToLowerInvariant();
137 if (s[0] == "name") {
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
SS048 Locking on discouraged object (string, Type, this) 8 hits
📄 OpenUtau.Core\Ustx\UPart.cs (line 249)
246 }
247
248 internal void SetPhonemizerResponse(PhonemizerResponse response) {
249 lock (this) {
250 phonemizerResponse = response;
251 }
252 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 OpenUtau.Core\Ustx\UPart.cs (line 147)
144 notesTimestamp = request.timestamp;
145 DocManager.Inst.PhonemizerRunner?.Push(request);
146 }
147 lock (this) {
148 if (phonemizerResponse != null) {
149 var resp = phonemizerResponse;
150 if (resp.timestamp == notesTimestamp) {
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 14 hits
📄 OpenUtau.Core\Classic\Ust.cs (line 122)
119 ParseNote(project, note, lastNotePos, lastNoteEnd, block.lines, out var noteTempo);
120 lastNotePos = note.position;
121 lastNoteEnd = note.End;
122 if (note.lyric.ToLowerInvariant() != "r") {
123 part.notes.Add(note);
124 }
125 if (noteTempo != null) {
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 OpenUtau.Core\Classic\Ust.cs (line 327)
324 int end = ustNote.position + ustNote.duration + part.position;
325 var tempo = project.tempos[tempoIndex];
326 if (pos <= tempo.position && tempo.position < end) {
327 if (pos == tempo.position || ustNote.lyric.ToLowerInvariant() != "r") {
328 // Does not break up the note even if the tempo change is in the middle.
329 ustNote.tempo = tempo.bpm;
330 tempoIndex++;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 50 hits
📄 OpenUtau.Core\Classic\ExeWavtool.cs (line 49)
46 }
47 PrepareHelper();
48 string batPath = Path.Combine(PathManager.Inst.CachePath, "temp.bat");
49 lock (tempBatLock) {
50 using (var stream = File.Open(batPath, FileMode.Create)) {
51 UTF8Encoding noBomEncoding = new UTF8Encoding(false);
52 using (var writer = new StreamWriter(stream, OS.IsWindows() ? osEncoding : noBomEncoding)) {
💬 A lock was obtained on tempBatLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 OpenUtau.Core\Classic\ToolsManager.cs (line 22)
19
20 public List<IResampler> Resamplers {
21 get {
22 lock (_locker) {
23 return resamplers.ToList();
24 }
25 }
💬 A lock was obtained on _locker but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 8 hits
📄 OpenUtau.Core\Classic\Ust.cs (line 338)
335 inserted.position = tempo.position - part.position;
336 inserted.duration = end - tempo.position;
337 inserted.tempo = tempo.bpm;
338 ustNotes.Insert(i + 1, inserted);
339 tempoIndex++;
340 }
341 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 OpenUtau.Core\PlaybackManager.cs (line 154)
151 lock (_lockObj) {
152 // Move to inactive frequencies list
153 inactiveFrequencies.Add(tone.Value);
154 activeFrequencies.Remove(tone.Key);
155 }
156 }
157
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 14 hits
📄 OpenUtau.Core\Classic\PluginLoader.cs (line 38)
35 var match = reg.Match(s[1]);
36 if (match.Success) {
37 plugin.Shortcut = match.Groups[2].Value;
38 plugin.Name = match.Groups[1].Value + " (" + plugin.Shortcut + ")";
39 } else {
40 plugin.Name = s[1];
41 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 OpenUtau.Core\Editing\LyricBatchEdits.cs (line 116)
113
114 for (int i = 0; i < colors[clrIndex].Length && i < value.Length; i++) {
115 if(colors[clrIndex][i] == value[i]) {
116 suffix += value[i];
117 } else {
118 break;
119 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 10 hits
📄 OpenUtau.Core\PackageManager.cs (line 150)
147 using var response = await client.GetAsync(mirror.url, HttpCompletionOption.ResponseHeadersRead);
148 response.EnsureSuccessStatusCode();
149 var contentLength = response.Content.Headers.ContentLength;
150 using var responseStream = await response.Content.ReadAsStreamAsync();
151 using var ms = new MemoryStream();
152 var buffer = new byte[81920];
153 long totalRead = 0;
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 OpenUtau.Core\PackageManager.cs (line 151)
148 response.EnsureSuccessStatusCode();
149 var contentLength = response.Content.Headers.ContentLength;
150 using var responseStream = await response.Content.ReadAsStreamAsync();
151 using var ms = new MemoryStream();
152 var buffer = new byte[81920];
153 long totalRead = 0;
154 int read;
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 22 hits
📄 OpenUtau.Core\DiffSinger\DiffSingerVariance.cs (line 29)
26 Dictionary<string, int> phonemeTokens;
27 ulong linguisticHash;
28 ulong varianceHash;
29 InferenceSession linguisticModel;
30 InferenceSession varianceModel;
31 IG2p g2p;
32 float frameMs;
💬 Disposable field linguisticModel in type DsVariance is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 OpenUtau.Core\DiffSinger\DiffSingerVariance.cs (line 30)
27 ulong linguisticHash;
28 ulong varianceHash;
29 InferenceSession linguisticModel;
30 InferenceSession varianceModel;
31 IG2p g2p;
32 float frameMs;
33 DiffSingerSpeakerEmbedManager speakerEmbedManager;
💬 Disposable field varianceModel in type DsVariance is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Bulk-Crap-Uninstaller

464 total diagnostics across 13 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 10 hits
📄 source\NBug_custom\Core\Submission\Dispatcher.cs (line 36)
33 ||
34 File.GetLastWriteTime(Settings.EntryAssembly.Location)
35 .AddDays(Settings.StopReportingAfter)
36 .CompareTo(DateTime.Now) > 0)
37 {
38 if (isAsynchronous)
39 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 source\NBug_custom\Core\Util\Web\StreamUpload.cs (line 29)
26
27 public StreamUpload()
28 {
29 boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
30 }
31
32 public static StreamUpload Create()
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 142 hits
📄 source\ObjectListView\VirtualObjectListView.cs (line 537)
534
535 // Scroll so that the last item of the previous group is just out of sight,
536 // which will make the desired group header visible.
537 int delta = r.Y + r.Height / 2;
538 NativeMethods.Scroll(this, 0, delta);
539 }
540 }
💬 The operands in the divisive expression r.Height / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 source\ObjectListView\DragDrop\DropSink.cs (line 919)
916
917 if (pt.Y <= (r.Top + close)) {
918 // Scroll faster if the mouse is closer to the top
919 timer.Interval = ((pt.Y <= (r.Top + close / 2)) ? 100 : 350);
920 timer.Start();
921 scrollAmount = -rowHeight;
922 } else {
💬 The operands in the divisive expression close / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 38 hits
📄 source\ObjectListView\Utilities\ColumnSelectionForm.cs (line 73)
70 RearrangableColumns = new List<OLVColumn>(AllColumns);
71 foreach (OLVColumn col in RearrangableColumns) {
72 if (view == View.Details)
73 MapColumnToVisible[col] = col.IsVisible;
74 else
75 MapColumnToVisible[col] = col.IsTileViewColumn;
76 }
💬 Type OLVColumn is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 source\ObjectListView\Utilities\ColumnSelectionForm.cs (line 75)
72 if (view == View.Details)
73 MapColumnToVisible[col] = col.IsVisible;
74 else
75 MapColumnToVisible[col] = col.IsTileViewColumn;
76 }
77 RearrangableColumns.Sort(new SortByDisplayOrder(this));
78
💬 Type OLVColumn is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 4 hits
📄 source\KlocTools\Limited.cs (line 167)
164
165 public override int GetHashCode()
166 {
167 return _value.GetHashCode();
168 }
169
170 TypeCode IConvertible.GetTypeCode()
💬 GetHashCode() refers to mutable field _value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 source\KlocTools\IO\FileSize.cs (line 87)
84
85 public override int GetHashCode()
86 {
87 return _sizeInKb.GetHashCode();
88 }
89
90 public int CompareTo(FileSize other)
💬 GetHashCode() refers to mutable field _sizeInKb (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS015 String placeholders in wrong order 8 hits
📄 source\ObjectListView\VirtualObjectListView.cs (line 235)
232
233 EndUpdate();
234
235 Debug.WriteLine(String.Format("PERF - Setting virtual CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, GetItemCount()));
236 }
237 }
238
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
📄 source\ObjectListView\ObjectListView.cs (line 1359)
1356 }
1357 EndUpdate();
1358
1359 Debug.WriteLine(String.Format("PERF - Setting CheckedObjects on {2} objects took {0}ms / {1} ticks", sw.ElapsedMilliseconds, sw.ElapsedTicks, GetItemCount()));
1360
1361 }
1362 }
💬 string.Format() Placeholders are not in ascending order. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 74 hits
📄 source\ObjectListView\Implementation\NativeMethods.cs (line 204)
201 }
202
203 [StructLayout(LayoutKind.Sequential)]
204 public struct IMAGELISTDRAWPARAMS
205 {
206 public int cbSize;
207 public IntPtr himl;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct IMAGELISTDRAWPARAMS. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 source\ObjectListView\Implementation\NativeMethods.cs (line 226)
223 }
224
225 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
226 public struct LVBKIMAGE
227 {
228 public int ulFlags;
229 public IntPtr hBmp;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct LVBKIMAGE. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 18 hits
📄 source\ObjectListView\CellEditing\CellEditKeyEngine.cs (line 376)
373 CellEditAtEdgeBehaviour atEdgeBehaviour;
374 if (!CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour))
375 atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap;
376 switch (atEdgeBehaviour) {
377 case CellEditAtEdgeBehaviour.Ignore:
378 break;
379 case CellEditAtEdgeBehaviour.EndEdit:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 source\ObjectListView\CellEditing\CellEditKeyEngine.cs (line 432)
429 CellEditAtEdgeBehaviour atEdgeBehaviour;
430 if (!CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour))
431 atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap;
432 switch (atEdgeBehaviour)
433 {
434 case CellEditAtEdgeBehaviour.Ignore:
435 return;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 60 hits
📄 source\ObjectListView\CellEditing\CellEditKeyEngine.cs (line 376)
373 CellEditAtEdgeBehaviour atEdgeBehaviour;
374 if (!CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour))
375 atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap;
376 switch (atEdgeBehaviour) {
377 case CellEditAtEdgeBehaviour.Ignore:
378 break;
379 case CellEditAtEdgeBehaviour.EndEdit:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 source\ObjectListView\CellEditing\CellEditKeyEngine.cs (line 432)
429 CellEditAtEdgeBehaviour atEdgeBehaviour;
430 if (!CellEditKeyAtEdgeBehaviourMap.TryGetValue(keyData, out atEdgeBehaviour))
431 atEdgeBehaviour = CellEditAtEdgeBehaviour.Wrap;
432 switch (atEdgeBehaviour)
433 {
434 case CellEditAtEdgeBehaviour.Ignore:
435 return;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 6 hits
📄 source\PortableSettingsProvider\PortableSettingsProvider.cs (line 57)
54 _settingsXml.Load(Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()));
55
56 if (_settingsXml.SelectSingleNode(SettingsRootName) == null)
57 throw new Exception("Invalid config file");
58 }
59 catch (Exception)
60 {
💬 An exception is thrown from the getter of property SettingsXml (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 source\ObjectListView\Rendering\Renderers.cs (line 1748)
1745 case StringAlignment.Far:
1746 return TextFormatFlags.Bottom;
1747 default:
1748 throw new ArgumentOutOfRangeException();
1749 }
1750 }
1751 }
💬 An exception is thrown from the getter of property CellVerticalAlignmentAsTextFormatFlag (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 source\KlocTools\Localising\LocalisedNameAttribute.cs (line 14)
11 /// <summary>
12 /// Used alongside GetFancyName method to give custom names to properties, fields and enums
13 /// </summary>
14 public class LocalisedNameAttribute : Attribute
15 {
16 public LocalisedNameAttribute(string name)
17 {
💬 LocalisedNameAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 source\KlocTools\Forms\Tools\WindowStyleController.cs (line 76)
73 return attrib == null || attrib.AllowStyleChange;
74 }
75
76 public class ControlStyleAttribute : Attribute
77 {
78 public ControlStyleAttribute(bool allowStyleChange)
79 {
💬 ControlStyleAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 6 hits
📄 source\NBug_custom\Core\Reporting\MiniDump\DumpWriter.cs (line 80)
77
78 private static bool Write(SafeHandle fileHandle, string dumpType)
79 {
80 if (dumpType.ToLower() == MiniDumpType.Tiny.ToString().ToLower())
81 {
82 return Write(fileHandle, DumpTypeFlag.WithIndirectlyReferencedMemory | DumpTypeFlag.ScanMemory);
83 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 source\NBug_custom\Core\Reporting\MiniDump\DumpWriter.cs (line 84)
81 {
82 return Write(fileHandle, DumpTypeFlag.WithIndirectlyReferencedMemory | DumpTypeFlag.ScanMemory);
83 }
84 if (dumpType.ToLower() == MiniDumpType.Normal.ToString().ToLower())
85 {
86 return Write(fileHandle, DumpTypeFlag.Normal);
87 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 2 hits
📄 source\NBug_custom\Core\Submission\ProtocolBase.cs (line 79)
76 if (!string.IsNullOrEmpty(val))
77 {
78 // Escape = and ; characters
79 connectionString += string.Format(
80 "{0}={1};", property.Name.Replace(";", @"\;").Replace("=", @"\="),
81 val.Replace(";", @"\;").Replace("=", @"\="));
82 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 source\NBug_custom\Core\Submission\ProtocolBase.cs (line 79)
76 if (!string.IsNullOrEmpty(val))
77 {
78 // Escape = and ; characters
79 connectionString += string.Format(
80 "{0}={1};", property.Name.Replace(";", @"\;").Replace("=", @"\="),
81 val.Replace(";", @"\;").Replace("=", @"\="));
82 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 92 hits
📄 source\ObjectListView\ObjectListView.cs (line 8955)
8952 objectListView.ResumeSelectionEvents();
8953 }
8954
8955 private readonly ObjectListView objectListView;
8956 }
8957
8958 #endregion
💬 Disposable field objectListView in type SuspendSelectionDisposable is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 source\ObjectListView\Rendering\TreeRenderer.cs (line 69)
66 get { return linePen; }
67 set { linePen = value; }
68 }
69 private Pen linePen;
70
71 /// <summary>
72 /// Should the renderer draw triangles as the expansion glyphs?
💬 Disposable field linePen in type TreeRenderer is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

UniTask

458 total diagnostics across 10 rules

SS003 Integer divided by integer causing implicit rounding 8 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\Internal\MinimumQueue.cs (line 67)
64
65 void Grow()
66 {
67 int newcapacity = (int)((long)array.Length * (long)GrowFactor / 100);
68 if (newcapacity < array.Length + MinimumGrow)
69 {
70 newcapacity = array.Length + MinimumGrow;
💬 The operands in the divisive expression (long)array.Length * (long)GrowFactor / 100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\Internal\MinimumQueue.cs (line 67)
64
65 void Grow()
66 {
67 int newcapacity = (int)((long)array.Length * (long)GrowFactor / 100);
68 if (newcapacity < array.Length + MinimumGrow)
69 {
70 newcapacity = array.Length + MinimumGrow;
💬 The operands in the divisive expression (long)array.Length * (long)GrowFactor / 100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 236 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\Internal\ArrayPoolUtil.cs (line 81)
78 }
79 }
80
81 public struct RentArray<T> : IDisposable
82 {
83 public readonly T[] Array;
84 public readonly int Length;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RentArray. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\IUniTaskAsyncEnumerable.cs (line 68)
65 }
66
67 [StructLayout(LayoutKind.Auto)]
68 public readonly struct Enumerator
69 {
70 private readonly IUniTaskAsyncEnumerator<T> enumerator;
71
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Enumerator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS023 Exception thrown from property getter 16 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\UniTaskObservableExtensions.cs (line 380)
377 get
378 {
379 ThrowIfDisposed();
380 if (!isStopped) throw new InvalidOperationException("AsyncSubject is not completed yet");
381 if (lastError != null) ExceptionDispatchInfo.Capture(lastError).Throw();
382 return lastValue;
383 }
💬 An exception is thrown from the getter of property Value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\Internal\ValueStopwatch.cs (line 29)
26 {
27 if (startTimestamp == 0)
28 {
29 throw new InvalidOperationException("Detected invalid initialization(use 'default'), only to create from StartNew().");
30 }
31
32 var delta = Stopwatch.GetTimestamp() - startTimestamp;
💬 An exception is thrown from the getter of property ElapsedTicks (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS032 Thread.Sleep used in async method 8 hits
📄 src\UniTask.NetCoreTests\AsyncLazyTest.cs (line 76)
73 async UniTask After()
74 {
75 await UniTask.Yield();
76 Thread.Sleep(TimeSpan.FromSeconds(1));
77 await UniTask.Yield();
78 await UniTask.Yield();
79 }
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 src\UniTask.NetCoreTests\AsyncLazyTest.cs (line 84)
81 async UniTask AfterException()
82 {
83 await UniTask.Yield();
84 Thread.Sleep(TimeSpan.FromSeconds(1));
85 await UniTask.Yield();
86 throw new TaskTestException();
87 }
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 12 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\UniTaskExtensions.cs (line 326)
323 }
324 finally
325 {
326 tokenRegistration.Dispose();
327 }
328 }
329
💬 Async overload available for CancellationTokenRegistration.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\UniTaskExtensions.cs (line 268)
265 }
266 finally
267 {
268 tokenRegistration.Dispose();
269 }
270 }
271
💬 Async overload available for CancellationTokenRegistration.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 8 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\UniTaskExtensions.cs (line 34)
31 p.TrySetException(x.Exception.InnerException ?? x.Exception);
32 break;
33 case TaskStatus.RanToCompletion:
34 p.TrySetResult(x.Result);
35 break;
36 default:
37 throw new NotSupportedException();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\UniTaskExtensions.cs (line 34)
31 p.TrySetException(x.Exception.InnerException ?? x.Exception);
32 break;
33 case TaskStatus.RanToCompletion:
34 p.TrySetResult(x.Result);
35 break;
36 default:
37 throw new NotSupportedException();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS044 Attribute must specify [AttributeUsage] 8 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\CompilerServices\AsyncMethodBuilderAttribute.cs (line 7)
4
5namespace System.Runtime.CompilerServices
6{
7 internal sealed class AsyncMethodBuilderAttribute : Attribute
8 {
9 public Type BuilderType { get; }
10
💬 AsyncMethodBuilderAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\CompilerServices\AsyncMethodBuilderAttribute.cs (line 7)
4
5namespace System.Runtime.CompilerServices
6{
7 internal sealed class AsyncMethodBuilderAttribute : Attribute
8 {
9 public Type BuilderType { get; }
10
💬 AsyncMethodBuilderAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS051 Locking on mutable reference 88 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\TaskPool.cs (line 45)
42
43 public static IEnumerable<(Type, int)> GetCacheSizeInfo()
44 {
45 lock (sizes)
46 {
47 foreach (var item in sizes)
48 {
💬 A lock was obtained on sizes but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\TaskPool.cs (line 56)
53
54 public static void RegisterSizeGetter(Type type, Func<int> getSize)
55 {
56 lock (sizes)
57 {
58 sizes[type] = getSize;
59 }
💬 A lock was obtained on sizes but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS063 ValueTask awaited multiple times 2 hits
📄 src\UniTask.NetCoreTests\ChannelTest.cs (line 239)
236 wait1 = reference.Reader.WaitToReadAsync();
237 wait2 = channel.Reader.WaitToReadAsync();
238
239 (await Assert.ThrowsAsync<Exception>(async () => await wait1)).Should().Be(ex);
240 (await Assert.ThrowsAsync<Exception>(async () => await wait2)).Should().Be(ex);
241
242 completion1.Status.Should().Be(TaskStatus.Faulted);
💬 A ValueTask can only be awaited once (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS063-ValueTaskAwaitedMultipleTimes.md)
📄 src\UniTask.NetCoreTests\ChannelTest.cs (line 239)
236 wait1 = reference.Reader.WaitToReadAsync();
237 wait2 = channel.Reader.WaitToReadAsync();
238
239 (await Assert.ThrowsAsync<Exception>(async () => await wait1)).Should().Be(ex);
240 (await Assert.ThrowsAsync<Exception>(async () => await wait2)).Should().Be(ex);
241
242 completion1.Status.Should().Be(TaskStatus.Faulted);
💬 A ValueTask can only be awaited once (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS063-ValueTaskAwaitedMultipleTimes.md)
SS066 Disposable field is not disposed 72 hits
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\AsyncReactiveProperty.cs (line 551)
548 {
549 static Action<object> cancellationCallback = CancellationCallback;
550
551 readonly ReadOnlyAsyncReactiveProperty<T> parent;
552 readonly CancellationToken cancellationToken;
553 readonly CancellationTokenRegistration cancellationTokenRegistration;
554 T value;
💬 Disposable field parent in type Enumerator is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\UniTask\Assets\Plugins\UniTask\Runtime\AsyncReactiveProperty.cs (line 553)
550
551 readonly ReadOnlyAsyncReactiveProperty<T> parent;
552 readonly CancellationToken cancellationToken;
553 readonly CancellationTokenRegistration cancellationTokenRegistration;
554 T value;
555 bool isDisposed;
556 bool firstCall;
💬 Disposable field cancellationTokenRegistration in type Enumerator is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

MQTTnet

456 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 12 hits
📄 Source\MQTTnet.TestApp\PerformanceTest.cs (line 144)
141 stopwatch.Stop();
142 Console.WriteLine($"Sent 10.000 messages within {stopwatch.ElapsedMilliseconds} ms ({stopwatch.ElapsedMilliseconds / (float)testMessageCount} ms / message).");
143
144 var last = DateTime.Now;
145 var msgCount = 0;
146
147 while (true)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Source\MQTTnet.TestApp\PerformanceTest.cs (line 172)
169 }
170 }
171
172 var now = DateTime.Now;
173 if (last < now - TimeSpan.FromSeconds(1))
174 {
175 Console.WriteLine($"sending {msgCount} intended {msgChunkSize / interval.TotalSeconds}");
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 4 hits
📄 Source\MQTTnet.Benchmarks\MessageDeliveryBenchmark.cs (line 175)
172 _allSubscribedTopics = new List<string>();
173
174 var totalNumTopics = _numPublishers * _numTopicsPerPublisher;
175 var topicIndexStep = totalNumTopics / (_numSubscribedTopicsPerSubscriber * _numSubscribers);
176 if (topicIndexStep * _numSubscribedTopicsPerSubscriber * _numSubscribers != totalNumTopics)
177 {
178 throw new InvalidOperationException(
💬 The operands in the divisive expression totalNumTopics / (_numSubscribedTopicsPerSubscriber * _numSubscribers) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Source\MQTTnet.Benchmarks\MessageDeliveryBenchmark.cs (line 175)
172 _allSubscribedTopics = new List<string>();
173
174 var totalNumTopics = _numPublishers * _numTopicsPerPublisher;
175 var topicIndexStep = totalNumTopics / (_numSubscribedTopicsPerSubscriber * _numSubscribers);
176 if (topicIndexStep * _numSubscribedTopicsPerSubscriber * _numSubscribers != totalNumTopics)
177 {
178 throw new InvalidOperationException(
💬 The operands in the divisive expression totalNumTopics / (_numSubscribedTopicsPerSubscriber * _numSubscribers) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 Source\MQTTnet.Server\Internal\TopicHashMaskSubscriptions.cs (line 17)
14 subscriptions = new HashSet<MqttSubscription>();
15 SubscriptionsByHashMask.Add(subscription.TopicHashMask, subscriptions);
16 }
17 subscriptions.Add(subscription);
18 }
19
20 public void RemoveSubscription(MqttSubscription subscription)
💬 Type MqttSubscription is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Source\MQTTnet.Server\Internal\TopicHashMaskSubscriptions.cs (line 17)
14 subscriptions = new HashSet<MqttSubscription>();
15 SubscriptionsByHashMask.Add(subscription.TopicHashMask, subscriptions);
16 }
17 subscriptions.Add(subscription);
18 }
19
20 public void RemoveSubscription(MqttSubscription subscription)
💬 Type MqttSubscription is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 40 hits
📄 Source\MQTTnet\Internal\AsyncEventInvocator.cs (line 7)
4
5namespace MQTTnet.Internal;
6
7public readonly struct AsyncEventInvocator<TEventArgs>
8{
9 readonly Action<TEventArgs> _handler;
10 readonly Func<TEventArgs, Task> _asyncHandler;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct AsyncEventInvocator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Source\MQTTnet\Internal\AsyncLock.cs (line 136)
133 }
134 }
135
136 readonly struct Releaser : IDisposable
137 {
138 readonly AsyncLock _asyncLock;
139
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Releaser. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 36 hits
📄 Source\MQTTnet\MqttClient.cs (line 589)
586
587 do
588 {
589 switch (connectionStatus)
590 {
591 case MqttClientConnectionStatus.Disconnected:
592 case MqttClientConnectionStatus.Disconnecting:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Source\MQTTnet\MqttClient.cs (line 589)
586
587 do
588 {
589 switch (connectionStatus)
590 {
591 case MqttClientConnectionStatus.Disconnected:
592 case MqttClientConnectionStatus.Disconnecting:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 8 hits
📄 Source\MQTTnet.Tests\Server\User_Properties_Tests.cs (line 17)
14[TestClass]
15public class Feature_Tests
16{
17 public TestContext TestContext { get; set; }
18
19 [TestMethod]
20 public async Task Use_User_Properties()
💬 Method set_TestContext might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 Source\MQTTnet.Tests\RoundtripTime_Tests.cs (line 16)
13[TestClass]
14public class RoundtripTime_Tests
15{
16 public TestContext TestContext { get; set; }
17
18 [TestMethod]
19 public async Task Round_Trip_Time()
💬 Method set_TestContext might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS027 Exception thrown from Dispose 4 hits
📄 Source\MQTTnet.Tests\Mockups\TestEnvironment.cs (line 328)
325 if (_exceptions.Count > 0)
326 {
327 // ReSharper disable once ThrowExceptionInUnexpectedLocation
328 throw new InvalidOperationException($"{_exceptions.Count} exceptions tracked.\r\n" + string.Join(Environment.NewLine, _exceptions));
329 }
330 }
331 finally
💬 An exception is thrown from the Dispose() method in type TestEnvironment (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 Source\MQTTnet.Tests\Mockups\TestEnvironment.cs (line 328)
325 if (_exceptions.Count > 0)
326 {
327 // ReSharper disable once ThrowExceptionInUnexpectedLocation
328 throw new InvalidOperationException($"{_exceptions.Count} exceptions tracked.\r\n" + string.Join(Environment.NewLine, _exceptions));
329 }
330 }
331 finally
💬 An exception is thrown from the Dispose() method in type TestEnvironment (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS033 Async overload is available 12 hits
📄 Source\MQTTnet.AspnetCore\MqttConnectionContext.cs (line 200)
197 catch (Exception exception)
198 {
199 // completing the channel makes sure that there is no more data read after a protocol error
200 _input?.Complete(exception);
201 _output?.Complete(exception);
202
203 throw;
💬 Async overload available for PipeReader.Complete (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Source\MQTTnet.AspnetCore\MqttConnectionContext.cs (line 201)
198 {
199 // completing the channel makes sure that there is no more data read after a protocol error
200 _input?.Complete(exception);
201 _output?.Complete(exception);
202
203 throw;
204 }
💬 Async overload available for PipeWriter.Complete (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 64 hits
📄 Source\MQTTnet\Adapter\MqttChannelAdapter.cs (line 148)
145 var receivedPacketTask = ReceiveAsync(cancellationToken);
146 if (receivedPacketTask.IsCompleted)
147 {
148 receivedPacket = receivedPacketTask.Result;
149 }
150 else
151 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Source\MQTTnet\MqttClient.cs (line 782)
779 MqttPacket packet;
780 if (packetTask.IsCompleted)
781 {
782 packet = packetTask.Result;
783 }
784 else
785 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 32 hits
📄 Source\MQTTnet.Tests\Server\HotSwapCerts_Tests.cs (line 39)
36 client01.WaitForConnectOrFail(DefaultTimeout);
37
38 client01.HotSwapClientCert();
39 server.ForceDisconnectAsync(client01).Wait(DefaultTimeout);
40 client01.WaitForDisconnectOrFail(DefaultTimeout);
41
42 client01.WaitForConnectToFail(DefaultTimeout);
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 Source\MQTTnet.Tests\Server\HotSwapCerts_Tests.cs (line 61)
58 client01.WaitForConnectOrFail(DefaultTimeout);
59
60 client01.HotSwapClientCert();
61 server.ForceDisconnectAsync(client01).Wait(DefaultTimeout);
62 client01.WaitForDisconnectOrFail(DefaultTimeout);
63
64 server.InstallNewClientCert(client01.GetCurrentClientCert());
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS051 Locking on mutable reference 4 hits
📄 Source\MQTTnet.Benchmarks\MessageDeliveryBenchmark.cs (line 144)
141 mqttSubscriberClient.ApplicationMessageReceivedAsync += _ =>
142 {
143 // count messages and signal cancellation when expected message count is reached
144 lock (_lockMsgCount)
145 {
146 ++_messagesReceivedCount;
147 if (_messagesReceivedCount == _messagesExpectedCount)
💬 A lock was obtained on _lockMsgCount but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Source\MQTTnet.Benchmarks\MessageDeliveryBenchmark.cs (line 144)
141 mqttSubscriberClient.ApplicationMessageReceivedAsync += _ =>
142 {
143 // count messages and signal cancellation when expected message count is reached
144 lock (_lockMsgCount)
145 {
146 ++_messagesReceivedCount;
147 if (_messagesReceivedCount == _messagesExpectedCount)
💬 A lock was obtained on _lockMsgCount but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS066 Disposable field is not disposed 228 hits
📄 Source\MQTTnet\Implementations\MqttTcpChannel.cs (line 22)
19 readonly MqttClientOptions _clientOptions;
20 readonly MqttClientTcpOptions _tcpOptions;
21
22 Stream _stream;
23
24 public MqttTcpChannel()
25 {
💬 Disposable field _stream in type MqttTcpChannel is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Source\MQTTnet\Implementations\MqttTcpChannel.cs (line 47)
44 ClientCertificate = clientCertificate;
45 }
46
47 public X509Certificate2 ClientCertificate { get; }
48
49 public bool IsSecureConnection { get; }
50
💬 Disposable field ClientCertificate in type MqttTcpChannel is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

SignalR

406 total diagnostics across 11 rules

SS001 Async method with void return type 2 hits
No source samples extracted
SS003 Integer divided by integer causing implicit rounding 36 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 4 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 32 hits
No source samples extracted
SS019 Switch is missing default label 24 hits
No source samples extracted
SS023 Exception thrown from property getter 2 hits
No source samples extracted
SS034 Accessing Task.Result without await 236 hits
No source samples extracted
SS035 Synchronous task wait instead of await 2 hits
No source samples extracted
SS051 Locking on mutable reference 22 hits
No source samples extracted
SS060 ConcurrentDictionary emptiness check without IsEmpty 2 hits
No source samples extracted
SS066 Disposable field is not disposed 44 hits
No source samples extracted

Dapper

400 total diagnostics across 8 rules

SS007 [Flags] enum values are not powers of two 16 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 64 hits
No source samples extracted
SS018 Switch does not handle all enum options 64 hits
No source samples extracted
SS019 Switch is missing default label 112 hits
No source samples extracted
SS033 Async overload is available 8 hits
No source samples extracted
SS034 Accessing Task.Result without await 48 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 72 hits
No source samples extracted
SS066 Disposable field is not disposed 16 hits
No source samples extracted

ExcelDataReader

400 total diagnostics across 6 rules

SS003 Integer divided by integer causing implicit rounding 144 hits
📄 src\ExcelDataReader\Misc\DateTimeHelper.cs (line 66)
63 millis -= millis % MillisPerDay * 2;
64 }
65
66 millis += DoubleDateOffset / TicksPerMillisecond;
67
68 if (millis is < 0 or >= MaxMillis)
69 throw new ArgumentException("OA Date out of range");
💬 The operands in the divisive expression DoubleDateOffset / TicksPerMillisecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\ExcelDataReader\Core\OfficeCrypto\StandardEncryption.cs (line 286)
283
284 byte[] x1 = hashAlgorithm.ComputeHash(derivedKey);
285
286 if (verifierHashSize > keySize / 8)
287 return x1;
288
289 for (int i = 0; i < derivedKey.Length; i++)
💬 The operands in the divisive expression keySize / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 8 hits
📄 src\ExcelDataReader\Log\Logger\NullLogFactory.cs (line 6)
3/// <summary>
4/// The default logger until one is set.
5/// </summary>
6public readonly struct NullLogFactory : ILogFactory, ILog
7{
8 /// <inheritdoc />
9 public void Debug(string message, params object[] formatting)
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NullLogFactory. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\ExcelDataReader\Log\Logger\NullLogFactory.cs (line 6)
3/// <summary>
4/// The default logger until one is set.
5/// </summary>
6public readonly struct NullLogFactory : ILogFactory, ILog
7{
8 /// <inheritdoc />
9 public void Debug(string message, params object[] formatting)
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NullLogFactory. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 32 hits
📄 src\ExcelDataReader\Core\BinaryFormat\XlsWorksheet.cs (line 235)
232 {
233 LogManager.Log(this).Debug("ReadMultiCell {0}", cell.Id);
234
235 switch (cell.Id)
236 {
237 case BIFFRECORDTYPE.MULRK:
238
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\ExcelDataReader\Core\BinaryFormat\XlsWorksheet.cs (line 267)
264
265 object value = null;
266 CellError? error = null;
267 switch (cell.Id)
268 {
269 case BIFFRECORDTYPE.BOOLERR:
270 if (cell.ReadByte(7) == 0)
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 144 hits
📄 src\ExcelDataReader\Core\OpenXmlFormat\XlsxWorkbook.cs (line 58)
55
56 while (reader.Read() is { } record)
57 {
58 switch (record)
59 {
60 case SharedStringRecord pr:
61 SST.Add(pr.Value);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\ExcelDataReader\Core\OpenXmlFormat\XlsxWorkbook.cs (line 35)
32
33 while (reader?.Read() is { } record)
34 {
35 switch (record)
36 {
37 case WorkbookPrRecord pr:
38 IsDate1904 = pr.Date1904;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 8 hits
📄 src\ExcelDataReader\Core\CsvFormat\CsvWorksheet.cs (line 61)
58 {
59 if (AnalyzedPartial)
60 {
61 throw new InvalidOperationException("Cannot use RowCount with AnalyzeInitialCsvRows > 0");
62 }
63
64 return AnalyzedRowCount;
💬 An exception is thrown from the getter of property RowCount (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\ExcelDataReader\Core\CsvFormat\CsvWorksheet.cs (line 61)
58 {
59 if (AnalyzedPartial)
60 {
61 throw new InvalidOperationException("Cannot use RowCount with AnalyzeInitialCsvRows > 0");
62 }
63
64 return AnalyzedRowCount;
💬 An exception is thrown from the getter of property RowCount (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS066 Disposable field is not disposed 64 hits
📄 src\ExcelDataReader\Core\BinaryFormat\XlsBiffStream.cs (line 83)
80 /// </summary>
81 public int Position { get => (int)BaseStream.Position; set => Seek(value, SeekOrigin.Begin); }
82
83 public Stream BaseStream { get; }
84
85 public byte[] SecretKey { get; }
86
💬 Disposable field BaseStream in type XlsBiffStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\ExcelDataReader\Misc\LeaveOpenStream.cs (line 17)
14
15 public override long Position { get => BaseStream.Position; set => BaseStream.Position = value; }
16
17 private Stream BaseStream { get; } = baseStream;
18
19 public override void Flush() => BaseStream.Flush();
20
💬 Disposable field BaseStream in type LeaveOpenStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

g-helper

400 total diagnostics across 9 rules

SS001 Async method with void return type 8 hits
📄 app\AutoUpdate\AutoUpdateControl.cs (line 66)
63 }
64 }
65
66 async void CheckForUpdatesAsync(bool force = false)
67 {
68
69 if (AppConfig.Is("skip_updates")) return;
💬 Method CheckForUpdatesAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 app\AutoUpdate\AutoUpdateControl.cs (line 145)
142 return Regex.Replace(Regex.Replace(input, @"\[|\]", "`$0"), @"\'", "''");
143 }
144
145 async void AutoUpdate(string requestUri)
146 {
147
148 Uri uri = new Uri(requestUri);
💬 Method AutoUpdate is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 14 hits
📄 app\Helpers\Logger.cs (line 10)
7
8 public static void WriteLine(string logMessage)
9 {
10 Debug.WriteLine($"{DateTime.Now}: {logMessage}");
11 if (!Directory.Exists(appPath)) Directory.CreateDirectory(appPath);
12
13 try
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 app\Helpers\Logger.cs (line 17)
14 {
15 using (StreamWriter w = File.AppendText(logFile))
16 {
17 w.WriteLine($"{DateTime.Now}: {logMessage}");
18 w.Close();
19 }
20 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 92 hits
📄 app\AsusACPI.cs (line 528)
525 if (curve.Length != 16) return -1;
526 if (curve.All(singleByte => singleByte == 0)) return -1;
527
528 byte min = (byte)(curve[8] * 255 / 100);
529 byte max = (byte)(curve[15] * 255 / 100);
530 byte[] range = { min, max };
531
💬 The operands in the divisive expression curve
📄 app\AsusACPI.cs (line 529)
526 if (curve.All(singleByte => singleByte == 0)) return -1;
527
528 byte min = (byte)(curve[8] * 255 / 100);
529 byte max = (byte)(curve[15] * 255 / 100);
530 byte[] range = { min, max };
531
532 int result;
💬 The operands in the divisive expression curve
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 app\Peripherals\Mouse\AsusMouse.cs (line 151)
148
149 public override int GetHashCode()
150 {
151 return HashCode.Combine(LightingMode, Brightness, RGBColor, RandomColor, AnimationSpeed, AnimationDirection);
152 }
153
154 public override string? ToString()
💬 GetHashCode() refers to mutable property LightingMode (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 app\Peripherals\Mouse\AsusMouse.cs (line 151)
148
149 public override int GetHashCode()
150 {
151 return HashCode.Combine(LightingMode, Brightness, RGBColor, RandomColor, AnimationSpeed, AnimationDirection);
152 }
153
154 public override string? ToString()
💬 GetHashCode() refers to mutable property Brightness (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 132 hits
📄 app\Display\GammaRamp.cs (line 7)
4{
5
6 [StructLayout(LayoutKind.Sequential)]
7 internal struct GammaRamp
8 {
9 public const int DataPoints = 256;
10
💬 Implement Equals(), GetHashCode() and ToString() methods on struct GammaRamp. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 app\Helpers\RestrictedProcessHelper.cs (line 117)
114 }
115
116 [StructLayout(LayoutKind.Sequential)]
117 private struct PROCESS_INFORMATION
118 {
119 public IntPtr hProcess;
120 public IntPtr hThread;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PROCESS_INFORMATION. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 24 hits
📄 app\Input\KeyboardHook.cs (line 38)
35
36 public static void KeyPress(Keys key)
37 {
38 switch (key)
39 {
40 case Keys.LButton:
41 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 app\Ally\AllyControl.cs (line 723)
720
721 public void ToggleMode()
722 {
723 switch (_mode)
724 {
725 case ControllerMode.Auto:
726 SetMode(ControllerMode.Gamepad);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 62 hits
📄 app\Input\KeyboardHook.cs (line 38)
35
36 public static void KeyPress(Keys key)
37 {
38 switch (key)
39 {
40 case Keys.LButton:
41 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 app\Ryzen\RyzenSmu.cs (line 45)
42 RyzenNbAccesss = new Ols();
43
44 // Check WinRing0 status
45 switch (RyzenNbAccesss.GetDllStatus())
46 {
47 case (uint)Ols.OlsDllStatus.OLS_DLL_NO_ERROR:
48 if (ShowDebug)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS049 Comparing strings without StringComparison 6 hits
📄 app\UI\RForm.cs (line 74)
71 {
72 string? uiMode = AppConfig.GetString("ui_mode");
73
74 if (uiMode is not null && uiMode.ToLower() == "dark")
75 {
76 return true;
77 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 app\UI\RForm.cs (line 79)
76 return true;
77 }
78
79 if (uiMode is not null && uiMode.ToLower() == "light")
80 {
81 return false;
82 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS066 Disposable field is not disposed 50 hits
📄 app\Updates.cs (line 25)
22 static int updatesCount = 0;
23 private static long lastUpdate;
24
25 private readonly Font _boldUnderlineFont;
26 private readonly Font _font;
27
28 public struct DriverDownload
💬 Disposable field _boldUnderlineFont in type Updates is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 app\Updates.cs (line 26)
23 private static long lastUpdate;
24
25 private readonly Font _boldUnderlineFont;
26 private readonly Font _font;
27
28 public struct DriverDownload
29 {
💬 Disposable field _font in type Updates is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

git-credential-manager

396 total diagnostics across 10 rules

SS001 Async method with void return type 4 hits
📄 src\shared\Core\Diagnostics\NetworkingDiagnostic.cs (line 101)
98 return true;
99 }
100
101 internal /* For testing purposes */ async void SendHttpRequest(StringBuilder log, HttpClient httpClient)
102 {
103 foreach (var uri in new List<string> { TestHttpUri, TestHttpUriFallback })
104 {
💬 Method SendHttpRequest is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\shared\Core\Diagnostics\NetworkingDiagnostic.cs (line 101)
98 return true;
99 }
100
101 internal /* For testing purposes */ async void SendHttpRequest(StringBuilder log, HttpClient httpClient)
102 {
103 foreach (var uri in new List<string> { TestHttpUri, TestHttpUriFallback })
104 {
💬 Method SendHttpRequest is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 src\shared\Core\Trace.cs (line 328)
325 }
326
327 // Git's trace format is "{timestamp,-15} {source,-23} trace: {details}"
328 string text = $"{DateTime.Now:HH:mm:ss.ffffff} {source,-23} trace: [{memberName}] {message}";
329
330 return text;
331 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\shared\Core\Trace.cs (line 328)
325 }
326
327 // Git's trace format is "{timestamp,-15} {source,-23} trace: {details}"
328 string text = $"{DateTime.Now:HH:mm:ss.ffffff} {source,-23} trace: [{memberName}] {message}";
329
330 return text;
331 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 src\shared\Core\Trace.cs (line 149)
146 lock (_writersLock)
147 {
148 // Try not to add the same listener more than once
149 if (_writers.Contains(listener))
150 return;
151
152 _writers.Add(listener);
💬 Type TextWriter is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\shared\Core\Trace.cs (line 149)
146 lock (_writersLock)
147 {
148 // Try not to add the same listener more than once
149 if (_writers.Contains(listener))
150 return;
151
152 _writers.Add(listener);
💬 Type TextWriter is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 80 hits
📄 src\shared\Core\IniFile.cs (line 30)
27 }
28
29 [DebuggerDisplay("{DebuggerDisplay}")]
30 public readonly struct IniSectionName : IEquatable<IniSectionName>
31 {
32 public IniSectionName(string name, string subName = null)
33 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct IniSectionName. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\shared\Core\PlatformUtils.cs (line 499)
496 }
497
498 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
499 private unsafe struct RTL_OSVERSIONINFOEX
500 {
501 internal uint dwOSVersionInfoSize;
502 internal uint dwMajorVersion;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RTL_OSVERSIONINFOEX. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 12 hits
📄 src\shared\Core\UI\Dispatcher.cs (line 146)
143 {
144 lock (_queue)
145 {
146 switch (_state)
147 {
148 case State.Started:
149 throw new InvalidOperationException("Dispatcher has already started.");
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\shared\Core\UI\Dispatcher.cs (line 169)
166 {
167 lock (_queue)
168 {
169 switch (_state)
170 {
171 case State.NotStarted:
172 throw new InvalidOperationException("Dispatcher is not running.");
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 24 hits
📄 src\shared\Core\UI\ViewModels\CredentialsViewModel.cs (line 21)
18
19 private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
20 {
21 switch (e.PropertyName)
22 {
23 case nameof(UserName):
24 case nameof(Password):
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\shared\Core\InputArguments.cs (line 148)
145 // We know the first piece is the path
146 ub.Path = pathParts[0];
147
148 switch (pathParts.Length)
149 {
150 // If we have 3 items, that means path, query, and fragment
151 case 3:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 150 hits
📄 src\shared\Core\Commands\GetCommand.cs (line 50)
47 Context.Trace.WriteDictionarySecrets(output, new []{ "password" }, StringComparer.OrdinalIgnoreCase);
48
49 // Write the values to standard out
50 Context.Streams.Out.WriteDictionary(output);
51 }
52 }
53}
💬 Async overload available for StreamExtensions.WriteDictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\shared\Core\ConfigurationService.cs (line 100)
97 foreach (IConfigurableComponent component in _components)
98 {
99 _context.Trace.WriteLine($"Unconfiguring component '{component.Name}'...");
100 _context.Streams.Error.WriteLine($"Unconfiguring component '{component.Name}'...");
101 await component.UnconfigureAsync(target);
102 }
103 }
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS057 Collection manipulated during traversal 8 hits
📄 src\shared\Core\Trace.cs (line 299)
296 {
297 using (var writer = _writers[i])
298 {
299 _writers.Remove(writer);
300 }
301 }
302 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\shared\Core\Trace2.cs (line 467)
464 {
465 using (var writer = _writers[i])
466 {
467 _writers.Remove(writer);
468 }
469 }
470 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 src\shared\Core\Commands\DiagnoseCommand.cs (line 80)
77 string logFilePath = Path.Combine(outputDir, "gcm-diagnose.log");
78 var extraLogs = new List<string>();
79
80 using var fullLog = new StreamWriter(logFilePath, append: false, Encoding.UTF8);
81 fullLog.WriteLine("Diagnose log at {0:s}Z", DateTime.UtcNow);
82 fullLog.WriteLine();
83 fullLog.WriteLine($"AppPath: {_context.ApplicationPath}");
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\shared\Core\Commands\DiagnoseCommand.cs (line 80)
77 string logFilePath = Path.Combine(outputDir, "gcm-diagnose.log");
78 var extraLogs = new List<string>();
79
80 using var fullLog = new StreamWriter(logFilePath, append: false, Encoding.UTF8);
81 fullLog.WriteLine("Diagnose log at {0:s}Z", DateTime.UtcNow);
82 fullLog.WriteLine();
83 fullLog.WriteLine($"AppPath: {_context.ApplicationPath}");
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 108 hits
📄 src\shared\Core\Interop\Windows\WindowsTerminal.cs (line 167)
164
165 private class TtyContext : IDisposable
166 {
167 private readonly ITrace _trace;
168 private readonly ITrace2 _trace2;
169 private readonly SafeFileHandle _stream;
170
💬 Disposable field _trace in type TtyContext is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\shared\Core\Interop\Windows\WindowsTerminal.cs (line 168)
165 private class TtyContext : IDisposable
166 {
167 private readonly ITrace _trace;
168 private readonly ITrace2 _trace2;
169 private readonly SafeFileHandle _stream;
170
171 private ConsoleMode _originalMode;
💬 Disposable field _trace2 in type TtyContext is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Util

384 total diagnostics across 19 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 24 hits
📄 src\Util.Core\Helpers\FileWatcher.cs (line 249)
246 /// <param name="path">文件路径</param>
247 /// <param name="debounceInterval">防抖间隔</param>
248 internal bool IsValid( string path, int debounceInterval ) {
249 if ( _file != null && path == _file.Path && DateTime.Now - _file.Time < TimeSpan.FromMilliseconds( debounceInterval ) ) {
250 _file = new WatchFile( path );
251 return false;
252 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Util.Core\Helpers\FileWatcher.cs (line 268)
265 /// <param name="path">文件路径</param>
266 public WatchFile( string path ) {
267 Path = path;
268 Time = DateTime.Now;
269 }
270
271 /// <summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 20 hits
📄 src\Util.Core\Helpers\Time.cs (line 150)
147 public static long GetUnixTimestamp( DateTime time ) {
148 var start = TimeZoneInfo.ConvertTime( new DateTime( 1970, 1, 1 ), TimeZoneInfo.Local );
149 long ticks = ( time - start.Add( new TimeSpan( 8, 0, 0 ) ) ).Ticks;
150 return Util.Helpers.Convert.ToLong( ticks / TimeSpan.TicksPerSecond );
151 }
152
153 /// <summary>
💬 The operands in the divisive expression ticks / TimeSpan.TicksPerSecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Util.Images.ImageSharp\ImageWrapper.cs (line 140)
137 var options = new RichTextOptions( _font ) {
138 VerticalAlignment = VerticalAlignment.Center,
139 HorizontalAlignment = HorizontalAlignment.Center,
140 Origin = new Vector2( _width / 2, _height / 2 )
141 };
142 return Text( text, color, options );
143 }
💬 The operands in the divisive expression _width / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 26 hits
📄 src\Util.Core\Expressions\ParameterRebinder.cs (line 34)
31 /// </summary>
32 /// <param name="parameterExpression">参数</param>
33 protected override Expression VisitParameter( ParameterExpression parameterExpression ) {
34 if( _map.TryGetValue( parameterExpression, out var replacement ) )
35 parameterExpression = replacement;
36 return base.VisitParameter( parameterExpression );
37 }
💬 Type ParameterExpression is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Util.Templates.Razor\RazorEngineCore\RazorEngineCompilationOptionsBuilder.cs (line 40)
37
38 public void AddMetadataReference(MetadataReference reference)
39 {
40 this.Options.MetadataReferences.Add(reference);
41 }
42
43 public void AddUsing(string namespaceName)
💬 Type MetadataReference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 4 hits
📄 src\Util.Domain\Entities\EntityBase.cs (line 58)
55 /// 获取哈希
56 /// </summary>
57 public override int GetHashCode() {
58 return ReferenceEquals( Id, null ) ? 0 : Id.GetHashCode();
59 }
60
61 /// <summary>
💬 GetHashCode() refers to mutable property Id (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Util.Domain\Entities\EntityBase.cs (line 58)
55 /// 获取哈希
56 /// </summary>
57 public override int GetHashCode() {
58 return ReferenceEquals( Id, null ) ? 0 : Id.GetHashCode();
59 }
60
61 /// <summary>
💬 GetHashCode() refers to mutable property Id (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 src\Util.FileStorage.Abstractions\FileSize.cs (line 6)
3/// <summary>
4/// 文件大小
5/// </summary>
6public readonly struct FileSize {
7 /// <summary>
8 /// 文件字节长度
9 /// </summary>
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FileSize. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Util.FileStorage.Abstractions\FileSize.cs (line 6)
3/// <summary>
4/// 文件大小
5/// </summary>
6public readonly struct FileSize {
7 /// <summary>
8 /// 文件字节长度
9 /// </summary>
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FileSize. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 34 hits
📄 src\Util.Core\ExpressionExtensions.cs (line 329)
326 /// <param name="operator">运算符</param>
327 /// <param name="value">值</param>
328 public static Expression Operation( this Expression left, Operator @operator, Expression value ) {
329 switch( @operator ) {
330 case Operator.Equal:
331 return left.Equal( value );
332 case Operator.NotEqual:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Util.Core\ExpressionExtensions.cs (line 299)
296 /// <param name="operator">运算符</param>
297 /// <param name="value">值</param>
298 public static Expression Operation( this Expression left, Operator @operator, object value ) {
299 switch( @operator ) {
300 case Operator.Equal:
301 return left.Equal( value );
302 case Operator.NotEqual:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 54 hits
📄 src\Util.Core\ExpressionExtensions.cs (line 329)
326 /// <param name="operator">运算符</param>
327 /// <param name="value">值</param>
328 public static Expression Operation( this Expression left, Operator @operator, Expression value ) {
329 switch( @operator ) {
330 case Operator.Equal:
331 return left.Equal( value );
332 case Operator.NotEqual:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Util.Core\ExpressionExtensions.cs (line 299)
296 /// <param name="operator">运算符</param>
297 /// <param name="value">值</param>
298 public static Expression Operation( this Expression left, Operator @operator, object value ) {
299 switch( @operator ) {
300 case Operator.Equal:
301 return left.Equal( value );
302 case Operator.NotEqual:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 2 hits
📄 src\Util.Generators\Contexts\EntityContext.cs (line 78)
75 var result = Properties.FirstOrDefault( t => t.IsKey );
76 if( result == null ) {
77 var message = string.Format( GeneratorResource.NotSetPrimaryKey, GetNameWithSchema() );
78 throw new InvalidOperationException( message );
79 }
80 return result;
81 }
💬 An exception is thrown from the getter of property Key (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Util.Generators\Contexts\EntityContext.cs (line 78)
75 var result = Properties.FirstOrDefault( t => t.IsKey );
76 if( result == null ) {
77 var message = string.Format( GeneratorResource.NotSetPrimaryKey, GetNameWithSchema() );
78 throw new InvalidOperationException( message );
79 }
80 return result;
81 }
💬 An exception is thrown from the getter of property Key (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 122 hits
📄 test\Util.Microservices.Dapr.PubsubSample\Program.cs (line 20)
17app.UseCloudEvents();
18app.MapSubscribeHandler();
19app.MapControllers();
20app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 test\Util.Microservices.Dapr.WebApiSample\Program.cs (line 20)
17app.UseCloudEvents();
18app.MapSubscribeHandler();
19app.MapControllers();
20app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 8 hits
📄 src\Util.Ui\Sources\Spa\Util\TaskTimeoutExtensions.cs (line 24)
21 {
22 if (task == await Task.WhenAny(task, Task.Delay(timeoutDelay)))
23 {
24 return task.Result;
25 }
26 else
27 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Util.Ui\Sources\Spa\Proxying\SpaProxy.cs (line 290)
287 await Task.Delay(100, cancellationToken);
288 }
289
290 var result = resultTask.Result; // We know it's completed already
291 if (result.MessageType == WebSocketMessageType.Close)
292 {
293 if (destination.State == WebSocketState.Open || destination.State == WebSocketState.CloseReceived)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 2 hits
📄 src\Util.Ui\Sources\Spa\Util\TaskTimeoutExtensions.cs (line 12)
9 {
10 if (task == await Task.WhenAny(task, Task.Delay(timeoutDelay)))
11 {
12 task.Wait(); // Allow any errors to propagate
13 }
14 else
15 {
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 src\Util.Ui\Sources\Spa\Util\TaskTimeoutExtensions.cs (line 12)
9 {
10 if (task == await Task.WhenAny(task, Task.Delay(timeoutDelay)))
11 {
12 task.Wait(); // Allow any errors to propagate
13 }
14 else
15 {
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS037 HttpClient instantiated directly 4 hits
📄 src\Util.Ui\Sources\Spa\Proxying\SpaProxy.cs (line 44)
41 UseCookies = false,
42 };
43
44 return new HttpClient(handler)
45 {
46 Timeout = requestTimeout
47 };
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 src\Util.Ui\Sources\Spa\AngularCli\AngularCliMiddleware.cs (line 87)
84 }
85
86 private static async Task WaitForAngularCliServerToAcceptRequests( Uri cliServerUri, CancellationToken applicationStoppingToken ) {
87 using var client = new HttpClient();
88 var i = 0;
89 while ( true ) {
90 try {
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 src\Util.Security\Helpers\Encrypt.cs (line 273)
270 encoding ??= Encoding.UTF8;
271 var sha256 = new HMACSHA256( Encoding.ASCII.GetBytes( key ) );
272 var hash = sha256.ComputeHash( encoding.GetBytes( value ) );
273 return string.Join( "", hash.ToList().Select( t => t.ToString( "x2" ) ).ToArray() );
274 }
275
276 #endregion
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\Util.Security\Helpers\Encrypt.cs (line 273)
270 encoding ??= Encoding.UTF8;
271 var sha256 = new HMACSHA256( Encoding.ASCII.GetBytes( key ) );
272 var hash = sha256.ComputeHash( encoding.GetBytes( value ) );
273 return string.Join( "", hash.ToList().Select( t => t.ToString( "x2" ) ).ToArray() );
274 }
275
276 #endregion
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 10 hits
📄 src\Util.Core\Ui\HtmlAttribute.cs (line 6)
3/// <summary>
4/// 用于控制Razor Page生成Html的路径
5/// </summary>
6public class HtmlAttribute : Attribute {
7 /// <summary>
8 /// 生成路径,相对根路径,范例:/ClientApp/src/app/app.component.html
9 /// </summary>
💬 HtmlAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\Util.Localization\LocalizedTypeAttribute.cs (line 6)
3/// <summary>
4/// 本地化资源类型
5/// </summary>
6public class LocalizedTypeAttribute : Attribute {
7 /// <summary>
8 /// 本地化资源类型
9 /// </summary>
💬 LocalizedTypeAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 46 hits
📄 src\Util.FileStorage\FileNameProcessorFactory.cs (line 24)
21 public IFileNameProcessor CreateProcessor( string policy ) {
22 if ( policy.IsEmpty() )
23 return new FileNameProcessor();
24 if ( policy.ToUpperInvariant() == UserTimeFileNameProcessor.Policy )
25 return new UserTimeFileNameProcessor( _session );
26 throw new NotImplementedException( $"文件名处理策略 {policy} 未实现." );
27 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 test\Util.FileStorage.Tests.Integration\Samples\TestFileNameProcessorFactory.cs (line 15)
12 public IFileNameProcessor CreateProcessor( string policy ) {
13 if ( policy.IsEmpty() )
14 return new FileNameProcessor();
15 if ( policy.ToLowerInvariant() == "test" )
16 return new TestFileNameProcessor();
17 throw new NotImplementedException( $"文件名处理策略 {policy} 未实现." );
18 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS056 HttpRequest.Form read synchronously 4 hits
📄 src\Util.AspNetCore\Helpers\Web.cs (line 151)
148 /// </summary>
149 public static List<IFormFile> GetFiles() {
150 var result = new List<IFormFile>();
151 var files = Request.Form.Files;
152 if ( files.Count == 0 )
153 return result;
154 result.AddRange( files.Where( file => file?.Length > 0 ) );
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
📄 src\Util.AspNetCore\Helpers\Web.cs (line 186)
183 string result = Request.Query[name];
184 if ( result.IsEmpty() == false )
185 return result;
186 result = Request.Form[name];
187 if ( result.IsEmpty() == false )
188 return result;
189 return Request.Headers[name];
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
SS058 String concatenated in a loop 2 hits
📄 src\Util.Tenants\Resolvers\Internal\DomainTenantResolver.cs (line 39)
36 domainMap.Add( item.Key, item.Value );
37 }
38 }
39 domainFormat += $",{resolver.DomainFormat}";
40 }
41 var map = await DomainTenantResolverHelper.CombineMapAsync( domainMap, _store );
42 return DomainTenantResolverHelper.ResolveTenantId( host, map, domainFormat );
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Util.Tenants\Resolvers\Internal\DomainTenantResolver.cs (line 39)
36 domainMap.Add( item.Key, item.Value );
37 }
38 }
39 domainFormat += $",{resolver.DomainFormat}";
40 }
41 var map = await DomainTenantResolverHelper.CombineMapAsync( domainMap, _store );
42 return DomainTenantResolverHelper.ResolveTenantId( host, map, domainFormat );
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 10 hits
📄 src\Util.Images.ImageSharp\ImageWrapper.cs (line 188)
185 /// <inheritdoc />
186 public async Task<byte[]> ToStreamAsync( CancellationToken cancellationToken = default ) {
187 using var image = GetImage();
188 using var stream = new MemoryStream();
189 _commands.ForEach( command => command.Invoke( image ) );
190 await image.SaveAsync( stream, GetImageEncoder(), cancellationToken );
191 return await Util.Helpers.File.ToBytesAsync( stream, cancellationToken );
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Util.QrCode.ZXing\ZXing\ZXingQrCodeService.cs (line 167)
164 /// <inheritdoc />
165 public async Task<byte[]> ToBytesAsync( CancellationToken cancellationToken = default ) {
166 using var image = GetImage();
167 using var stream = new MemoryStream();
168 await image.SaveAsync( stream, GetImageEncoder(), cancellationToken );
169 return stream.ToArray();
170 }
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 8 hits
📄 src\Util.Core\Helpers\FileWatcher.cs (line 10)
7 /// <summary>
8 /// 文件系统监视器
9 /// </summary>
10 private readonly FileSystemWatcher _watcher;
11 /// <summary>
12 /// 防抖间隔
13 /// </summary>
💬 Disposable field _watcher in type FileWatcher is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Util.Data.EntityFrameworkCore\StoreBase.cs (line 55)
52 /// <summary>
53 /// 工作单元
54 /// </summary>
55 protected UnitOfWorkBase UnitOfWork { get; }
56
57 /// <summary>
58 /// 实体集
💬 Disposable field UnitOfWork in type StoreBase is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Il2CppDumper

380 total diagnostics across 7 rules

SS003 Integer divided by integer causing implicit rounding 96 hits
📄 Il2CppDumper\ExecutableFormats\Elf64.cs (line 32)
29 FixedProgramSegment();
30 }
31 pt_dynamic = programSegment.First(x => x.p_type == PT_DYNAMIC);
32 dynamicSection = ReadClassArray<Elf64_Dyn>(pt_dynamic.p_offset, pt_dynamic.p_filesz / 16L);
33 if (IsDumped)
34 {
35 FixedDynamicSection();
💬 The operands in the divisive expression pt_dynamic.p_filesz / 16L are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Il2CppDumper\ExecutableFormats\Elf.cs (line 41)
38 FixedProgramSegment();
39 }
40 pt_dynamic = programSegment.First(x => x.p_type == PT_DYNAMIC);
41 dynamicSection = ReadClassArray<Elf32_Dyn>(pt_dynamic.p_offset, pt_dynamic.p_filesz / 8u);
42 if (IsDumped)
43 {
44 FixedDynamicSection();
💬 The operands in the divisive expression pt_dynamic.p_filesz / 8u are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 128 hits
📄 Il2CppDumper\Il2Cpp\Il2Cpp.cs (line 255)
252 methodDefinitionMethodSpecs.Add(methodDefinitionIndex, list);
253 }
254 list.Add(methodSpec);
255 methodSpecGenericMethodPointers.Add(methodSpec, genericMethodPointers[table.indices.methodIndex]);
256 }
257 }
258
💬 Type Il2CppMethodSpec is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Il2CppDumper\Utils\DummyAssemblyGenerator.cs (line 90)
87 var namespaceName = metadata.GetStringFromIndex(typeDef.namespaceIndex);
88 var typeName = metadata.GetStringFromIndex(typeDef.nameIndex);
89 var typeDefinition = new TypeDefinition(namespaceName, typeName, (TypeAttributes)typeDef.flags);
90 typeDefinitionDic.Add(typeDef, typeDefinition);
91 if (typeDef.declaringTypeIndex == -1)
92 {
93 moduleDefinition.Types.Add(typeDefinition);
💬 Type Il2CppTypeDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 Il2CppDumper\Utils\FileDialogNative.cs (line 146)
143 }
144
145 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
146 internal struct COMDLG_FILTERSPEC
147 {
148 [MarshalAs(UnmanagedType.LPWStr)]
149 internal string pszName;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct COMDLG_FILTERSPEC. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Il2CppDumper\Utils\FileDialogNative.cs (line 146)
143 }
144
145 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
146 internal struct COMDLG_FILTERSPEC
147 {
148 [MarshalAs(UnmanagedType.LPWStr)]
149 internal string pszName;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct COMDLG_FILTERSPEC. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 16 hits
📄 Il2CppDumper\Outputs\StructGenerator.cs (line 832)
829 {
830 rgctxDefData = definitionData.data;
831 }
832 switch (definitionData.type)
833 {
834 case Il2CppRGCTXDataType.IL2CPP_RGCTX_DATA_TYPE:
835 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Il2CppDumper\Outputs\StructGenerator.cs (line 878)
875 {
876 rgctxDefData = definitionData.data;
877 }
878 switch (definitionData.type)
879 {
880 case Il2CppRGCTXDataType.IL2CPP_RGCTX_DATA_TYPE:
881 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 96 hits
📄 Il2CppDumper\Utils\SectionHelper.cs (line 153)
150
151 private void SetSection(SearchSectionType type, List<SearchSection> secs)
152 {
153 switch (type)
154 {
155 case SearchSectionType.Exec:
156 exec = secs;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Il2CppDumper\ExecutableFormats\Elf64.cs (line 108)
105 foreach (var symbol in symbolTable)
106 {
107 var name = ReadStringToNull(dynstrOffset + symbol.st_name);
108 switch (name)
109 {
110 case "g_CodeRegistration":
111 codeRegistration = symbol.st_value;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS058 String concatenated in a loop 28 hits
📄 Il2CppDumper\Outputs\StructGenerator.cs (line 103)
100 var returnType = ParseType(methodReturnType);
101 if (methodReturnType.byref == 1)
102 {
103 returnType += "*";
104 }
105 methodTypeSignature.Add(methodReturnType.byref == 1 ? Il2CppTypeEnum.IL2CPP_TYPE_PTR : methodReturnType.type);
106 var signature = $"{returnType} {FixName(methodFullName)} (";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Il2CppDumper\Outputs\StructGenerator.cs (line 134)
131 }
132 methodTypeSignature.Add(Il2CppTypeEnum.IL2CPP_TYPE_PTR);
133 parameterStrs.Add("const MethodInfo* method");
134 signature += string.Join(", ", parameterStrs);
135 signature += ");";
136 scriptMethod.Signature = signature;
137 scriptMethod.TypeSignature = GetMethodTypeSignature(methodTypeSignature);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 12 hits
📄 Il2CppDumper\IO\BinaryStream.cs (line 15)
12 public double Version;
13 public bool Is32Bit;
14 public ulong ImageBase;
15 private readonly Stream stream;
16 private readonly BinaryReader reader;
17 private readonly BinaryWriter writer;
18 private readonly MethodInfo readClass;
💬 Disposable field stream in type BinaryStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Il2CppDumper\Utils\CustomAttributeDataReader.cs (line 9)
6 public class CustomAttributeDataReader : BinaryReader
7 {
8 private readonly Il2CppExecutor executor;
9 private readonly Metadata metadata;
10 private long ctorBuffer;
11 private long dataBuffer;
12
💬 Disposable field metadata in type CustomAttributeDataReader is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

SwarmUI

378 total diagnostics across 21 rules

SS001 Async method with void return type 2 hits
📄 src\Backends\NetworkBackendUtils.cs (line 572)
569 }
570 }
571 new Thread(MonitorLoop) { Name = $"SelfStart{nameSimple.Replace(' ', '_')}_Monitor" }.Start();
572 async void MonitorErrLoop()
573 {
574 try
575 {
💬 Method MonitorErrLoop is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Backends\NetworkBackendUtils.cs (line 572)
569 }
570 }
571 new Thread(MonitorLoop) { Name = $"SelfStart{nameSimple.Replace(' ', '_')}_Monitor" }.Start();
572 async void MonitorErrLoop()
573 {
574 try
575 {
💬 Method MonitorErrLoop is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 src\WebAPI\AdminAPI.cs (line 341)
338 FormUrlEncodedContent content = new(new Dictionary<string, string>()
339 {
340 ["pastetype"] = "swarm",
341 ["pastetitle"] = $"SwarmUI v{Utilities.Version} Server Log - {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
342 ["response"] = "micro",
343 ["v"] = "300",
344 ["pastecontents"] = logText
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\WebAPI\AdminAPI.cs (line 341)
338 FormUrlEncodedContent content = new(new Dictionary<string, string>()
339 {
340 ["pastetype"] = "swarm",
341 ["pastetitle"] = $"SwarmUI v{Utilities.Version} Server Log - {DateTime.Now:yyyy-MM-dd HH:mm:ss}",
342 ["response"] = "micro",
343 ["v"] = "300",
344 ["pastecontents"] = logText
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 50 hits
📄 src\Accounts\User.cs (line 507)
504 {
505 string id = Utilities.SecureRandomHex(32);
506 string validationText = Utilities.SecureRandomHex(32);
507 byte[] salt = RandomNumberGenerator.GetBytes(128 / 8);
508 byte[] hashedText = KeyDerivation.Pbkdf2(password: validationText, salt: salt, prf: KeyDerivationPrf.HMACSHA256, iterationCount: 10, numBytesRequested: 256 / 8);
509 string validationHashed = Utilities.BytesToHex(salt) + ":" + Utilities.BytesToHex(hashedText);
510 long nowUnix = DateTimeOffset.Now.ToUnixTimeSeconds();
💬 The operands in the divisive expression 128 / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Accounts\User.cs (line 508)
505 string id = Utilities.SecureRandomHex(32);
506 string validationText = Utilities.SecureRandomHex(32);
507 byte[] salt = RandomNumberGenerator.GetBytes(128 / 8);
508 byte[] hashedText = KeyDerivation.Pbkdf2(password: validationText, salt: salt, prf: KeyDerivationPrf.HMACSHA256, iterationCount: 10, numBytesRequested: 256 / 8);
509 string validationHashed = Utilities.BytesToHex(salt) + ":" + Utilities.BytesToHex(hashedText);
510 long nowUnix = DateTimeOffset.Now.ToUnixTimeSeconds();
511 SessionHandler.LoginSession session = new()
💬 The operands in the divisive expression 256 / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIWebAPI.cs (line 224)
221 }
222 else
223 {
224 backendsToStart = [.. backendsToStart.Concat(backendsStopped).Distinct()];
225 }
226 }
227 if (doFullRestart)
💬 Type ComfyUISelfStartBackend is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIWebAPI.cs (line 224)
221 }
222 else
223 {
224 backendsToStart = [.. backendsToStart.Concat(backendsStopped).Distinct()];
225 }
226 }
227 if (doFullRestart)
💬 Type ComfyUISelfStartBackend is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 2 hits
📄 src\Accounts\Session.cs (line 281)
278 /// <summary>Gets a hash code for this session, for C# equality comparsion.</summary>
279 public override int GetHashCode()
280 {
281 return ID.GetHashCode();
282 }
283
284 /// <summary>Returns true if this session is the same as another.</summary>
💬 GetHashCode() refers to mutable field ID (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Accounts\Session.cs (line 281)
278 /// <summary>Gets a hash code for this session, for C# equality comparsion.</summary>
279 public override int GetHashCode()
280 {
281 return ID.GetHashCode();
282 }
283
284 /// <summary>Returns true if this session is the same as another.</summary>
💬 GetHashCode() refers to mutable field ID (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 src\Utils\MemoryNum.cs (line 4)
1namespace SwarmUI.Utils;
2
3/// <summary>Mini-struct to hold data about a memory (bytes) size number.</summary>
4public struct MemoryNum(long inBytes)
5{
6 public long InBytes = inBytes;
7
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MemoryNum. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Utils\MemoryNum.cs (line 4)
1namespace SwarmUI.Utils;
2
3/// <summary>Mini-struct to hold data about a memory (bytes) size number.</summary>
4public struct MemoryNum(long inBytes)
5{
6 public long InBytes = inBytes;
7
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MemoryNum. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 src\Text2Image\T2IParamTypes.cs (line 971)
968 {
969 throw new SwarmUserErrorException("Unknown parameter type");
970 }
971 switch (type.Type)
972 {
973 case T2IParamDataType.INTEGER:
974 if (!long.TryParse(val, out long valInt))
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Text2Image\T2IParamTypes.cs (line 971)
968 {
969 throw new SwarmUserErrorException("Unknown parameter type");
970 }
971 switch (type.Type)
972 {
973 case T2IParamDataType.INTEGER:
974 if (!long.TryParse(val, out long valInt))
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 12 hits
📄 src\Text2Image\T2IModel.cs (line 396)
393
394 public static JToken ReadRawGGUFObject(Stream file, string modelPath, int keyId, GGUFMetadataValueType type, byte[] buf)
395 {
396 switch (type)
397 {
398 case GGUFMetadataValueType.UINT8: return file.ReadByte();
399 case GGUFMetadataValueType.INT8: return (sbyte)file.ReadByte();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Core\Program.cs (line 364)
361 Thread.Sleep(500);
362 try
363 {
364 switch (LaunchMode.Trim().ToLowerFast())
365 {
366 case "web":
367 Logs.Init("Launch web browser...");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS032 Thread.Sleep used in async method 2 hits
📄 src\Backends\BackendHandler.cs (line 831)
828 Logs.Info($"Backend {backend.ID} ({backend.AbstractBackend.HandlerTypeData.Name}) has been locked in use for at least 5 seconds after shutdown, giving up and killing anyway.");
829 break;
830 }
831 Thread.Sleep(100);
832 }
833 tasks.Add((backend, backend.AbstractBackend.DoShutdownNow()));
834 })));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 src\Backends\BackendHandler.cs (line 831)
828 Logs.Info($"Backend {backend.ID} ({backend.AbstractBackend.HandlerTypeData.Name}) has been locked in use for at least 5 seconds after shutdown, giving up and killing anyway.");
829 break;
830 }
831 Thread.Sleep(100);
832 }
833 tasks.Add((backend, backend.AbstractBackend.DoShutdownNow()));
834 })));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 38 hits
📄 src\BuiltinExtensions\AutoWebUIBackend\AutoWebUISelfStartBackend.cs (line 45)
42 Status = BackendStatus.ERRORED;
43 return;
44 }
45 string scrContent = File.ReadAllText(settings.StartScript);
46 if (!scrContent.Contains("%*") && !scrContent.Contains("%~")) // on Windows, it's only valid if you forward swarm's CLI args
47 {
48 Logs.Error($"Refusing init of AutoWebUI with 'webui-user.bat' target script. Please use the 'webui.bat' script instead. (If webui-user.bat usage is intentional, please forward CLI args, eg 'COMMANDLINE_ARGS=%*'.");
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\BuiltinExtensions\ImageBatchTool\ImageBatchToolExtension.cs (line 130)
127 {
128 break;
129 }
130 Image image = new(File.ReadAllBytes(file), MediaType.GetByExtension(file.AfterLast('.')));
131 ISImage imgData = image.ToIS;
132 T2IParamInput param = baseParams.Clone();
133 void setRes(int width, int height)
💬 Async overload available for File.ReadAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 28 hits
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIRedirectHelper.cs (line 45)
42 try
43 {
44 using CancellationTokenSource cancel = Utilities.TimedCancel(TimeSpan.FromMinutes(1));
45 result = backend.Client.GetAsync($"{backend.APIAddress}/object_info", cancel.Token).Result.Content.ReadAsStringAsync().Result.ParseToJson();
46 }
47 catch (Exception ex)
48 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIRedirectHelper.cs (line 45)
42 try
43 {
44 using CancellationTokenSource cancel = Utilities.TimedCancel(TimeSpan.FromMinutes(1));
45 result = backend.Client.GetAsync($"{backend.APIAddress}/object_info", cancel.Token).Result.Content.ReadAsStringAsync().Result.ParseToJson();
46 }
47 catch (Exception ex)
48 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 4 hits
📄 src\BuiltinExtensions\GridGenerator\GridGeneratorExtension.cs (line 273)
270 if (requests < Program.ServerSettings.Backends.MaxRequestsForcedOrder)
271 {
272 Logs.Debug($"Grid Gen micro-pausing to maintain order as {requests} < {Program.ServerSettings.Backends.MaxRequestsForcedOrder}");
273 Task.Delay(20).Wait(); // Tiny few-ms delay to encourage tasks retaining order.
274 }
275 return t;
276 };
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 src\WebAPI\T2IAPI.cs (line 413)
410 })));
411 if (Program.Backends.QueuedRequests < Program.ServerSettings.Backends.MaxRequestsForcedOrder)
412 {
413 Task.Delay(20).Wait(); // Tiny few-ms delay to encourage tasks retaining order.
414 }
415 }
416 while (tasks.Any())
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS037 HttpClient instantiated directly 2 hits
📄 src\Backends\NetworkBackendUtils.cs (line 24)
21 /// <summary>Create and preconfigure a basic <see cref="HttpClient"/> instance to make web requests with.</summary>
22 public static HttpClient MakeHttpClient(int timeoutMinutes = 10)
23 {
24 HttpClient client = new(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(10), MaxConnectionsPerServer = 1000 });
25 client.DefaultRequestHeaders.UserAgent.ParseAdd($"SwarmUI/{Utilities.Version}");
26 client.Timeout = TimeSpan.FromMinutes(timeoutMinutes);
27 return client;
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 src\Backends\NetworkBackendUtils.cs (line 24)
21 /// <summary>Create and preconfigure a basic <see cref="HttpClient"/> instance to make web requests with.</summary>
22 public static HttpClient MakeHttpClient(int timeoutMinutes = 10)
23 {
24 HttpClient client = new(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(10), MaxConnectionsPerServer = 1000 });
25 client.DefaultRequestHeaders.UserAgent.ParseAdd($"SwarmUI/{Utilities.Version}");
26 client.Timeout = TimeSpan.FromMinutes(timeoutMinutes);
27 return client;
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS038 HttpContext stored in a field 2 hits
📄 src\Utils\GeneratePageModel.cs (line 9)
6
7public class GeneratePageModel
8{
9 public HttpContext HttpContext;
10
11 public string AlwaysRefreshOnLoad => Program.ServerSettings.Backends.AlwaysRefreshOnLoad ? "true" : "false";
12
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
📄 src\Utils\GeneratePageModel.cs (line 9)
6
7public class GeneratePageModel
8{
9 public HttpContext HttpContext;
10
11 public string AlwaysRefreshOnLoad => Program.ServerSettings.Backends.AlwaysRefreshOnLoad ? "true" : "false";
12
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
SS041 Unnecessary enumerable materialization 10 hits
📄 src\WebAPI\APICallReflectBuilder.cs (line 25)
22 [typeof(bool)] = input => (bool.TryParse(input.ToString(), out bool output), output),
23 [typeof(byte)] = input => (byte.TryParse(input.ToString(), out byte output), output),
24 [typeof(char)] = input => (char.TryParse(input.ToString(), out char output), output),
25 [typeof(string[])] = input => (true, input.ToList().Select(j => j.ToString()).ToArray())
26 };
27
28 public static APICall BuildFor(object obj, MethodInfo method, bool isUserUpdate, PermInfo permission)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\Core\ExtensionsManager.cs (line 78)
75 Logs.CriticalLoadError($"Failed to delete extension folder SwarmUI/{deletable}: {ex.ReadableString()}, you will need to remove it manually");
76 }
77 }
78 foreach (Type extType in AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(x => x.GetTypes()).Where(t => typeof(Extension).IsAssignableFrom(t) && !t.IsAbstract))
79 {
80 bool isCore = extType.Namespace.StartsWith("SwarmUI.");
81 string[] possible = isCore ? builtins : extras;
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS048 Locking on discouraged object (string, Type, this) 4 hits
📄 src\Media\ImageFile.cs (line 67)
64 {
65 if (_CacheISImg is null)
66 {
67 lock (this)
68 {
69 _CacheISImg ??= ISImage.Load(RawData);
70 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 src\Core\WebServer.cs (line 61)
58 {
59 if (Value is null)
60 {
61 lock (this)
62 {
63 Value ??= Getter();
64 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS051 Locking on mutable reference 150 hits
📄 src\BuiltinExtensions\AutoWebUIBackend\AutoWebUIBackendExtension.cs (line 27)
24
25 public static void LoadSamplerList(List<string> newSamplers)
26 {
27 lock (ExtBackLock)
28 {
29 Samplers = [.. Samplers.Union(newSamplers).Distinct()];
30 }
💬 A lock was obtained on ExtBackLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\Accounts\Permissions.cs (line 21)
18 {
19 throw new InvalidOperationException($"Permission key '{perm.ID}' is already registered.");
20 }
21 lock (OrderedKeys)
22 {
23 OrderedKeys.Add(perm.ID);
24 }
💬 A lock was obtained on OrderedKeys but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 4 hits
📄 src\BuiltinExtensions\ImageBatchTool\ImageBatchToolExtension.cs (line 110)
107 {
108 Logs.Error($"Image generation failed: {tasks[i].Exception}");
109 }
110 tasks.RemoveAt(i--);
111 }
112 }
113 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\WebAPI\T2IAPI.cs (line 309)
306 {
307 Logs.Error($"Image generation failed: {tasks[i].Exception}");
308 }
309 tasks.RemoveAt(i--);
310 }
311 }
312 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 44 hits
📄 src\BuiltinExtensions\AutoWebUIBackend\AutoWebUIAPIAbstractBackend.cs (line 86)
83 {
84 lora = lora.BeforeLast('.');
85 }
86 promptAdd += $"<lora:{lora}:{loraWeights[i]}>";
87 }
88 }
89 JObject toSend = new()
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Utils\WebUtil.cs (line 78)
75 string basic = "";
76 foreach (NvidiaUtil.NvidiaInfo info in nv)
77 {
78 basic += $"{(info == bestGpu ? "* " : "")}GPU {info.ID}: <b>{info.GPUName}</b>, <b>{info.TotalMemory}</b> VRAM\n<br>";
79 }
80 if (nv.Length > 1)
81 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 10 hits
📄 src\Utils\Utilities.cs (line 308)
305 public static async Task<byte[]> ReceiveData(this WebSocket socket, long maxBytes, CancellationToken limit)
306 {
307 byte[] buffer = new byte[8192];
308 using MemoryStream ms = new();
309 WebSocketReceiveResult result;
310 do
311 {
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIRedirectHelper.cs (line 332)
329 {
330 try
331 {
332 using MemoryStream memStream = new();
333 await context.Request.Body.CopyToAsync(memStream);
334 byte[] data = memStream.ToArray();
335 JObject parsed = StringConversionHelper.UTF8Encoding.GetString(data).ParseToJson();
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 6 hits
📄 src\WebAPI\T2IAPI.cs (line 128)
125 });
126 Task handle = API.RunWebsocketHandlerCallWS(GenT2I_Internal, session, (images, rawInput, data, 0), socket);
127 tasks.TryAdd(handle, handle);
128 while (Volatile.Read(ref retain) || tasks.Any())
129 {
130 await Task.WhenAny(tasks.Keys.ToList());
131 foreach (Task t in tasks.Keys.Where(t => t.IsCompleted).ToList())
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 src\Utils\Utilities.cs (line 99)
96 return;
97 }
98 }
99 if (Program.Backends.T2IBackendRequests.Any() || Program.Backends.QueuedRequests > 0 || Program.Backends.AllBackends.Values.Any(b => b.CheckIsInUseAtAll))
100 {
101 return;
102 }
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)

cecil

376 total diagnostics across 7 rules

SS003 Integer divided by integer causing implicit rounding 48 hits
📄 Mono\MergeSort.cs (line 49)
46 if (end - start < 2)
47 return;
48
49 int middle = (end + start) / 2;
50 TopDownSplitMerge (b, a, start, middle);
51 TopDownSplitMerge (b, a, middle, end);
52 TopDownMerge (a, b, start, middle, end);
💬 The operands in the divisive expression (end + start) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Mono.Cecil\AssemblyNameReference.cs (line 203)
200 if (pk_token == "null")
201 break;
202
203 name.PublicKeyToken = new byte [pk_token.Length / 2];
204 for (int j = 0; j < name.PublicKeyToken.Length; j++)
205 name.PublicKeyToken [j] = Byte.Parse (pk_token.Substring (j * 2, 2), NumberStyles.HexNumber);
206
💬 The operands in the divisive expression pk_token.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 44 hits
📄 Mono.Cecil.Metadata\Buffers.cs (line 447)
444 public uint GetBlobIndex (ByteBuffer blob)
445 {
446 uint index;
447 if (blobs.TryGetValue (blob, out index))
448 return index;
449
450 index = (uint) base.position;
💬 Type ByteBuffer is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Mono.Cecil.Metadata\Buffers.cs (line 452)
449
450 index = (uint) base.position;
451 WriteBlob (blob);
452 blobs.Add (blob, index);
453 return index;
454 }
455
💬 Type ByteBuffer is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 80 hits
📄 Mono\Disposable.cs (line 28)
25 }
26 }
27
28 struct Disposable<T> : IDisposable where T : class, IDisposable {
29
30 internal readonly T value;
31 readonly bool owned;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Disposable. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Mono.Collections.Generic\Collection.cs (line 350)
347 return new Enumerator (this);
348 }
349
350 public struct Enumerator : IEnumerator<T>, IDisposable {
351
352 Collection<T> collection;
353 T current;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Enumerator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 64 hits
📄 Mono.Cecil\TypeReference.cs (line 324)
321
322 public static bool IsTypeSpecification (this TypeReference type)
323 {
324 switch (type.etype) {
325 case ElementType.Array:
326 case ElementType.ByRef:
327 case ElementType.CModOpt:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Mono.Cecil\AssemblyWriter.cs (line 1273)
1270 return exported_type.DeclaringType.MetadataToken;
1271
1272 var scope = exported_type.Scope;
1273 switch (scope.MetadataToken.TokenType) {
1274 case TokenType.AssemblyRef:
1275 return scope.MetadataToken;
1276 case TokenType.ModuleRef:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 104 hits
📄 Mono.Security.Cryptography\CryptoConvert.cs (line 238)
235 if (offset >= blob.Length)
236 throw new ArgumentException ("blob is too small.");
237
238 switch (blob [offset]) {
239 case 0x00:
240 // this could be a public key inside an header
241 // like "sn -e" would produce
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Mono.Cecil\AssemblyNameReference.cs (line 191)
188 if (parts.Length != 2)
189 throw new ArgumentException ("Malformed name");
190
191 switch (parts [0].ToLowerInvariant ()) {
192 case "version":
193 name.Version = new Version (parts [1]);
194 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 Mono.Collections.Generic\Collection.cs (line 367)
364 CheckState ();
365
366 if (next <= 0)
367 throw new InvalidOperationException ();
368
369 return current;
370 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Mono.Collections.Generic\Collection.cs (line 367)
364 CheckState ();
365
366 if (next <= 0)
367 throw new InvalidOperationException ();
368
369 return current;
370 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS066 Disposable field is not disposed 32 hits
📄 Mono.Cecil\ModuleDefinition.cs (line 261)
258 internal ushort subsystem_minor = 0;
259 internal uint timestamp;
260
261 internal AssemblyDefinition assembly;
262 MethodDefinition entry_point;
263 bool entry_point_set;
264
💬 Disposable field assembly in type ModuleDefinition is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Mono.Cecil.Cil\PortablePdb.cs (line 521)
518
519 public sealed class EmbeddedPortablePdbWriter : ISymbolWriter {
520
521 readonly Stream stream;
522 readonly PortablePdbWriter writer;
523
524 internal EmbeddedPortablePdbWriter (Stream stream, PortablePdbWriter writer)
💬 Disposable field stream in type EmbeddedPortablePdbWriter is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

RestSharp

340 total diagnostics across 9 rules

SS001 Async method with void return type 12 hits
No source samples extracted
SS002 Use DateTime.UtcNow instead of DateTime.Now 88 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 12 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 20 hits
No source samples extracted
SS019 Switch is missing default label 12 hits
No source samples extracted
SS033 Async overload is available 42 hits
No source samples extracted
SS037 HttpClient instantiated directly 48 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 24 hits
No source samples extracted
SS066 Disposable field is not disposed 82 hits
No source samples extracted

Vue.NetCore

334 total diagnostics across 17 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 140 hits
📄 vol.api.sqlsugar\VOL.Core\Services\Logger.cs (line 29)
26 public static class Logger
27 {
28 public static ConcurrentQueue<Sys_Log> loggerQueueData = new ConcurrentQueue<Sys_Log>();
29 private static DateTime lastClearFileDT = DateTime.Now.AddDays(-1);
30 private static string _loggerPath = AppSetting.DownLoadPath + "Logger\\Queue\\";
31 static Logger()
32 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 vol.api.sqlsugar\VOL.Core\Extensions\StringExtension.cs (line 52)
49 if (string.IsNullOrEmpty(urlPath))
50 return null;
51 userId = userId ?? UserContext.Current.UserInfo.User_Id;
52 return $"{urlPath}{(urlPath.IndexOf("?token") > 0 ? "&" : "?")}uid={userId}&rt_v={DateTime.Now.ToString("HHmmss")}";
53 // return urlPath + ((urlPath.IndexOf("?token") > 0 ? "&" : "?") + "uid=" + userId);
54 }
55
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 8 hits
📄 vol.api.sqlsugar\VOL.Core\Extensions\StringExtension.cs (line 34)
31 /// <returns></returns>
32 public static long GetTimeStamp(this DateTime dateTime)
33 {
34 return (dateTime.ToUniversalTime().Ticks - longTime) / samllTime;
35 }
36 /// <summary>
37 /// 时间戳转换成日期
💬 The operands in the divisive expression (dateTime.ToUniversalTime().Ticks - longTime) / samllTime are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 vol.api.sqlsugar\VOL.Core\Filters\ApiAuthorizeFilter.cs (line 75)
72 DateTime expDate = context.HttpContext.User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Exp)
73 .Select(x => x.Value).FirstOrDefault().GetTimeSpmpToDate();
74 //动态标识刷新token(2021.05.01)
75 if ((expDate - DateTime.Now).TotalMinutes < AppSetting.ExpMinutes/ 3 && context.HttpContext.Request.Path != replaceTokenPath)
76 {
77 context.HttpContext.Response.Headers["vol_exp"]= "1";
78 }
💬 The operands in the divisive expression AppSetting.ExpMinutes/ 3 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 vol.api.sqlsugar\VOL.Core\UserManager\RoleContext.cs (line 88)
85 /// <param name="roleId"></param>
86 private static List<RoleNodes> GetChildren(List<RoleNodes> roles, int roleId)
87 {
88 List<RoleNodes> rolesChildren = roles.Where(x => x.Id == roleId).Distinct().ToList();
89
90 for (int i = 0; i < rolesChildren.Count; i++)
91 {
💬 Type RoleNodes is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 vol.api.sqlsugar\VOL.Core\UserManager\RoleContext.cs (line 93)
90 for (int i = 0; i < rolesChildren.Count; i++)
91 {
92 RoleNodes node = rolesChildren[i];
93 var children = roles.Where(x => x.ParentId == node.Id && !rolesChildren.Any(c => c.Id == x.Id)).Distinct().ToList();
94 rolesChildren.AddRange(children);
95 }
96 return rolesChildren;
💬 Type RoleNodes is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 8 hits
📄 vol.api.sqlsugar\VOL.Core\Const\HtmlElementType.cs (line 7)
4
5namespace VOL.Core.Const
6{
7 public struct HtmlElementType
8 {
9 public const string drop = "drop";
10 public const string droplist = "droplist";
💬 Implement Equals(), GetHashCode() and ToString() methods on struct HtmlElementType. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 vol.api.sqlsugar\VOL.Core\Const\SqlDbTypeName.cs (line 7)
4
5namespace VOL.Core.Const
6{
7 public struct SqlDbTypeName
8 {
9 public const string NVarChar = "nvarchar";
10 public const string VarChar = "varchar";
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SqlDbTypeName. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 vol.api.sqlsugar\VOL.Core\Quartz\QuartzNETExtension.cs (line 263)
260 return new { status = false, msg = errorMsg };
261 }
262 object result = null;
263 switch (action)
264 {
265 case JobAction.删除:
266
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 vol.api.sqlsugar\VOL.Core\Quartz\QuartzNETExtension.cs (line 263)
260 return new { status = false, msg = errorMsg };
261 }
262 object result = null;
263 switch (action)
264 {
265 case JobAction.删除:
266
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 6 hits
📄 vol.api.sqlsugar\VOL.Core\Extensions\StringExtension.cs (line 389)
386
387 public static object ParseTo(this string str, string type)
388 {
389 switch (type)
390 {
391 case "System.Boolean":
392 return ToBoolean(str);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 vol.api.sqlsugar\VOL.Core\Quartz\QuartzNETExtension.cs (line 263)
260 return new { status = false, msg = errorMsg };
261 }
262 object result = null;
263 switch (action)
264 {
265 case JobAction.删除:
266
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 vol.api.sqlsugar\VOL.Builder\Services\Core\Partial\Sys_TableInfoService.cs (line 54)
51 webProject = ProjectPath.GetLastIndexOfDirectoryName(".WebApi") ?? ProjectPath.GetLastIndexOfDirectoryName("Api") ?? ProjectPath.GetLastIndexOfDirectoryName(".Web");
52 if (webProject == null)
53 {
54 throw new Exception("未获取到以.WebApi结尾的项目名称,无法创建页面");
55 }
56 return webProject;
57 }
💬 An exception is thrown from the getter of property WebProject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 vol.api.sqlsugar\VOL.Builder\Services\Core\Partial\Sys_TableInfoService.cs (line 68)
65 apiNameSpace = ProjectPath.GetLastIndexOfDirectoryName(".WebApi");
66 if (apiNameSpace == null)
67 {
68 throw new Exception("未获取到以.WebApi,无法创建Api控制器");
69 }
70 return apiNameSpace;
71 }
💬 An exception is thrown from the getter of property ApiNameSpace (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 8 hits
📄 vol.api.sqlsugar\VOL.Core\Quartz\HttpResultfulJob.cs (line 66)
63 _taskOptions.LastRunTime = DateTime.Now;
64 DbManger.SqlSugarClient.Update(_taskOptions, new string[] { "LastRunTime" });
65
66 DbManger.SqlSugarClient.SaveChanges();
67 }
68
69 Dictionary<string, string> header = new Dictionary<string, string>();
💬 Async overload available for SqlSugarExtension.SaveChanges (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 vol.api.sqlsugar\VOL.Core\Quartz\HttpResultfulJob.cs (line 105)
102 EndDate = DateTime.Now
103 };
104 DbManger.SqlSugarClient.Add(log);
105 DbManger.SqlSugarClient.SaveChanges();
106 }
107 catch (Exception ex)
108 {
💬 Async overload available for SqlSugarExtension.SaveChanges (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 12 hits
📄 vol.api.sqlsugar\VOL.Core\Quartz\QuartzNETExtension.cs (line 63)
60 {
61 return false;
62 }
63 JobKey jobKey = jobKeys.Where(s => scheduler.GetTriggersOfJob(s).Result
64 .Any(x => (x as CronTriggerImpl).Name == taskName))
65 .FirstOrDefault();
66 if (jobKey == null)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 vol.api.sqlsugar\VOL.Core\Quartz\QuartzNETExtension.cs (line 240)
237 string groupName = "group";
238 string taskName = taskOptions.Id.ToString();
239 IScheduler scheduler = await schedulerFactory.GetScheduler();
240 List<JobKey> jobKeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName)).Result.ToList();
241 if (jobKeys == null || jobKeys.Count() == 0)
242 {
243 errorMsg = $"未找到分组[{groupName}]";
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS038 HttpContext stored in a field 2 hits
📄 vol.api.sqlsugar\VOL.Sys\Services\System\Partial\Sys_UserService.cs (line 25)
22{
23 public partial class Sys_UserService
24 {
25 private Microsoft.AspNetCore.Http.HttpContext _context;
26 private ISys_UserRepository _repository;
27 [ActivatorUtilitiesConstructor]
28 public Sys_UserService(IHttpContextAccessor httpContextAccessor, ISys_UserRepository repository)
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
📄 vol.api.sqlsugar\VOL.Sys\Services\System\Partial\Sys_UserService.cs (line 25)
22{
23 public partial class Sys_UserService
24 {
25 private Microsoft.AspNetCore.Http.HttpContext _context;
26 private ISys_UserRepository _repository;
27 [ActivatorUtilitiesConstructor]
28 public Sys_UserService(IHttpContextAccessor httpContextAccessor, ISys_UserRepository repository)
💬 HttpContext was stored in a field. Use IHttpContextAccessor instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS038-HttpContextStoredInField.md)
SS040 Unused result on immutable object 6 hits
📄 vol.api.sqlsugar\VOL.Core\Extensions\ConvertJsonExtension.cs (line 186)
183 {
184 jsonString += ToJson(item) + ",";
185 }
186 jsonString.Remove(jsonString.Length - 1, jsonString.Length);
187 return jsonString + "]";
188 }
189 #endregion
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
📄 vol.api.sqlsugar\VOL.Core\Extensions\ConvertJsonExtension.cs (line 204)
201 {
202 jsonString = ToJson(item.ToString()) + ",";
203 }
204 jsonString.Remove(jsonString.Length - 1, jsonString.Length);
205 return jsonString + "]";
206 }
207 #endregion
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
SS044 Attribute must specify [AttributeUsage] 16 hits
📄 vol.api.sqlsugar\VOL.Entity\AttributeManager\PermissionTableAttribute.cs (line 5)
2
3namespace VOL.Entity.AttributeManager
4{
5 public class PermissionTableAttribute : Attribute
6 {
7 /// <summary>
8 /// 需要控制权限的表名与Sys_Menu表的表名必须一致
💬 PermissionTableAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 vol.api.sqlsugar\VOL.Entity\AttributeManager\EntityAttribute.cs (line 9)
6
7namespace VOL.Entity
8{
9 public class EntityAttribute : Attribute
10 {
11 /// <summary>
12 /// 真实表名(数据库表名,若没有填写默认实体为表名)
💬 EntityAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 82 hits
📄 vol.api.sqlsugar\VOL.Core\BaseProvider\ServiceBase.cs (line 142)
139 Dictionary<string, QueryOrderBy> sortDic = new Dictionary<string, QueryOrderBy>();
140 foreach (var name in sortArr)
141 {
142 sortDic[name] = pageData.Order?.ToLower() == _asc ? QueryOrderBy.Asc : QueryOrderBy.Desc;
143 }
144 return sortDic;
145 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 vol.api.sqlsugar\VOL.Core\BaseProvider\ServiceBase.cs (line 150)
147 {
148 return new Dictionary<string, QueryOrderBy>() { {
149 pageData.Sort,
150 pageData.Order?.ToLower() == _asc? QueryOrderBy.Asc: QueryOrderBy.Desc
151 } };
152 }
153 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS051 Locking on mutable reference 10 hits
📄 vol.api.sqlsugar\VOL.Core\Infrastructure\DictionaryManager.cs (line 85)
82 return _dictionaries;
83 }
84
85 lock (_dicObj)
86 {
87 if (_dicVersionn != "" && _dictionaries != null && _dicVersionn == cacheService.Get(Key)) return _dictionaries;
88 _dictionaries = DBServerProvider.DbContext
💬 A lock was obtained on _dicObj but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 vol.api.sqlsugar\VOL.Core\UserManager\RoleContext.cs (line 30)
27 {
28 return _roles;
29 }
30 lock (_RoleObj)
31 {
32 if (_RoleVersionn != "" && _roles != null && _RoleVersionn == cacheService.Get(Key)) return _roles;
33 _roles = DBServerProvider.DbContext
💬 A lock was obtained on _RoleObj but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS056 HttpRequest.Form read synchronously 2 hits
📄 vol.api.sqlsugar\VOL.Core\Extensions\RequestExtension.cs (line 54)
51 if (context == null)
52 return null;
53 if (context.Request.Method == "POST")
54 return context.Request.Form[parameter].ToString();
55 else
56 return context.Request.Query[parameter].ToString();
57 }
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
📄 vol.api.sqlsugar\VOL.Core\Extensions\RequestExtension.cs (line 54)
51 if (context == null)
52 return null;
53 if (context.Request.Method == "POST")
54 return context.Request.Form[parameter].ToString();
55 else
56 return context.Request.Query[parameter].ToString();
57 }
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
SS058 String concatenated in a loop 10 hits
📄 vol.api.sqlsugar\VOL.Core\Utilities\VierificationCode.cs (line 30)
27 return RandomText();
28 }
29 temp = t;
30 code += _chars[t];
31 }
32 return code;
33 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 vol.api.sqlsugar\VOL.Core\Quartz\QuartzAuthorization.cs (line 47)
44 for (int i = 0; i < s.Length; i++)
45 {
46 string btos = s[i].ToString("X2");
47 md5str += btos;
48 }
49 return md5str;
50 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 6 hits
📄 vol.api.sqlsugar\VOL.WebApi\Controllers\Sys\Partial\Sys_UserController.cs (line 38)
35 public partial class Sys_UserController
36 {
37 private ISys_UserRepository _userRepository;
38 private ICacheService _cache;
39 [ActivatorUtilitiesConstructor]
40 public Sys_UserController(
41 ISys_UserService userService,
💬 Disposable field _cache in type Sys_UserController is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 vol.api.sqlsugar\VOL.WebApi\Controllers\Hubs\HomePageMessageHub.cs (line 22)
19 /// </summary>
20 public class HomePageMessageHub : Hub
21 {
22 private readonly ICacheService _cacheService;
23
24
25 private static ConcurrentDictionary<string, string> _connectionIds = new ConcurrentDictionary<string, string>();
💬 Disposable field _cacheService in type HomePageMessageHub is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

MemoryPack

328 total diagnostics across 12 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 10 hits
📄 sandbox\Benchmark\Models\BinaryPackModels\NeuralNetworkLayerModel.cs (line 66)
63 Biases[i] = (float)RandomProvider.NextDouble();
64 }
65 Activation = ActivationType.Sigmoid;
66 LastUpdateTime = DateTime.Now;
67 }
68
69 /// <inheritdoc/>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 sandbox\Benchmark\Micro\Hyper.cs (line 26)
23 // Gn
24 A = i,
25 B = i,
26 C = DateTime.Now.Date,
27 D = (uint)i,
28 E = i,
29 F = DateTime.Now - DateTime.Now.AddDays(-1),
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 18 hits
📄 src\MemoryPack.Core\Compression\BitPackFormatter.cs (line 118)
115 return;
116 }
117
118 var readCount = ((length - 1) / 32) + 1;
119 var requireSize = readCount * 4;
120 if (reader.Remaining < requireSize)
121 {
💬 The operands in the divisive expression (length - 1) / 32 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\MemoryPack.Core\Compression\BitPackFormatter.cs (line 118)
115 return;
116 }
117
118 var readCount = ((length - 1) / 32) + 1;
119 var requireSize = readCount * 4;
120 if (reader.Remaining < requireSize)
121 {
💬 The operands in the divisive expression (length - 1) / 32 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS005 Equals() and GetHashCode() not implemented together 2 hits
📄 tests\MemoryPack.Tests\ArrayFormatterTest.cs (line 201)
198}
199
200[MemoryPackable]
201public partial class ObjectValue : IEquatable<ObjectValue>
202{
203 public int Value { get; }
204
💬 Equals() and GetHashcode() must be implemented together on ObjectValue (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 tests\MemoryPack.Tests\ArrayFormatterTest.cs (line 201)
198}
199
200[MemoryPackable]
201public partial class ObjectValue : IEquatable<ObjectValue>
202{
203 public int Value { get; }
204
💬 Equals() and GetHashcode() must be implemented together on ObjectValue (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 sandbox\SandboxConsoleApp\Program.cs (line 91)
88 }
89 public override int GetHashCode()
90 {
91 return System.HashCode.Combine(x, y, z);
92 }
93}
94[MemoryPackable]
💬 GetHashCode() refers to mutable field x (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 sandbox\SandboxConsoleApp\Program.cs (line 91)
88 }
89 public override int GetHashCode()
90 {
91 return System.HashCode.Combine(x, y, z);
92 }
93}
94[MemoryPackable]
💬 GetHashCode() refers to mutable field y (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 242 hits
📄 src\MemoryPack.Generator\EquatableArray.cs (line 6)
3
4namespace MemoryPack.Generator;
5
6public readonly struct EquatableArray<T> : IEquatable<EquatableArray<T>>, IEnumerable<T>
7 where T : IEquatable<T>
8{
9 readonly T[]? array;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EquatableArray. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\MemoryPack.Core\Compression\BrotliDecompressor.cs (line 8)
5
6namespace MemoryPack.Compression;
7
8public struct BrotliDecompressor : IDisposable
9{
10 ReusableReadOnlySequenceBuilder? sequenceBuilder;
11
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BrotliDecompressor. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 4 hits
📄 src\MemoryPack.Generator\MemoryPackGenerator.Emitter.cs (line 305)
302 Members = originalMembers;
303 }
304
305 var classOrStructOrRecord = (IsRecord, IsValueType) switch
306 {
307 (true, true) => "record struct",
308 (true, false) => "record",
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\MemoryPack.Generator\MemoryPackGenerator.Emitter.cs (line 317)
314 var containingType = Symbol.ContainingType;
315 while (containingType is not null)
316 {
317 containingTypeDeclarations.Add((containingType.IsRecord, containingType.IsValueType) switch
318 {
319 (true, true) => $"partial record struct {containingType.Name}",
320 (true, false) => $"partial record {containingType.Name}",
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS030 Exception thrown from Equals 4 hits
📄 sandbox\Benchmark\Models\BinaryPackModels\JsonResponseModel.cs (line 400)
397 public bool Equals(ImageModel? other)
398 {
399 if (other is null) return false;
400 if (ReferenceEquals(this, other)) throw new InvalidOperationException();
401 return
402 Url?.Equals(other.Url) == true &&
403 Width == other.Width &&
💬 An exception is thrown from the Equals(ImageModel?) method in type ImageModel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
📄 sandbox\Benchmark\Models\BinaryPackModels\JsonResponseModel.cs (line 131)
128 public bool Equals(ApiModelContainer? other)
129 {
130 if (other is null) return false;
131 if (ReferenceEquals(this, other)) throw new InvalidOperationException();
132 return
133 Id?.Equals(other.Id) == true &&
134 Type?.Equals(other.Type) == true &&
💬 An exception is thrown from the Equals(ApiModelContainer?) method in type ApiModelContainer (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
SS033 Async overload is available 2 hits
📄 sandbox\SandboxWebApp\Program.cs (line 33)
30
31app.MapControllers();
32
33app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 sandbox\SandboxWebApp\Program.cs (line 33)
30
31app.MapControllers();
32
33app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS044 Attribute must specify [AttributeUsage] 6 hits
📄 src\MemoryPack.Core\Internal\PreserveAttribute.cs (line 5)
2
3// Preserve for Unity IL2CPP(internal but used for code generator)
4
5public sealed class PreserveAttribute : System.Attribute
6{
7}
💬 PreserveAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\MemoryPack.Core\Internal\PreserveAttribute.cs (line 5)
2
3// Preserve for Unity IL2CPP(internal but used for code generator)
4
5public sealed class PreserveAttribute : System.Attribute
6{
7}
💬 PreserveAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS047 LINQ traversal before filter 2 hits
📄 src\MemoryPack.Generator\MemoryPackGenerator.Parser.cs (line 81)
78 this.TypeName = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
79 this.Constructor = ChooseConstructor(symbol, reference);
80
81 this.Members = symbol.GetAllMembers() // iterate includes parent type
82 .Where(x => x is (IFieldSymbol or IPropertySymbol) and { IsStatic: false, IsImplicitlyDeclared: false, CanBeReferencedByName: true })
83 .Reverse()
84 .DistinctBy(x => x.Name) // remove duplicate name(new)
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 src\MemoryPack.Generator\MemoryPackGenerator.Parser.cs (line 81)
78 this.TypeName = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
79 this.Constructor = ChooseConstructor(symbol, reference);
80
81 this.Members = symbol.GetAllMembers() // iterate includes parent type
82 .Where(x => x is (IFieldSymbol or IPropertySymbol) and { IsStatic: false, IsImplicitlyDeclared: false, CanBeReferencedByName: true })
83 .Reverse()
84 .DistinctBy(x => x.Name) // remove duplicate name(new)
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 tests\MemoryPack.Tests\NonGenerics.cs (line 30)
27 [Fact]
28 public async Task StreamCheck()
29 {
30 using var ms = new MemoryStream();
31
32 // Generic version works
33 await MemoryPackSerializer.SerializeAsync(ms, new Item());
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 tests\MemoryPack.Tests\NonGenerics.cs (line 30)
27 [Fact]
28 public async Task StreamCheck()
29 {
30 using var ms = new MemoryStream();
31
32 // Generic version works
33 await MemoryPackSerializer.SerializeAsync(ms, new Item());
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 24 hits
📄 src\MemoryPack.Core\MemoryPackSerializer.StateBackup.cs (line 26)
23 readonly bool _resetReaderState;
24 readonly bool _resetWriterState;
25 readonly SerializerWriterThreadStaticState? _threadStaticState;
26 readonly MemoryPackWriterOptionalState? _threadStaticWriterOptionalState;
27 readonly MemoryPackReaderOptionalState? _threadStaticReaderOptionalState;
28
29 internal StateSnapshot(bool resetReaderState, bool resetWriterState)
💬 Disposable field _threadStaticWriterOptionalState in type StateSnapshot is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\MemoryPack.Core\MemoryPackSerializer.StateBackup.cs (line 27)
24 readonly bool _resetWriterState;
25 readonly SerializerWriterThreadStaticState? _threadStaticState;
26 readonly MemoryPackWriterOptionalState? _threadStaticWriterOptionalState;
27 readonly MemoryPackReaderOptionalState? _threadStaticReaderOptionalState;
28
29 internal StateSnapshot(bool resetReaderState, bool resetWriterState)
30 {
💬 Disposable field _threadStaticReaderOptionalState in type StateSnapshot is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

YamlDotNet

326 total diagnostics across 9 rules

SS003 Integer divided by integer causing implicit rounding 20 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 100 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 60 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 60 hits
No source samples extracted
SS018 Switch does not handle all enum options 20 hits
No source samples extracted
SS019 Switch is missing default label 44 hits
No source samples extracted
SS023 Exception thrown from property getter 10 hits
No source samples extracted
SS057 Collection manipulated during traversal 10 hits
No source samples extracted
SS058 String concatenated in a loop 2 hits
No source samples extracted

Windows-Auto-Night-Mode

284 total diagnostics across 14 rules

SS001 Async method with void return type 26 hits
📄 AutoDarkModeSvc\Communication\AsyncPipeServer.cs (line 125)
122 });
123 }
124
125 private async void HandleClient()
126 {
127 Tuple<string, string> result = await HandleRequest();
128 // if no string was received, add the worker back to the pool
💬 Method HandleClient is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 AutoDarkModeSvc\Communication\AsyncPipeServer.cs (line 234)
231 return new(msg, responderPipeId);
232 }
233
234 private async void HandleResponse(string msg, string responderPipeId)
235 {
236 // for the response timeout, we don't want to wait forever, so it also adheres to streamTimeout
237 using CancellationTokenSource connectTimeoutTokenSource = new();
💬 Method HandleResponse is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 148 hits
📄 AutoDarkModeLib\Configs\LocationData.cs (line 23)
20
21public class LocationData
22{
23 public DateTime Sunrise { get; set; } = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 7, 0, 0);
24 public DateTime Sunset { get; set; } = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 0, 0);
25 public double Lat { get; set; }
26 public double Lon { get; set; }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 AutoDarkModeLib\Configs\LocationData.cs (line 23)
20
21public class LocationData
22{
23 public DateTime Sunrise { get; set; } = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 7, 0, 0);
24 public DateTime Sunset { get; set; } = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 19, 0, 0);
25 public double Lat { get; set; }
26 public double Lon { get; set; }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 20 hits
📄 AutoDarkModeSvc\Timers\TimerFrequency.cs (line 25)
22 public static int Main { get; set; } = 60000;
23 // Short Timer for operations that need to be performed a little bit more often
24 // By default this is half of main
25 public static int Short { get; set; } = Main > 1 ? (Main/2) : 1;
26 // IO Timer is 2h
27 public const int IO = 7200000;
28 //location Timer is 1h
💬 The operands in the divisive expression Main/2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 AutoDarkModeSvc\Handlers\UpdateHandler.cs (line 664)
661 {
662 if (percent % 10 == 0)
663 {
664 string mbReceived = (receivedBytes / 1000000).ToString();
665 string mbTotal = (totalBytes / 1000000).ToString();
666 nfi.NumberDecimalSeparator = ".";
667 Progress = percent;
💬 The operands in the divisive expression receivedBytes / 1000000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 8 hits
📄 AutoDarkModeLib\ComponentSettings\Base\ScriptSwitchSettings.cs (line 80)
77
78 public override int GetHashCode()
79 {
80 return HashCode.Combine(Name, Command, ArgsLight, ArgsDark);
81 }
82}
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 AutoDarkModeLib\ComponentSettings\Base\ScriptSwitchSettings.cs (line 80)
77
78 public override int GetHashCode()
79 {
80 return HashCode.Combine(Name, Command, ArgsLight, ArgsDark);
81 }
82}
💬 GetHashCode() refers to mutable property Command (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 6 hits
📄 AutoDarkModeSvc\Handlers\DisplayHandler.cs (line 162)
159 }
160
161 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
162 private struct DISPLAY_DEVICE
163 {
164 [MarshalAs(UnmanagedType.U4)]
165 public int cb;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DISPLAY_DEVICE. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 AutoDarkModeSvc\Modules\SystemIdleCheckModule.cs (line 73)
70
71 [DllImport("User32.dll")]
72 private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
73 internal struct LASTINPUTINFO
74 {
75 public uint cbSize;
76
💬 Implement Equals(), GetHashCode() and ToString() methods on struct LASTINPUTINFO. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 4 hits
📄 AutoDarkModeSvc\SwitchComponents\Base\WallpaperSwitch.cs (line 474)
471
472 WallpaperType type = e.Theme == Theme.Dark ? Settings.Component.TypeDark : Settings.Component.TypeLight;
473
474 switch (type)
475 {
476 case WallpaperType.Individual:
477 List<string> wallpapersTarget =
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 AutoDarkModeSvc\Handlers\ThemeHandler.cs (line 120)
117 public static void EnforceNoMonitorUpdates(AdmConfigBuilder builder, GlobalState state, Theme theme)
118 {
119 string themePath = "";
120 switch (theme)
121 {
122 case Theme.Light:
123 themePath = Helper.PathUnmanagedLightTheme;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 10 hits
📄 AutoDarkModeSvc\SwitchComponents\Base\WallpaperSwitch.cs (line 474)
471
472 WallpaperType type = e.Theme == Theme.Dark ? Settings.Component.TypeDark : Settings.Component.TypeLight;
473
474 switch (type)
475 {
476 case WallpaperType.Individual:
477 List<string> wallpapersTarget =
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 AutoDarkModeSvc\Handlers\ThemeHandler.cs (line 120)
117 public static void EnforceNoMonitorUpdates(AdmConfigBuilder builder, GlobalState state, Theme theme)
118 {
119 string themePath = "";
120 switch (theme)
121 {
122 case Theme.Light:
123 themePath = Helper.PathUnmanagedLightTheme;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 6 hits
📄 AutoDarkModeSvc\Communication\AsyncPipeServer.cs (line 180)
177 using StreamReader sr = new(requestPipe);
178
179 // read two lines, the message and the output pipe address
180 if (requestPipe.IsConnected) msg = sr.ReadLine();
181 if (requestPipe.IsConnected) responderPipeId = sr.ReadLine() ?? "";
182 if (msg == null)
183 {
💬 Async overload available for StreamReader.ReadLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 AutoDarkModeSvc\Communication\AsyncPipeServer.cs (line 181)
178
179 // read two lines, the message and the output pipe address
180 if (requestPipe.IsConnected) msg = sr.ReadLine();
181 if (requestPipe.IsConnected) responderPipeId = sr.ReadLine() ?? "";
182 if (msg == null)
183 {
184 Logger.Warn("no message received within request window");
💬 Async overload available for StreamReader.ReadLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 20 hits
📄 AutoDarkModeLib\ComponentSettings\Base\WallpaperSwitchSettings.cs (line 80)
77 {
78 try
79 {
80 DisplayMonitor monitor = Task.Run(async () => await GetMonitorInfoAsync()).Result;
81 if (monitor != null)
82 {
83 Connected = true;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 AutoDarkModeSvc\Handlers\WallpaperHandler.cs (line 102)
99 {
100 IDesktopWallpaper handler = (IDesktopWallpaper)new DesktopWallpaperClass();
101 handler.SetPosition(position);
102 var monitors = Task.Run(DisplayHandler.GetMonitorInfosAsync).Result;
103
104 foreach (var monitor in monitors)
105 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS049 Comparing strings without StringComparison 4 hits
📄 AutoDarkModeSvc\SwitchComponents\Base\WallpaperSwitch.cs (line 376)
373
374 // global wallpaper enable state synchronization;
375 string globalWallpaper = WallpaperHandler.GetGlobalWallpaper().ToLower();
376 if (globalWallpaper == Settings.Component.GlobalWallpaper.Light?.ToLower()) currentGlobalTheme = Theme.Light;
377 else if (globalWallpaper == Settings.Component.GlobalWallpaper.Dark?.ToLower()) currentGlobalTheme = Theme.Dark;
378
379 // solid color enable state synchronization
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 AutoDarkModeSvc\SwitchComponents\Base\WallpaperSwitch.cs (line 377)
374 // global wallpaper enable state synchronization;
375 string globalWallpaper = WallpaperHandler.GetGlobalWallpaper().ToLower();
376 if (globalWallpaper == Settings.Component.GlobalWallpaper.Light?.ToLower()) currentGlobalTheme = Theme.Light;
377 else if (globalWallpaper == Settings.Component.GlobalWallpaper.Dark?.ToLower()) currentGlobalTheme = Theme.Dark;
378
379 // solid color enable state synchronization
380 if (GlobalState.ManagedThemeFile.Desktop.Wallpaper.Length == 0 &&
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS057 Collection manipulated during traversal 6 hits
📄 AutoDarkModeSvc\Handlers\ThemeFiles\ThemeFile.cs (line 338)
335 if (line.Length != 0 && !line.Contains('=') && !line.StartsWith('[') && !line.StartsWith(';'))
336 {
337 Logger.Warn($"invalid ini file entry detected: {line}, removing line to preserve theme file integrity");
338 ThemeFileContent.RemoveAt(i);
339 i--;
340 }
341 // removes invalid sections
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 AutoDarkModeSvc\Handlers\ThemeFiles\ThemeFile.cs (line 354)
351 {
352 if ((i + 1) < ThemeFileContent.Count && ThemeFileContent[i + 1].Length == 0)
353 {
354 ThemeFileContent.RemoveAt(i + 1);
355 i--;
356 }
357 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 2 hits
📄 AutoDarkModeSvc\Handlers\ThemeDllHandler.cs (line 44)
41 string line = "";
42 while (!bridge.StandardOutput.EndOfStream)
43 {
44 line += bridge.StandardOutput.ReadLine();
45 }
46 bridge.WaitForExit();
47 int exitCode = bridge.ExitCode;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 AutoDarkModeSvc\Handlers\ThemeDllHandler.cs (line 44)
41 string line = "";
42 while (!bridge.StandardOutput.EndOfStream)
43 {
44 line += bridge.StandardOutput.ReadLine();
45 }
46 bridge.WaitForExit();
47 int exitCode = bridge.ExitCode;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 6 hits
📄 AutoDarkModeSvc\HttpClientProgressExtensions.cs (line 32)
29 using (var response = await client.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead))
30 {
31 var contentLength = response.Content.Headers.ContentLength;
32 using (var download = await response.Content.ReadAsStreamAsync())
33 {
34 // no progress... no contentLength... very sad
35 if (progress is null || !contentLength.HasValue)
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 AutoDarkModeSvc\Communication\AsyncPipeServer.cs (line 152)
149 try
150 {
151 // this stream is the main requester loop and should only be cancelled from the outside if the server is stopped
152 using NamedPipeServerStream requestPipe = new(Address.PipePrefix + Address.PipeRequest, PipeDirection.InOut, WorkerCount, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
153 await requestPipe.WaitForConnectionAsync(WorkerTokenSource.Token);
154 Interlocked.Decrement(ref availableWorkers);
155 if (AvailableWorkers == 0)
💬 NamedPipeServerStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 18 hits
📄 AutoDarkModeSvc\Service.cs (line 46)
43 private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
44
45 private AdmConfigBuilder builder = AdmConfigBuilder.Instance();
46 private NotifyIcon NotifyIcon { get; }
47 private List<ModuleTimer> Timers { get; set; }
48 private IMessageServer MessageServer { get; }
49 private AdmConfigMonitor ConfigMonitor { get; }
💬 Disposable field NotifyIcon in type Service is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 AutoDarkModeSvc\Service.cs (line 54)
51 GlobalState state = GlobalState.Instance();
52
53
54 public readonly ToolStripMenuItem forceDarkMenuItem = new();
55 public readonly ToolStripMenuItem forceLightMenuItem = new();
56 public readonly ToolStripMenuItem autoThemeSwitchingItem = new();
57 public readonly ToolStripMenuItem toggleThemeItem = new();
💬 Disposable field forceDarkMenuItem in type Service is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

LiteNetLib

280 total diagnostics across 10 rules

SS003 Integer divided by integer causing implicit rounding 108 hits
📄 LiteNetLib\NetConstants.cs (line 50)
47 public const int FragmentHeaderSize = 6;
48 public const int FragmentedHeaderTotalSize = ChanneledHeaderSize + FragmentHeaderSize;
49 public const ushort MaxSequence = 32768;
50 public const ushort HalfMaxSequence = MaxSequence / 2;
51
52 //protocol
53 internal const int ProtocolId = 13;
💬 The operands in the divisive expression MaxSequence / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 LiteNetLib\NetConstants.cs (line 57)
54 internal const int MaxUdpHeaderSize = 68;
55 internal const int ChannelTypeCount = 4;
56 internal const int FragmentedChannelsCount = 2;
57 internal const int MaxFragmentsInWindow = DefaultWindowSize / 2;
58
59 internal static readonly int[] PossibleMtu =
60 {
💬 The operands in the divisive expression DefaultWindowSize / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 16 hits
📄 LiteNetLib\LiteNetManager.Socket.cs (line 146)
143 continue;
144 }
145 bool messageReceived = false;
146 if (socketv4.Available != 0 || selectReadList.Contains(socketv4))
147 {
148 if (NativeReceiveFrom(socketHandle4, addrBuffer4) == false)
149 return;
💬 Type Socket is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 LiteNetLib\LiteNetManager.Socket.cs (line 152)
149 return;
150 messageReceived = true;
151 }
152 if (socketV6.Available != 0 || selectReadList.Contains(socketV6))
153 {
154 if (NativeReceiveFrom(socketHandle6, addrBuffer6) == false)
155 return;
💬 Type Socket is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 4 hits
📄 LiteNetLib\LiteNetPeer.cs (line 53)
50 /// <summary>
51 /// Network peer. Main purpose is sending messages to specific peer.
52 /// </summary>
53 public class LiteNetPeer : IPEndPoint
54 {
55 //Ping and RTT
56 private int _rtt;
💬 Equals() and GetHashcode() must be implemented together on LiteNetPeer (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 LiteNetLib\LiteNetPeer.cs (line 53)
50 /// <summary>
51 /// Network peer. Main purpose is sending messages to specific peer.
52 /// </summary>
53 public class LiteNetPeer : IPEndPoint
54 {
55 //Ping and RTT
56 private int _rtt;
💬 Equals() and GetHashcode() must be implemented together on LiteNetPeer (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 8 hits
📄 LiteNetLib\LiteNetPeer.cs (line 228)
225
226 public override int GetHashCode() =>
227 //uses SocketAddress hash in NET8 and IPEndPoint hash for NativeSockets and previous NET versions
228 _cachedHashCode;
229
230 //incoming connection constructor
231 internal LiteNetPeer(LiteNetManager netManager, IPEndPoint remoteEndPoint, int id) : base(remoteEndPoint.Address, remoteEndPoint.Port)
💬 GetHashCode() refers to mutable field _cachedHashCode (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 LiteNetLib\LiteNetPeer.cs (line 228)
225
226 public override int GetHashCode() =>
227 //uses SocketAddress hash in NET8 and IPEndPoint hash for NativeSockets and previous NET versions
228 _cachedHashCode;
229
230 //incoming connection constructor
231 internal LiteNetPeer(LiteNetManager netManager, IPEndPoint remoteEndPoint, int id) : base(remoteEndPoint.Address, remoteEndPoint.Port)
💬 GetHashCode() refers to mutable field _cachedHashCode (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 60 hits
📄 LiteNetLib\INetEventListener.cs (line 59)
56 /// <summary>
57 /// Additional information about disconnection
58 /// </summary>
59 public struct DisconnectInfo
60 {
61 /// <summary>
62 /// Additional info why peer disconnected
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DisconnectInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 LiteNetLib\NatPunchModule.cs (line 47)
44 /// </summary>
45 public sealed class NatPunchModule
46 {
47 struct RequestEventData
48 {
49 public IPEndPoint LocalEndPoint;
50 public IPEndPoint RemoteEndPoint;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RequestEventData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 28 hits
📄 LiteNetLib\LiteNetManager.cs (line 835)
832 return;
833 }
834
835 switch (packet.Property)
836 {
837 //special case connect request
838 case PacketProperty.ConnectRequest:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 LiteNetLib\LiteNetPeer.cs (line 935)
932 internal ConnectRequestResult ProcessConnectRequest(NetConnectRequestPacket connRequest)
933 {
934 //current or new request
935 switch (_connectionState)
936 {
937 //P2P case
938 case ConnectionState.Outgoing:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 36 hits
📄 LiteNetLib\LiteNetManager.cs (line 391)
388 {
389 NetDebug.Write("[NM] Processing event: " + evt.Type);
390 bool emptyData = evt.DataReader.IsNull;
391 switch (evt.Type)
392 {
393 case NetEvent.EType.Connect:
394 _netEventListener.OnPeerConnected(evt.Peer);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 LiteNetLib\NetManager.cs (line 148)
145 NetDebug.Write("[NM] Processing event: " + evt.Type);
146 bool emptyData = evt.DataReader.IsNull;
147 var netPeer = evt.Peer as NetPeer;
148 switch (evt.Type)
149 {
150 case NetEvent.EType.Connect:
151 _netEventListener.OnPeerConnected(netPeer);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 8 hits
📄 LiteNetLib.Tests\LiteCommunicationTest.cs (line 39)
36 private const string DefaultAppKey = "test_server";
37 private static readonly byte[] DefaultAppKeyBytes = [12, 0, 116, 101, 115, 116, 95, 115, 101, 114, 118, 101, 114];
38
39 public LiteNetManagerStack ManagerStack { get; set; }
40
41 [Test, CancelAfter(TestTimeout)]
42 public void ConnectionByIpV4()
💬 Method set_ManagerStack might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 LiteNetLib.Tests\CommunicationTest.cs (line 39)
36 private const string DefaultAppKey = "test_server";
37 private static readonly byte[] DefaultAppKeyBytes = [12, 0, 116, 101, 115, 116, 95, 115, 101, 114, 118, 101, 114];
38
39 public NetManagerStack ManagerStack { get; set; }
40
41 [Test, CancelAfter(TestTimeout)]
42 public void ConnectionByIpV4()
💬 Method set_ManagerStack might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS057 Collection manipulated during traversal 8 hits
📄 LiteNetLib\LiteNetManager.cs (line 539)
536 if (incomingData.TimeWhenGet <= time)
537 {
538 HandleMessageReceived(incomingData.Data, incomingData.EndPoint);
539 _pingSimulationList.RemoveAt(i);
540 i--;
541 }
542 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 LiteNetLib\LiteNetManager.cs (line 555)
552 {
553 // Send the delayed packet directly to socket layer bypassing simulation
554 SendRawCore(outboundData.Data, outboundData.Start, outboundData.Length, outboundData.EndPoint);
555 _outboundSimulationList.RemoveAt(i);
556 i--;
557 }
558 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 4 hits
📄 LiteNetLib\NetManager.cs (line 95)
92
93 internal override bool CustomMessageHandle(NetPacket packet, IPEndPoint remoteEndPoint)
94 {
95 if (_ntpRequests.Count > 0 && _ntpRequests.TryGetValue(remoteEndPoint, out _))
96 {
97 if (packet.Size < 48)
98 {
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 LiteNetLib\NetManager.cs (line 95)
92
93 internal override bool CustomMessageHandle(NetPacket packet, IPEndPoint remoteEndPoint)
94 {
95 if (_ntpRequests.Count > 0 && _ntpRequests.TryGetValue(remoteEndPoint, out _))
96 {
97 if (packet.Size < 48)
98 {
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)

TwitchDownloader

276 total diagnostics across 14 rules

SS001 Async method with void return type 4 hits
📄 TwitchDownloaderWPF\MainWindow.xaml.cs (line 136)
133#endif
134 }
135
136 private async void FlashTaskbarIconIfNotForeground(TimeSpan flashDuration)
137 {
138 var currentWindow = new WindowInteropHelper(this).Handle;
139 var foregroundWindow = NativeFunctions.GetForegroundWindow();
💬 Method FlashTaskbarIconIfNotForeground is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 TwitchDownloaderWPF\MainWindow.xaml.cs (line 136)
133#endif
134 }
135
136 private async void FlashTaskbarIconIfNotForeground(TimeSpan flashDuration)
137 {
138 var currentWindow = new WindowInteropHelper(this).Handle;
139 var foregroundWindow = NativeFunctions.GetForegroundWindow();
💬 Method FlashTaskbarIconIfNotForeground is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 8 hits
📄 TwitchDownloaderCore\ChatDownloader.cs (line 368)
365 {
366 var chatRoot = new ChatRoot
367 {
368 FileInfo = new ChatRootInfo { Version = ChatRootVersion.CurrentVersion, CreatedAt = DateTime.Now },
369 streamer = new Streamer(),
370 video = new Video(),
371 comments = new List<Comment>()
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 TwitchDownloaderCore\ChatUpdater.cs (line 59)
56
57 private async Task UpdateAsyncImpl(FileInfo outputFileInfo, FileStream outputFs, CancellationToken cancellationToken)
58 {
59 chatRoot.FileInfo = new() { Version = ChatRootVersion.CurrentVersion, CreatedAt = chatRoot.FileInfo.CreatedAt, UpdatedAt = DateTime.Now };
60 if (!Path.GetExtension(_updateOptions.InputFile.Replace(".gz", ""))!.Equals(".json", StringComparison.OrdinalIgnoreCase))
61 {
62 throw new NotSupportedException("Only JSON chat files can be used as update input. HTML support may come in the future.");
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 64 hits
📄 TwitchDownloaderCore\ChatDownloader.cs (line 488)
485 {
486 percentages[tc] = Math.Clamp(percent, 0, 100);
487
488 var reportPercent = percentages.Sum() / connectionCount;
489 _progress.ReportProgress(reportPercent);
490 });
491
💬 The operands in the divisive expression percentages.Sum() / connectionCount are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 TwitchDownloaderCore\ChatDownloader.cs (line 576)
573 imageScale = emote.ImageScale,
574 data = emote.ImageData,
575 name = emote.Name,
576 width = emote.Width / emote.ImageScale,
577 height = emote.Height / emote.ImageScale,
578 isZeroWidth = emote.IsZeroWidth,
579 };
💬 The operands in the divisive expression emote.Width / emote.ImageScale are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 TwitchDownloaderCore\ChatUpdater.cs (line 469)
466 commentsSet.EnsureCapacity(commentsSet.Count + chatRoot.comments.Count);
467 foreach (var comment in chatRoot.comments)
468 {
469 commentsSet.Add(comment);
470 }
471
472 chatRoot.comments = commentsSet.ToList();
💬 Type Comment is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 TwitchDownloaderCore\ChatUpdater.cs (line 469)
466 commentsSet.EnsureCapacity(commentsSet.Count + chatRoot.comments.Count);
467 foreach (var comment in chatRoot.comments)
468 {
469 commentsSet.Add(comment);
470 }
471
472 chatRoot.comments = commentsSet.ToList();
💬 Type Comment is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 TwitchDownloaderCore\TwitchObjects\CommentSection.cs (line 13)
10 public int CommentIndex { get; set; }
11 }
12
13 public struct Point
14 {
15 public int X { get; set; }
16 public int Y { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Point. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 TwitchDownloaderCore\TwitchObjects\CommentSection.cs (line 13)
10 public int CommentIndex { get; set; }
11 }
12
13 public struct Point
14 {
15 public int X { get; set; }
16 public int Y { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Point. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 20 hits
📄 TwitchDownloaderCore\Tools\TimeSpanHFormat.cs (line 100)
97 bigHStart = -1;
98 }
99
100 switch (readChar)
101 {
102 // If the current char is an escape we can skip the next char
103 case '\\':
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 TwitchDownloaderCLI\Tools\UserPrompt.cs (line 25)
22 return UserPromptResult.Unknown;
23 }
24
25 switch (userInput.Trim().ToLower())
26 {
27 case "y" or "yes":
28 return UserPromptResult.Yes;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 6 hits
📄 TwitchDownloaderCore\TwitchHelper.cs (line 826)
823 await ms.CopyToAsync(fs, cancellationToken);
824 }
825
826 using var archive = ZipFile.OpenRead(emojiZipPath);
827 var emojiAssetsPath = emojiVendor.AssetPath();
828 var emojis = archive.Entries
829 .Where(x => !string.IsNullOrWhiteSpace(x.Name) && Path.GetDirectoryName(x.FullName) == emojiAssetsPath);
💬 Async overload available for ZipFile.OpenRead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 TwitchDownloaderCore\TwitchHelper.cs (line 840)
837 {
838 try
839 {
840 emoji.ExtractToFile(filePath);
841 }
842 catch { /* Being written by a parallel process? */ }
843 }
💬 Async overload available for ZipFileExtensions.ExtractToFile (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 68 hits
📄 TwitchDownloaderCore\ChatDownloader.cs (line 506)
503 _progress.ReportProgress(100);
504
505 var commentList = downloadTasks
506 .SelectMany(task => task.Result)
507 .ToHashSet(new CommentIdEqualityComparer())
508 .ToList();
509
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 TwitchDownloaderCore\ChatRenderer.cs (line 1743)
1740 GC.Collect();
1741 GC.WaitForPendingFinalizers();
1742
1743 badgeList = badgeTask.Result;
1744 emoteList = emoteTask.Result;
1745 emoteThirdList = emoteThirdTask.Result;
1746 cheermotesList = cheerTask.Result;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 TwitchDownloaderCore\ChatDownloader.cs (line 505)
502
503 _progress.ReportProgress(100);
504
505 var commentList = downloadTasks
506 .SelectMany(task => task.Result)
507 .ToHashSet(new CommentIdEqualityComparer())
508 .ToList();
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 TwitchDownloaderCore\ChatDownloader.cs (line 505)
502
503 _progress.ReportProgress(100);
504
505 var commentList = downloadTasks
506 .SelectMany(task => task.Result)
507 .ToHashSet(new CommentIdEqualityComparer())
508 .ToList();
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS047 LINQ traversal before filter 4 hits
📄 TwitchDownloaderCore\VideoDownloader.cs (line 124)
121 var concatListPath = Path.Combine(_vodCacheDir, "concat.txt");
122 var streamIds = GetStreamIds(playlist);
123
124 var validParts = playlist.Streams
125 .Take(videoListCrop)
126 .Where(x => File.Exists(Path.Combine(_vodCacheDir, DownloadTools.RemoveQueryString(x.Path))))
127 .ToArray();
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 TwitchDownloaderCore\VideoDownloader.cs (line 133)
130 if (validParts.Length < videoListCrop.GetOffsetAndLength(playlist.Streams.Length).Length)
131 {
132 // This is probably super inefficient, but it's a very cold path anyway
133 var missingParts = playlist.Streams
134 .Take(videoListCrop)
135 .Where(x => !validParts.Contains(x));
136
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS048 Locking on discouraged object (string, Type, this) 50 hits
📄 TwitchDownloaderCLI\Tools\CliTaskProgress.cs (line 41)
38 {
39 if ((_logLevel & LogLevel.Status) == 0) return;
40
41 lock (this)
42 {
43 _status = status;
44 _statusIsTemplate = false;
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 TwitchDownloaderCLI\Tools\CliTaskProgress.cs (line 54)
51 {
52 if ((_logLevel & LogLevel.Status) == 0) return;
53
54 lock (this)
55 {
56 _status = statusTemplate;
57 _statusIsTemplate = true;
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS057 Collection manipulated during traversal 4 hits
📄 TwitchDownloaderCore\TwitchObjects\TwitchEmote.cs (line 82)
79 {
80 for (int i = 0; i < EmoteFrameDurations.Count; i++)
81 {
82 EmoteFrameDurations.RemoveAt(i);
83 EmoteFrameDurations.Insert(i, 10);
84 }
85 TotalDuration = EmoteFrameDurations.Count * 10;
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 TwitchDownloaderCore\TwitchObjects\TwitchEmote.cs (line 83)
80 for (int i = 0; i < EmoteFrameDurations.Count; i++)
81 {
82 EmoteFrameDurations.RemoveAt(i);
83 EmoteFrameDurations.Insert(i, 10);
84 }
85 TotalDuration = EmoteFrameDurations.Count * 10;
86 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 TwitchDownloaderCore\Chat\ChatHtml.cs (line 33)
30
31 cancellationToken.ThrowIfCancellationRequested();
32
33 using var templateStream = new MemoryStream(Properties.Resources.chat_template);
34 using var templateReader = new StreamReader(templateStream);
35
36 await using var sw = new StreamWriter(outputStream, leaveOpen: true);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 TwitchDownloaderCore\TwitchHelper.cs (line 820)
817 var emojiZipPath = Path.Combine(emojiFolder, Path.GetRandomFileName());
818 try
819 {
820 using (var ms = emojiVendor.MemoryStream())
821 {
822 await using var fs = File.OpenWrite(emojiZipPath);
823 await ms.CopyToAsync(fs, cancellationToken);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 34 hits
📄 TwitchDownloaderCore\Tools\HighlightIcons.cs (line 64)
61 [GeneratedRegex("""^We added \d+ Gift Subs (?:AND \d+ Bonus Gift Subs )?to """)]
62 private static partial Regex SubtemberRegex { get; }
63
64 private SKImage _subscribedTierIcon;
65 private SKImage _subscribedPrimeIcon;
66 private SKImage _giftSingleIcon;
67 private SKImage _giftManyIcon;
💬 Disposable field _subscribedTierIcon in type HighlightIcons is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 TwitchDownloaderCore\Tools\HighlightIcons.cs (line 65)
62 private static partial Regex SubtemberRegex { get; }
63
64 private SKImage _subscribedTierIcon;
65 private SKImage _subscribedPrimeIcon;
66 private SKImage _giftSingleIcon;
67 private SKImage _giftManyIcon;
68 private SKImage _giftAnonymousIcon;
💬 Disposable field _subscribedPrimeIcon in type HighlightIcons is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

commandline

276 total diagnostics across 9 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 24 hits
📄 src\CommandLine\Text\CopyrightInfo.cs (line 123)
120 //if both copyrightAttr and companyAttr aren't available in Assembly,don't fire Exception
121 ? Empty
122 // if no copyright attribute exist but a company attribute does, use it as copyright holder
123 : new CopyrightInfo(companyAttr.FromJust().Company, DateTime.Now.Year);
124
125 }
126 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\CommandLine\Text\CopyrightInfo.cs (line 34)
31 {
32 get
33 {
34 return new CopyrightInfo("author", DateTime.Now.Year);
35 }
36 }
37
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 112 hits
📄 src\CommandLine\UnParserExtensions.cs (line 171)
168 select info;
169
170 var optSpecs = settings.GroupSwitches
171 ? allOptSpecs.Where(info => !shortSwitches.Contains(info))
172 : allOptSpecs;
173
174 var valSpecs = from info in specs.Where(i => i.Specification.Tag == SpecificationType.Value)
💬 Type is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\CommandLine\Core\TokenPartitioner.cs (line 78)
75 break;
76 case TargetType.Sequence:
77 nameToken = token;
78 if (! sequences.ContainsKey(nameToken))
79 {
80 sequences[nameToken] = new List<Token>();
81 count[nameToken] = 0;
💬 Type Token is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 24 hits
📄 src\CommandLine\Core\TypeDescriptor.cs (line 8)
5
6namespace CommandLine.Core
7{
8 struct TypeDescriptor
9 {
10 private readonly TargetType targetType;
11 private readonly Maybe<int> maxItems;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TypeDescriptor. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\CommandLine\Text\HelpText.cs (line 25)
22
23
24
25 public struct ComparableOption
26 {
27 public bool Required;
28 public bool IsOption;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ComparableOption. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 24 hits
📄 src\CommandLine\Core\ValueMapper.cs (line 74)
71
72 private static Maybe<int> CountOfMaxNumberOfValues(this Specification specification)
73 {
74 switch (specification.TargetType)
75 {
76 case TargetType.Scalar:
77 return Maybe.Just(1);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\CommandLine\UnParserExtensions.cs (line 219)
216 private static string FormatValue(Specification spec, object value)
217 {
218 var builder = new StringBuilder();
219 switch (spec.TargetType)
220 {
221 case TargetType.Scalar:
222 builder.Append(FormatWithQuotesIfString(value));
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 48 hits
📄 src\CommandLine\Core\ValueMapper.cs (line 74)
71
72 private static Maybe<int> CountOfMaxNumberOfValues(this Specification specification)
73 {
74 switch (specification.TargetType)
75 {
76 case TargetType.Scalar:
77 return Maybe.Just(1);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\CommandLine\Core\GetoptTokenizer.cs (line 44)
41 var enumerator = arguments.GetEnumerator();
42 while (enumerator.MoveNext())
43 {
44 switch (enumerator.Current) {
45 case null:
46 break;
47
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 8 hits
📄 src\CommandLine\Text\SentenceBuilder.cs (line 168)
165 return MultipleDefaultVerbsError.ErrorMessage;
166
167 }
168 throw new InvalidOperationException();
169 };
170 }
171 }
💬 An exception is thrown from the getter of property FormatError (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\CommandLine\Text\SentenceBuilder.cs (line 168)
165 return MultipleDefaultVerbsError.ErrorMessage;
166
167 }
168 throw new InvalidOperationException();
169 };
170 }
171 }
💬 An exception is thrown from the getter of property FormatError (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS041 Unnecessary enumerable materialization 8 hits
📄 src\CommandLine\Text\HelpText.cs (line 884)
881 if (OptionComparison != null)
882 {
883 int i = -1;
884 var comparables = specifications.ToList().Select(s =>
885 {
886 i++;
887 return ToComparableOption(s, i);
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\CommandLine\Text\HelpText.cs (line 884)
881 if (OptionComparison != null)
882 {
883 int i = -1;
884 var comparables = specifications.ToList().Select(s =>
885 {
886 i++;
887 return ToComparableOption(s, i);
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 20 hits
📄 src\CommandLine\BaseAttribute.cs (line 10)
7 /// <summary>
8 /// Models a base attribute to define command line syntax.
9 /// </summary>
10 public abstract class BaseAttribute : Attribute
11 {
12 private int min;
13 private int max;
💬 BaseAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\CommandLine\Text\MultiLineTextAttribute.cs (line 12)
9 /// <summary>
10 /// Provides base properties for creating an attribute, used to define multiple lines of text.
11 /// </summary>
12 public abstract class MultilineTextAttribute : Attribute
13 {
14 private readonly string line1;
15 private readonly string line2;
💬 MultilineTextAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS066 Disposable field is not disposed 8 hits
📄 src\CommandLine\ParserSettings.cs (line 22)
19 private bool disposed;
20 private bool caseSensitive;
21 private bool caseInsensitiveEnumValues;
22 private TextWriter helpWriter;
23 private bool ignoreUnknownArguments;
24 private bool autoHelp;
25 private bool autoVersion;
💬 Disposable field helpWriter in type ParserSettings is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\CommandLine\ParserSettings.cs (line 22)
19 private bool disposed;
20 private bool caseSensitive;
21 private bool caseInsensitiveEnumValues;
22 private TextWriter helpWriter;
23 private bool ignoreUnknownArguments;
24 private bool autoHelp;
25 private bool autoVersion;
💬 Disposable field helpWriter in type ParserSettings is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Autofac

256 total diagnostics across 10 rules

SS004 Elementary methods of type in collection not overridden 8 hits
📄 test\Autofac.Test\Util\Cache\ReflectionCacheParameterDictionaryTests.cs (line 49)
46 {
47 var cache = new ReflectionCacheParameterDictionary<bool>
48 {
49 [SampleParameter] = true,
50 };
51
52 cache.Clear((_, _) => false);
💬 Type ParameterInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 test\Autofac.Test\Util\Cache\ReflectionCacheParameterDictionaryTests.cs (line 62)
59 {
60 var cache = new ReflectionCacheParameterDictionary<bool>
61 {
62 [SampleParameter] = true,
63 };
64
65 cache.Clear((member, _) => member == SampleParameter.Member);
💬 Type ParameterInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 8 hits
📄 src\Autofac\Features\OwnedInstances\InstancePerOwnedKey.cs (line 32)
29
30 /// <inheritdoc/>
31 public override int GetHashCode()
32 => _serviceWithType.ServiceType.GetHashCode();
33}
💬 GetHashCode() refers to mutable field _serviceWithType (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Autofac\Features\OwnedInstances\InstancePerOwnedKey.cs (line 32)
29
30 /// <inheritdoc/>
31 public override int GetHashCode()
32 => _serviceWithType.ServiceType.GetHashCode();
33}
💬 GetHashCode() refers to mutable field _serviceWithType (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 52 hits
📄 src\Autofac\Core\Activators\Reflection\InjectablePropertyState.cs (line 9)
6/// <summary>
7/// Structure used to track whether or not we have set a property during activation.
8/// </summary>
9internal struct InjectablePropertyState
10{
11 /// <summary>
12 /// Initializes a new instance of the <see cref="InjectablePropertyState"/> struct.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct InjectablePropertyState. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Autofac\Diagnostics\ValueStopwatch.cs (line 15)
12/// Lightweight stopwatch for timing without heap allocations.
13/// </summary>
14[ExcludeFromCodeCoverage]
15internal struct ValueStopwatch
16{
17#if !NET7_0_OR_GREATER
18 private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ValueStopwatch. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS023 Exception thrown from property getter 20 hits
📄 src\Autofac\Module.cs (line 63)
60 var baseType = thisType.BaseType;
61 if (baseType != typeof(Module))
62 {
63 throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, ModuleResources.ThisAssemblyUnavailable, thisType, baseType));
64 }
65
66 return thisType.Assembly;
💬 An exception is thrown from the getter of property ThisAssembly (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Autofac\Core\Resolving\SegmentedStack.cs (line 159)
156 {
157 if (_index < 0)
158 {
159 throw new InvalidOperationException(SegmentedStackResources.EnumeratorNotValid);
160 }
161
162 return _currentElement!;
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS027 Exception thrown from Dispose 8 hits
📄 src\Autofac\Core\Resolving\SegmentedStack.cs (line 131)
128 // the segment was not fully popped before exiting the segment.
129 if (_stack.Count > 0)
130 {
131 throw new InvalidOperationException(SegmentedStackResources.CannotExitSegmentWithRemainingItems);
132 }
133
134 _stack._activeSegmentBase = _resetPosition;
💬 An exception is thrown from the Dispose() method in type StackSegment (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 src\Autofac\Core\Resolving\SegmentedStack.cs (line 131)
128 // the segment was not fully popped before exiting the segment.
129 if (_stack.Count > 0)
130 {
131 throw new InvalidOperationException(SegmentedStackResources.CannotExitSegmentWithRemainingItems);
132 }
133
134 _stack._activeSegmentBase = _resetPosition;
💬 An exception is thrown from the Dispose() method in type StackSegment (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS033 Async overload is available 12 hits
📄 src\Autofac\Util\AsyncReleaseAction.cs (line 42)
39 await _action(_factory()).ConfigureAwait(false);
40 }
41
42 base.Dispose(disposing);
43 }
44
45 /// <inheritdoc/>
💬 Async overload available for Disposable.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Autofac\Util\AsyncReleaseAction.cs (line 42)
39 await _action(_factory()).ConfigureAwait(false);
40 }
41
42 base.Dispose(disposing);
43 }
44
45 /// <inheritdoc/>
💬 Async overload available for Disposable.Dispose (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 test\Autofac.Test.Scenarios.ScannedAssembly\MetadataAttributeScanningScenario\DuplicatedNameAttribute.cs (line 8)
5
6namespace Autofac.Test.Scenarios.ScannedAssembly.MetadataAttributeScanningScenario
7{
8 public class DuplicatedNameAttribute : Attribute, IHaveName
9 {
10 public DuplicatedNameAttribute(string name)
11 {
💬 DuplicatedNameAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 test\Autofac.Test.Scenarios.ScannedAssembly\MetadataAttributeScanningScenario\NameAttribute.cs (line 8)
5
6namespace Autofac.Test.Scenarios.ScannedAssembly.MetadataAttributeScanningScenario
7{
8 public class NameAttribute : Attribute, IHaveName
9 {
10 public NameAttribute(string name)
11 {
💬 NameAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 test\Autofac.Test\Core\ComponentRegistrationTests.cs (line 40)
37
38 await using var disposable = new AsyncDisposeTracker();
39
40 using var activator = Factory.CreateProvidedInstanceActivator(disposable);
41 activator.DisposeInstance = true;
42
43 var registration = Factory.CreateSingletonRegistration(services, activator);
💬 ProvidedInstanceActivator can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 test\Autofac.Test\Core\ComponentRegistrationTests.cs (line 55)
52 {
53 var services = new Service[] { new TypedService(typeof(object)) };
54
55 using var activator = Factory.CreateProvidedInstanceActivator(new object());
56 var registration = Factory.CreateSingletonRegistration(services, activator);
57
58 await registration.DisposeAsync();
💬 ProvidedInstanceActivator can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 32 hits
📄 src\Autofac\Util\Cache\ReflectionCacheTupleDictionary.cs (line 26)
23 /// <inheritdoc />
24 public void Clear(ReflectionCacheClearPredicate predicate)
25 {
26 if (Count == 0)
27 {
28 return;
29 }
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 src\Autofac\Util\Cache\ReflectionCacheParameterDictionary.cs (line 28)
25 throw new ArgumentNullException(nameof(predicate));
26 }
27
28 if (Count == 0)
29 {
30 return;
31 }
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
SS066 Disposable field is not disposed 104 hits
📄 src\Autofac\Features\OwnedInstances\Owned.cs (line 67)
64[SuppressMessage("Microsoft.ApiDesignGuidelines", "CA2213", Justification = "False positive - the lifetime does get disposed.")]
65public class Owned<T> : Disposable
66{
67 private IDisposable? _lifetime;
68
69 /// <summary>
70 /// Initializes a new instance of the <see cref="Owned{T}"/> class.
💬 Disposable field _lifetime in type Owned is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Autofac\Core\Registration\ComponentRegistration.cs (line 24)
21 RegistrationOptions.ExcludeFromCollections |
22 RegistrationOptions.DisableDecoration;
23
24 private readonly IComponentRegistration? _target;
25 private readonly IResolvePipelineBuilder _lateBuildPipeline;
26
27 private EventHandler<IResolvePipelineBuilder>? _pipelineBuildEvent;
💬 Disposable field _target in type ComponentRegistration is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

LLamaSharp

244 total diagnostics across 12 rules

SS001 Async method with void return type 2 hits
📄 LLama.Examples\Examples\SpeechChat.cs (line 199)
196 }
197
198
199 async void SendTranscription()
200 {
201 var bytesPerClip = _waveFormat.BitsPerSample * (int)ClipLength.TotalMilliseconds * 2;
202 var capturedClipBytes = _recordedBytes.TakeLast(bytesPerClip * (_nonIdleTime + 2)).ToArray();
💬 Method SendTranscription is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 LLama.Examples\Examples\SpeechChat.cs (line 199)
196 }
197
198
199 async void SendTranscription()
200 {
201 var bytesPerClip = _waveFormat.BitsPerSample * (int)ClipLength.TotalMilliseconds * 2;
202 var capturedClipBytes = _recordedBytes.TakeLast(bytesPerClip * (_nonIdleTime + 2)).ToArray();
💬 Method SendTranscription is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS003 Integer divided by integer causing implicit rounding 30 hits
📄 LLama\Batched\BatchedExecutor.cs (line 231)
228 return;
229 }
230
231 if (_batchQueueHead > CleanupThreshold && _batchQueueHead > _batchQueue.Count / 2)
232 {
233 _batchQueue.RemoveRange(0, _batchQueueHead);
234 _batchQueueHead = 0;
💬 The operands in the divisive expression _batchQueue.Count / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 LLama\Batched\Conversation.cs (line 436)
433 AssertCanBePrompted();
434
435 var dim = Executor.Model.EmbeddingSize;
436 var count = embeddings.Length / dim;
437 if (count * dim != embeddings.Length)
438 throw new ArgumentException($"Incorrect embeddings span size, length ({embeddings.Length}) must be divisible by embedding dimensions ({Executor.Model.EmbeddingSize})");
439
💬 The operands in the divisive expression embeddings.Length / dim are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 100 hits
📄 LLama\Batched\Conversation.cs (line 537)
534 /// Provides direct access to the KV cache of a <see cref="Conversation"/>.
535 /// See <see cref="Modify"/> for how to use this.
536 /// </summary>
537 public readonly ref struct KvAccessor
538 {
539 private readonly Conversation _conversation;
540
💬 Implement Equals(), GetHashCode() and ToString() methods on struct KvAccessor. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 LLama\Extensions\IReadOnlyListExtensions.cs (line 84)
81 return tokens.TokensEndsWithAnyString(new ReadonlyWrapper<string>(queries), model, encoding);
82 }
83
84 private readonly struct ReadonlyWrapper<T>
85 : IReadOnlyList<T>
86 {
87 private readonly IList<T> _list;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ReadonlyWrapper. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 6 hits
📄 LLama\Extensions\IContextParamsExtensions.cs (line 54)
51 result.offload_kqv = !@params.NoKqvOffload;
52 result.llama_pooling_type = @params.PoolingType;
53 result.attention_type = @params.AttentionType;
54 result.llama_flash_attn_type = @params.FlashAttention switch
55 {
56 true => LLamaFlashAttentionType.LLAMA_FLASH_ATTENTION_TYPE_ENABLED,
57 false => LLamaFlashAttentionType.LLAMA_FLASH_ATTENTION_TYPE_DISABLED,
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 LLama\Extensions\IContextParamsExtensions.cs (line 54)
51 result.offload_kqv = !@params.NoKqvOffload;
52 result.llama_pooling_type = @params.PoolingType;
53 result.attention_type = @params.AttentionType;
54 result.llama_flash_attn_type = @params.FlashAttention switch
55 {
56 true => LLamaFlashAttentionType.LLAMA_FLASH_ATTENTION_TYPE_ENABLED,
57 false => LLamaFlashAttentionType.LLAMA_FLASH_ATTENTION_TYPE_DISABLED,
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 LLama\Native\SafeMtmdEmbed.cs (line 209)
206 unsafe
207 {
208 if (!IsValid)
209 throw new ObjectDisposedException("Cannot access Embed data, accessor has been disposed");
210 return new ReadOnlySpan<byte>(_dataPtr, _dataLength);
211 }
212 }
💬 An exception is thrown from the getter of property Data (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 LLama\Native\SafeMtmdEmbed.cs (line 209)
206 unsafe
207 {
208 if (!IsValid)
209 throw new ObjectDisposedException("Cannot access Embed data, accessor has been disposed");
210 return new ReadOnlySpan<byte>(_dataPtr, _dataLength);
211 }
212 }
💬 An exception is thrown from the getter of property Data (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 4 hits
📄 LLama\Native\NativeApi.Load.cs (line 29)
26 }
27 catch (DllNotFoundException)
28 {
29 throw new RuntimeError("The native library cannot be correctly loaded. It could be one of the following reasons: \n" +
30 "1. No LLamaSharp backend was installed. Please search LLamaSharp.Backend and install one of them. \n" +
31 "2. You are using a device with only CPU but installed cuda backend. Please install cpu backend instead. \n" +
32 "3. One of the dependency of the native library is missed. Please use `ldd` on linux, `dumpbin` on windows and `otool`" +
💬 An exception is thrown from NativeApi its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 LLama\Native\NativeApi.Load.cs (line 29)
26 }
27 catch (DllNotFoundException)
28 {
29 throw new RuntimeError("The native library cannot be correctly loaded. It could be one of the following reasons: \n" +
30 "1. No LLamaSharp backend was installed. Please search LLamaSharp.Backend and install one of them. \n" +
31 "2. You are using a device with only CPU but installed cuda backend. Please install cpu backend instead. \n" +
32 "3. One of the dependency of the native library is missed. Please use `ldd` on linux, `dumpbin` on windows and `otool`" +
💬 An exception is thrown from NativeApi its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS027 Exception thrown from Dispose 4 hits
📄 LLama\Batched\Conversation.cs (line 743)
740 public override void Dispose()
741 {
742 if (IsDisposed)
743 throw new ObjectDisposedException(nameof(State));
744 IsDisposed = true;
745
746 SequenceState.Dispose();
💬 An exception is thrown from the Dispose() method in type PrivateState (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 LLama\Batched\Conversation.cs (line 743)
740 public override void Dispose()
741 {
742 if (IsDisposed)
743 throw new ObjectDisposedException(nameof(State));
744 IsDisposed = true;
745
746 SequenceState.Dispose();
💬 An exception is thrown from the Dispose() method in type PrivateState (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS033 Async overload is available 14 hits
📄 LLama.WebAPI\Program.cs (line 32)
29 _ = endpoints.MapControllers();
30});
31
32app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 LLama.Web\Program.cs (line 50)
47
48app.MapHub<SessionConnectionHub>(nameof(SessionConnectionHub));
49
50app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 12 hits
📄 LLama.Experimental\Native\AutoDownloadedLibraries.cs (line 81)
78 foreach (var relativePath in _macLibrary.Prepare(systemInfo, logCallback))
79 {
80 yield return relativePath;
81 var path = NativeLibraryDownloader.DownloadLibraryFile(_settings, relativePath, logCallback).Result;
82 if (path is not null)
83 {
84 yield return path;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 LLama.Experimental\Native\AutoDownloadedLibraries.cs (line 27)
24 foreach(var relativePath in _cudaLibrary.Prepare(systemInfo, logCallback))
25 {
26 yield return relativePath;
27 var path = NativeLibraryDownloader.DownloadLibraryFile(_settings, relativePath, logCallback).Result;
28 if (path is not null)
29 {
30 yield return path;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS058 String concatenated in a loop 2 hits
📄 LLama.WebAPI\Services\StatefulChatService.cs (line 63)
60 await foreach (var output in outputs)
61 {
62 _logger.LogInformation("Message: {output}", output);
63 result += output;
64 }
65
66 return result;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 LLama.WebAPI\Services\StatefulChatService.cs (line 63)
60 await foreach (var output in outputs)
61 {
62 _logger.LogInformation("Message: {output}", output);
63 result += output;
64 }
65
66 return result;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 LLama\LLamaInstructExecutor.cs (line 115)
112 public override async Task SaveState(string filename, CancellationToken cancellationToken = default)
113 {
114 var state = (InstructExecutorState)GetStateData();
115 using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
116 {
117 await JsonSerializer.SerializeAsync(fs, state, cancellationToken: cancellationToken);
118 }
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 LLama\LLamaInteractExecutor.cs (line 101)
98 public override async Task SaveState(string filename, CancellationToken cancellationToken = default)
99 {
100 var state = (InteractiveExecutorState)GetStateData();
101 using (var fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
102 {
103 await JsonSerializer.SerializeAsync(fs, state, cancellationToken: cancellationToken);
104 }
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 58 hits
📄 LLama\Native\SafeLLamaContextHandle.cs (line 75)
72 /// </summary>
73 public SafeLlamaModelHandle.Vocabulary Vocab => ThrowIfDisposed().Vocab;
74
75 private SafeLlamaModelHandle? _model;
76 #endregion
77
78 #region construction/destruction
💬 Disposable field _model in type SafeLLamaContextHandle is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 LLama\LLamaEmbedder.cs (line 31)
28 /// </summary>
29 public LLamaContext Context { get; private set; }
30
31 private LLamaWeights _weights;
32 private IContextParams _params;
33 private ILogger? _logger;
34
💬 Disposable field _weights in type LLamaEmbedder is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

StableSwarmUI

236 total diagnostics across 19 rules

SS001 Async method with void return type 2 hits
📄 src\Backends\NetworkBackendUtils.cs (line 444)
441 }
442 }
443 new Thread(MonitorLoop) { Name = $"SelfStart{nameSimple.Replace(' ', '_')}_Monitor" }.Start();
444 async void MonitorErrLoop()
445 {
446 StringBuilder errorLog = new();
447 string line;
💬 Method MonitorErrLoop is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Backends\NetworkBackendUtils.cs (line 444)
441 }
442 }
443 new Thread(MonitorLoop) { Name = $"SelfStart{nameSimple.Replace(' ', '_')}_Monitor" }.Start();
444 async void MonitorErrLoop()
445 {
446 StringBuilder errorLog = new();
447 string line;
💬 Method MonitorErrLoop is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 src\Text2Image\T2IParamInput.cs (line 440)
437 SourceSession = session;
438 InterruptToken = session is null ? new CancellationTokenSource().Token : session.SessInterrupt.Token;
439 ExtraMeta["swarm_version"] = Utilities.Version;
440 ExtraMeta["date"] = DateTime.Now.ToString("yyyy-MM-dd");
441 }
442
443 /// <summary>Gets the desired image width, automatically using alt-res parameter if needed.</summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Text2Image\T2IParamInput.cs (line 440)
437 SourceSession = session;
438 InterruptToken = session is null ? new CancellationTokenSource().Token : session.SessInterrupt.Token;
439 ExtraMeta["swarm_version"] = Utilities.Version;
440 ExtraMeta["date"] = DateTime.Now.ToString("yyyy-MM-dd");
441 }
442
443 /// <summary>Gets the desired image width, automatically using alt-res parameter if needed.</summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 20 hits
📄 src\Backends\BackendHandler.cs (line 711)
708 public LockObject Locker = new();
709
710 /// <summary>Gets a loose heuristic for model order preference - sort by earliest requester, but higher count of requests is worth 10 seconds.</summary>
711 public long Heuristic(long timeRel) => Count * 10 + ((timeRel - TimeFirstRequest) / 1000); // TODO: 10 -> ?
712 }
713
714 /// <summary>Used by <see cref="GetNextT2IBackend(TimeSpan, T2IModel)"/> to determine which model to load onto a backend, heuristically.</summary>
💬 The operands in the divisive expression (timeRel - TimeFirstRequest) / 1000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\WebAPI\BackendAPI.cs (line 54)
51 public static JObject BackendToNet(BackendHandler.T2IBackendData backend, bool full = false)
52 {
53 long timeLastRelease = backend.TimeLastRelease;
54 long timeSinceUsed = timeLastRelease == 0 ? 0 : (Environment.TickCount64 - timeLastRelease) / 1000;
55 JObject data = new()
56 {
57 ["type"] = backend.Backend.HandlerTypeData.ID,
💬 The operands in the divisive expression (Environment.TickCount64 - timeLastRelease) / 1000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 2 hits
📄 src\Accounts\Session.cs (line 211)
208 /// <summary>Gets a hash code for this session, for C# equality comparsion.</summary>
209 public override int GetHashCode()
210 {
211 return ID.GetHashCode();
212 }
213
214 /// <summary>Returns true if this session is the same as another.</summary>
💬 GetHashCode() refers to mutable field ID (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Accounts\Session.cs (line 211)
208 /// <summary>Gets a hash code for this session, for C# equality comparsion.</summary>
209 public override int GetHashCode()
210 {
211 return ID.GetHashCode();
212 }
213
214 /// <summary>Returns true if this session is the same as another.</summary>
💬 GetHashCode() refers to mutable field ID (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 src\Utils\MemoryNum.cs (line 4)
1namespace StableSwarmUI.Utils;
2
3/// <summary>Mini-struct to hold data about a memory (bytes) size number.</summary>
4public struct MemoryNum(long inBytes)
5{
6 public long InBytes = inBytes;
7
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MemoryNum. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Utils\MemoryNum.cs (line 4)
1namespace StableSwarmUI.Utils;
2
3/// <summary>Mini-struct to hold data about a memory (bytes) size number.</summary>
4public struct MemoryNum(long inBytes)
5{
6 public long InBytes = inBytes;
7
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MemoryNum. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 src\Text2Image\T2IParamTypes.cs (line 679)
676 {
677 throw new InvalidDataException("Unknown parameter type");
678 }
679 switch (type.Type)
680 {
681 case T2IParamDataType.INTEGER:
682 if (!long.TryParse(val, out long valInt))
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Text2Image\T2IParamTypes.cs (line 679)
676 {
677 throw new InvalidDataException("Unknown parameter type");
678 }
679 switch (type.Type)
680 {
681 case T2IParamDataType.INTEGER:
682 if (!long.TryParse(val, out long valInt))
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 10 hits
📄 src\Core\Program.cs (line 236)
233 Thread.Sleep(500);
234 try
235 {
236 switch (LaunchMode.Trim().ToLowerFast())
237 {
238 case "web":
239 Logs.Init("Launch web browser...");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Core\Program.cs (line 488)
485 public static void ApplyCommandLineSettings()
486 {
487 ReapplySettings();
488 string environment = GetCommandLineFlag("environment", "production").ToLowerFast() switch
489 {
490 "dev" or "development" => "Development",
491 "prod" or "production" => "Production",
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS032 Thread.Sleep used in async method 2 hits
📄 src\Backends\BackendHandler.cs (line 654)
651 Logs.Info($"Backend {backend.ID} ({backend.Backend.HandlerTypeData.Name}) has been locked in use for at least 5 seconds after shutdown, giving up and killing anyway.");
652 break;
653 }
654 Thread.Sleep(100);
655 }
656 tasks.Add((backend, backend.Backend.DoShutdownNow()));
657 })));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 src\Backends\BackendHandler.cs (line 654)
651 Logs.Info($"Backend {backend.ID} ({backend.Backend.HandlerTypeData.Name}) has been locked in use for at least 5 seconds after shutdown, giving up and killing anyway.");
652 break;
653 }
654 Thread.Sleep(100);
655 }
656 tasks.Add((backend, backend.Backend.DoShutdownNow()));
657 })));
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 28 hits
📄 src\BuiltinExtensions\AutoWebUIBackend\AutoWebUISelfStartBackend.cs (line 45)
42 Status = BackendStatus.ERRORED;
43 return;
44 }
45 string scrContent = File.ReadAllText(settings.StartScript);
46 if (!scrContent.Contains("%*") && !scrContent.Contains("%~")) // on Windows, it's only valid if you forward swarm's CLI args
47 {
48 Logs.Error($"Refusing init of AutoWebUI with 'webui-user.bat' target script. Please use the 'webui.bat' script instead. (If webui-user.bat usage is intentional, please forward CLI args, eg 'COMMANDLINE_ARGS=%*'.");
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\BuiltinExtensions\StabilityAPI\StabilityAPIBackend.cs (line 43)
40 Status = BackendStatus.DISABLED;
41 return;
42 }
43 Key = File.ReadAllText(fn).Trim();
44 WebClient = NetworkBackendUtils.MakeHttpClient();
45 WebClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {Key}");
46 await UpdateBalance();
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 14 hits
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIRedirectHelper.cs (line 115)
112 ComfyUIBackendExtension.ComfyBackendData backend = ComfyUIBackendExtension.ComfyBackendsDirect().First();
113 try
114 {
115 JObject result = backend.Client.GetAsync($"{backend.Address}/object_info", Utilities.TimedCancel(TimeSpan.FromMinutes(1))).Result.Content.ReadAsStringAsync().Result.ParseToJson();
116 if (result is not null)
117 {
118 LastObjectInfo = result;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIRedirectHelper.cs (line 115)
112 ComfyUIBackendExtension.ComfyBackendData backend = ComfyUIBackendExtension.ComfyBackendsDirect().First();
113 try
114 {
115 JObject result = backend.Client.GetAsync($"{backend.Address}/object_info", Utilities.TimedCancel(TimeSpan.FromMinutes(1))).Result.Content.ReadAsStringAsync().Result.ParseToJson();
116 if (result is not null)
117 {
118 LastObjectInfo = result;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS035 Synchronous task wait instead of await 6 hits
📄 src\BuiltinExtensions\GridGenerator\GridGeneratorExtension.cs (line 216)
213 if (requests < Program.ServerSettings.Backends.MaxRequestsForcedOrder)
214 {
215 Logs.Debug($"Grid Gen micro-pausing to maintain order as {requests} < {Program.ServerSettings.Backends.MaxRequestsForcedOrder}");
216 Task.Delay(20).Wait(); // Tiny few-ms delay to encourage tasks retaining order.
217 }
218 return t;
219 };
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
📄 src\Backends\SwarmSwarmBackend.cs (line 443)
440 if (user_input.InterruptToken.IsCancellationRequested)
441 {
442 // TODO: This will require separate remote sessions per-user for multiuser support
443 HttpClient.PostJson($"{Address}/API/InterruptAll", new JObject()
444 {
445 ["session_id"] = Session,
446 ["other_sessions"] = false
💬 Asynchronously wait for task completion using await instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS035-SynchronousTaskWait.md)
SS037 HttpClient instantiated directly 2 hits
📄 src\Backends\NetworkBackendUtils.cs (line 21)
18 /// <summary>Create and preconfigure a basic <see cref="HttpClient"/> instance to make web requests with.</summary>
19 public static HttpClient MakeHttpClient()
20 {
21 HttpClient client = new(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(10) });
22 client.DefaultRequestHeaders.UserAgent.ParseAdd($"StableSwarmUI/{Utilities.Version}");
23 client.Timeout = TimeSpan.FromMinutes(10);
24 return client;
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 src\Backends\NetworkBackendUtils.cs (line 21)
18 /// <summary>Create and preconfigure a basic <see cref="HttpClient"/> instance to make web requests with.</summary>
19 public static HttpClient MakeHttpClient()
20 {
21 HttpClient client = new(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(10) });
22 client.DefaultRequestHeaders.UserAgent.ParseAdd($"StableSwarmUI/{Utilities.Version}");
23 client.Timeout = TimeSpan.FromMinutes(10);
24 return client;
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS041 Unnecessary enumerable materialization 10 hits
📄 src\WebAPI\APICallReflectBuilder.cs (line 25)
22 [typeof(bool)] = (JToken input) => (bool.TryParse(input.ToString(), out bool output), output),
23 [typeof(byte)] = (JToken input) => (byte.TryParse(input.ToString(), out byte output), output),
24 [typeof(char)] = (JToken input) => (char.TryParse(input.ToString(), out char output), output),
25 [typeof(string[])] = (JToken input) => (true, input.ToList().Select(j => j.ToString()).ToArray())
26 };
27
28 public static APICall BuildFor(object obj, MethodInfo method, bool isUserUpdate)
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\BuiltinExtensions\ComfyUIBackend\ComfyUIWebAPI.cs (line 97)
94 /// <summary>API route to read a list of available Comfy custom workflows.</summary>
95 public static async Task<JObject> ComfyListWorkflows()
96 {
97 return new JObject() { ["workflows"] = JToken.FromObject(ComfyUIBackendExtension.CustomWorkflows.Keys.ToList()
98 .Select(ComfyUIBackendExtension.GetWorkflowByName).OrderBy(w => w.Name).Select(w => new JObject()
99 {
100 ["name"] = w.Name,
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS051 Locking on mutable reference 92 hits
📄 src\Accounts\User.cs (line 54)
51 public void Save()
52 {
53 Data.RawSettings = Settings.Save(false).ToString();
54 lock (SessionHandlerSource.DBLock)
55 {
56 SessionHandlerSource.UserDatabase.Upsert(Data);
57 }
💬 A lock was obtained on DBLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\Accounts\User.cs (line 63)
60 /// <summary>Returns the user generic-data for the given name, or null if not found.</summary>
61 public string GetGenericData(string dataname, string name)
62 {
63 lock (SessionHandlerSource.DBLock)
64 {
65 return SessionHandlerSource.GenericData.FindById($"{UserID}///${dataname}///{name.ToLowerFast()}")?.Data;
66 }
💬 A lock was obtained on DBLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 4 hits
📄 src\BuiltinExtensions\ImageBatchTool\ImageBatchToolExtension.cs (line 104)
101 {
102 Logs.Error($"Image generation failed: {tasks[i].Exception}");
103 }
104 tasks.RemoveAt(i--);
105 }
106 }
107 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\WebAPI\T2IAPI.cs (line 215)
212 {
213 Logs.Error($"Image generation failed: {tasks[i].Exception}");
214 }
215 tasks.RemoveAt(i--);
216 }
217 }
218 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 26 hits
📄 src\BuiltinExtensions\AutoWebUIBackend\AutoWebUIAPIAbstractBackend.cs (line 88)
85 {
86 lora = lora.BeforeLast('.');
87 }
88 promptAdd += $"<lora:{lora}:{loraWeights[i]}>";
89 }
90 }
91 JObject toSend = new()
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\BuiltinExtensions\GridGenerator\GridGenCore.cs (line 216)
213 }
214 if (key.Length < 4 || keys.Contains(key))
215 {
216 key = $"{key}{index}";
217 }
218 while (keys.Contains(key)) // Backup for if there's a key that looks like the indexed key of another value for some reason
219 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 src\Utils\Utilities.cs (line 208)
205 public static async Task<byte[]> ReceiveData(this WebSocket socket, int maxBytes, CancellationToken limit)
206 {
207 byte[] buffer = new byte[8192];
208 using MemoryStream ms = new();
209 WebSocketReceiveResult result;
210 do
211 {
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Utils\Utilities.cs (line 510)
507 public static async Task DownloadFile(string url, string filepath, Action<long, long> progressUpdate, string altUrl = null)
508 {
509 altUrl ??= url;
510 using FileStream writer = File.OpenWrite(filepath);
511 using HttpResponseMessage response = await UtilWebClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, url), HttpCompletionOption.ResponseHeadersRead, Program.GlobalProgramCancel);
512 long length = response.Content.Headers.ContentLength ?? 0;
513 byte[] buffer = new byte[Math.Min(length + 1024, 1024 * 1024 * 64)]; // up to 64 megabytes, just grab as big a chunk as we can at a time
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 2 hits
📄 src\Backends\BackendHandler.cs (line 384)
381 /// <summary>Loads the backends list from a file.</summary>
382 public void Load()
383 {
384 if (T2IBackends.Any()) // Backup to prevent duplicate calls
385 {
386 return;
387 }
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 src\Backends\BackendHandler.cs (line 384)
381 /// <summary>Loads the backends list from a file.</summary>
382 public void Load()
383 {
384 if (T2IBackends.Any()) // Backup to prevent duplicate calls
385 {
386 return;
387 }
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
SS066 Disposable field is not disposed 2 hits
📄 src\Accounts\Session.cs (line 67)
64 public CancellationToken InterruptToken;
65
66 /// <summary>Token source to interrupt just this claim's set.</summary>
67 public CancellationTokenSource LocalClaimInterrupt = new();
68
69 /// <summary>Unique claim ID from an incremental number.</summary>
70 public long ID = Interlocked.Increment(ref ClaimID);
💬 Disposable field LocalClaimInterrupt in type GenClaim is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Accounts\Session.cs (line 67)
64 public CancellationToken InterruptToken;
65
66 /// <summary>Token source to interrupt just this claim's set.</summary>
67 public CancellationTokenSource LocalClaimInterrupt = new();
68
69 /// <summary>Unique claim ID from an incremental number.</summary>
70 public long ID = Interlocked.Increment(ref ClaimID);
💬 Disposable field LocalClaimInterrupt in type GenClaim is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

winsw

230 total diagnostics across 10 rules

SS001 Async method with void return type 8 hits
📄 src\WinSW.Core\LogAppenders.cs (line 132)
129
130 protected abstract Task LogError(StreamReader errorReader);
131
132 private async void SafeLogOutput(StreamReader outputReader)
133 {
134 try
135 {
💬 Method SafeLogOutput is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\WinSW.Core\LogAppenders.cs (line 144)
141 }
142 }
143
144 private async void SafeLogError(StreamReader errorReader)
145 {
146 try
147 {
💬 Method SafeLogError is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 24 hits
📄 src\WinSW.Core\PeriodicRollingCalendar.cs (line 17)
14 {
15 this.format = format;
16 this.period = period;
17 this.currentRoll = DateTime.Now;
18 }
19
20 public void Init()
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\WinSW.Core\LogAppenders.cs (line 447)
444 {
445 writer.Dispose();
446
447 var now = DateTime.Now.AddDays(-1);
448 int nextFileNumber = this.GetNextFileNumber(extension, baseDirectory, baseFileName, now);
449 string? nextFileName = Path.Combine(baseDirectory, string.Format("{0}.{1}.#{2:D4}{3}", baseFileName, now.ToString(this.FilePattern), nextFileNumber, extension));
450 File.Move(logFile, nextFileName);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 src\WinSW.Tasks\Trim.cs (line 45)
42 continue;
43 }
44
45 if (this.usedTypes.Contains(type))
46 {
47 continue;
48 }
💬 Type TypeDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\WinSW.Tasks\Trim.cs (line 82)
79
80 if (typeRef is TypeDefinition typeDef)
81 {
82 if (!this.usedTypes.Add(typeDef))
83 {
84 return;
85 }
💬 Type TypeDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 108 hits
📄 src\WinSW.Core\Configuration\ProcessCommand.cs (line 3)
1namespace WinSW
2{
3 public struct ProcessCommand
4 {
5 public string? Executable;
6 public string? Arguments;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ProcessCommand. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\WinSW.Core\Native\FileTime.cs (line 5)
2
3namespace WinSW.Native
4{
5 internal struct FileTime
6 {
7 internal int LowDateTime;
8 internal int HighDateTime;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FileTime. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 4 hits
📄 src\WinSW.Core\WrapperService.cs (line 372)
369 var process = this.process;
370 Log.Debug("ProcessKill " + process.Id);
371 bool? result = process.Stop(this.config.StopTimeoutInMs);
372 this.LogMinimal($"Child process '{process.Format()}' " + result switch
373 {
374 true => $"canceled with code {process.ExitCode}.",
375 false => "terminated.",
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\WinSW.Core\WrapperService.cs (line 372)
369 var process = this.process;
370 Log.Debug("ProcessKill " + process.Id);
371 bool? result = process.Stop(this.config.StopTimeoutInMs);
372 this.LogMinimal($"Child process '{process.Format()}' " + result switch
373 {
374 true => $"canceled with code {process.ExitCode}.",
375 false => "terminated.",
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 24 hits
📄 src\WinSW.Core\Configuration\XmlServiceConfig.cs (line 299)
296 var patternNode = e.SelectSingleNode("pattern");
297 if (patternNode is null)
298 {
299 throw new InvalidDataException("Time Based rolling policy is specified but no pattern can be found in configuration XML.");
300 }
301
302 string? pattern = patternNode.InnerText;
💬 An exception is thrown from the getter of property LogHandler (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\WinSW.Core\Configuration\XmlServiceConfig.cs (line 319)
316 var filePatternNode = e.SelectSingleNode("pattern");
317 if (filePatternNode is null)
318 {
319 throw new InvalidDataException("Roll-Size-Time Based rolling policy is specified but no pattern can be found in configuration XML.");
320 }
321
322 var autoRollAtTimeNode = e.SelectSingleNode("autoRollAtTime");
💬 An exception is thrown from the getter of property LogHandler (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 30 hits
📄 src\WinSW.Core\LogAppenders.cs (line 675)
672 {
673 int count = newLineIndex - startIndex + 1;
674 total += count;
675 destination.Write(buffer, startIndex, count);
676 destination.Flush();
677 startIndex = (newLineIndex + 1) % BufferSize;
678 break;
💬 Async overload available for Stream.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\WinSW.Core\LogAppenders.cs (line 676)
673 int count = newLineIndex - startIndex + 1;
674 total += count;
675 destination.Write(buffer, startIndex, count);
676 destination.Flush();
677 startIndex = (newLineIndex + 1) % BufferSize;
678 break;
679 }
💬 Async overload available for Stream.Flush (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS048 Locking on discouraged object (string, Type, this) 12 hits
📄 src\WinSW.Core\WrapperService.cs (line 326)
323
324 Process StartProcessLocked()
325 {
326 lock (this)
327 {
328 return this.startingProcess = this.StartProcess(poststartExecutable, poststart.Arguments, poststart.CreateLogHandler());
329 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 src\WinSW.Core\WrapperService.cs (line 446)
443
444 Process StartProcessLocked(string executable, string? arguments, LogHandler? logHandler = null)
445 {
446 lock (this)
447 {
448 return this.stoppingProcess = this.StartProcess(executable, arguments, logHandler);
449 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 src\WinSW.Core\Download.cs (line 173)
170 try
171 {
172 using (var response = await request.GetResponseAsync().ConfigureAwait(false))
173 using (var responseStream = response.GetResponseStream())
174 using (var tmpStream = new FileStream(tmpFilePath, FileMode.Create))
175 {
176 if (supportsIfModifiedSince)
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\WinSW.Core\Download.cs (line 174)
171 {
172 using (var response = await request.GetResponseAsync().ConfigureAwait(false))
173 using (var responseStream = response.GetResponseStream())
174 using (var tmpStream = new FileStream(tmpFilePath, FileMode.Create))
175 {
176 if (supportsIfModifiedSince)
177 {
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 12 hits
📄 src\WinSW.Core\WrapperService.cs (line 27)
24
25 private readonly XmlServiceConfig config;
26
27 private Process process = null!;
28 private volatile Process? startingProcess;
29 private volatile Process? stoppingProcess;
30
💬 Disposable field process in type WrapperService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\WinSW.Core\WrapperService.cs (line 28)
25 private readonly XmlServiceConfig config;
26
27 private Process process = null!;
28 private volatile Process? startingProcess;
29 private volatile Process? stoppingProcess;
30
31 internal WinSWExtensionManager ExtensionManager { get; }
💬 Disposable field startingProcess in type WrapperService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

XUnity.AutoTranslator

224 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 src\XUnity.AutoTranslator.Plugin.Core\Web\Internal\ConnectionTrackingWebClient.cs (line 1535)
1532 {
1533 str = "application/octet-stream";
1534 }
1535 string str3 = "------------" + DateTime.Now.Ticks.ToString( "x" );
1536 this.Headers[ "Content-Type" ] = string.Format( "multipart/form-data; boundary={0}", str3 );
1537 Stream requestStream = null;
1538 Stream stream2 = null;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\XUnity.AutoTranslator.Plugin.Core\TextTranslationCache.cs (line 156)
153
154 if( anyChanges )
155 {
156 var backupFileName = input.FullName + "." + DateTime.Now.ToString( "yyyyMMddHHmmssfff.bak" );
157 File.Move( input.FullName, backupFileName );
158
159 using( var outputFile = new FileStream( input.FullName, FileMode.Create ) )
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 18 hits
📄 src\Translators\Common.ExtProtocol\Utilities\SimpleJson.cs (line 399)
396 {
397 var sb = EscapeBuilder;
398 sb.Length = 0;
399 if( sb.Capacity < aText.Length + aText.Length / 10 )
400 sb.Capacity = aText.Length + aText.Length / 10;
401 foreach( char c in aText )
402 {
💬 The operands in the divisive expression aText.Length / 10 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Translators\Common.ExtProtocol\Utilities\SimpleJson.cs (line 400)
397 var sb = EscapeBuilder;
398 sb.Length = 0;
399 if( sb.Capacity < aText.Length + aText.Length / 10 )
400 sb.Capacity = aText.Length + aText.Length / 10;
401 foreach( char c in aText )
402 {
403 switch( c )
💬 The operands in the divisive expression aText.Length / 10 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 24 hits
📄 src\XUnity.Common\Utilities\ExtensionDataHelper.cs (line 61)
58#if IL2CPP
59 if( obj is Il2CppObjectBase obj2 )
60 {
61 if( DynamicFields.TryGetValue( obj2, out object value ) )
62 {
63 if( value is Dictionary<Type, object> existingDictionary )
64 {
💬 Type Il2CppObjectBase is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\XUnity.Common\Utilities\ExtensionDataHelper.cs (line 72)
69 var newDictionary = new Dictionary<Type, object>();
70 newDictionary.Add( value.GetType(), value );
71 newDictionary[ typeof( T ) ] = t;
72 DynamicFields[ obj2 ] = newDictionary;
73 }
74 }
75 else
💬 Type Il2CppObjectBase is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 22 hits
📄 src\XUnity.RuntimeHooker.Core\Utilities\ReflectionCache.cs (line 91)
88 // override object.GetHashCode
89 public override int GetHashCode()
90 {
91 return Type.GetHashCode() + MemberName.GetHashCode();
92 }
93 }
94 }
💬 GetHashCode() refers to mutable property Type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\XUnity.RuntimeHooker.Core\Utilities\ReflectionCache.cs (line 91)
88 // override object.GetHashCode
89 public override int GetHashCode()
90 {
91 return Type.GetHashCode() + MemberName.GetHashCode();
92 }
93 }
94 }
💬 GetHashCode() refers to mutable property MemberName (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 26 hits
📄 src\XUnity.RuntimeHooker.Core\Utilities\ReflectionCache.cs (line 66)
63 return cachedMember;
64 }
65
66 public struct MemberLookupKey
67 {
68 public MemberLookupKey( Type type, string memberName )
69 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MemberLookupKey. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Translators\Common.ExtProtocol\Utilities\SimpleJson.cs (line 55)
52 public abstract partial class JSONNode
53 {
54 #region Enumerators
55 public struct Enumerator
56 {
57 private enum Type { None, Array, Object }
58 private Type type;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Enumerator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 30 hits
📄 src\XUnity.Common\Utilities\UnityInput.cs (line 213)
210
211 private static ButtonControl GetControl(KeyCode key, bool silent = false)
212 {
213 switch (key)
214 {
215 case KeyCode.None:
216 break;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\XUnity.AutoTranslator.Plugin.Core\Utilities\DynamicQueryable.cs (line 645)
642 CheckAndPromoteOperands( isEquality ? typeof( IEqualitySignatures ) : typeof( IRelationalSignatures ),
643 op.text, ref left, ref right, op.pos );
644 }
645 switch( op.id )
646 {
647 case TokenId.Equal:
648 case TokenId.DoubleEqual:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 32 hits
📄 src\XUnity.Common\Utilities\UnityInput.cs (line 213)
210
211 private static ButtonControl GetControl(KeyCode key, bool silent = false)
212 {
213 switch (key)
214 {
215 case KeyCode.None:
216 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\XUnity.AutoTranslator.Plugin.Core\Utilities\DynamicQueryable.cs (line 645)
642 CheckAndPromoteOperands( isEquality ? typeof( IEqualitySignatures ) : typeof( IRelationalSignatures ),
643 op.text, ref left, ref right, op.pos );
644 }
645 switch( op.id )
646 {
647 case TokenId.Equal:
648 case TokenId.DoubleEqual:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 src\XUnity.AutoTranslator.Plugin.Core\Web\Internal\ConnectionTrackingWebClient.cs (line 1941)
1938 {
1939 get
1940 {
1941 throw GetMustImplement();
1942 }
1943 set
1944 {
💬 An exception is thrown from the getter of property CachePolicy (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\XUnity.AutoTranslator.Plugin.Core\Web\Internal\ConnectionTrackingWebClient.cs (line 2041)
2038 {
2039 get
2040 {
2041 throw GetMustImplement();
2042 }
2043 set
2044 {
💬 An exception is thrown from the getter of property UseDefaultCredentials (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 4 hits
📄 src\Translators\Common.ExtProtocol.Executor\ExtProtocolHandler.cs (line 58)
55
56 while( true )
57 {
58 var receivedPayload = reader.ReadLine();
59 if( string.IsNullOrEmpty( receivedPayload ) ) return;
60
61 var message = ExtProtocolConvert.Decode( receivedPayload );
💬 Async overload available for StreamReader.ReadLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Translators\Common.ExtProtocol.Executor\ExtProtocolHandler.cs (line 110)
107 }
108
109 var translatedPayload = ExtProtocolConvert.Encode( response );
110 writer.WriteLine( translatedPayload );
111 }
112 else
113 {
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS044 Attribute must specify [AttributeUsage] 2 hits
📄 src\XUnity.Common\Utilities\HookingHelperPriorityAttribute.cs (line 11)
8 /// <summary>
9 /// WARNING: Pubternal API (internal). Do not use. May change during any update.
10 /// </summary>
11 public class HookingHelperPriorityAttribute : Attribute
12 {
13 /// <summary>
14 /// WARNING: Pubternal API (internal). Do not use. May change during any update.
💬 HookingHelperPriorityAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\XUnity.Common\Utilities\HookingHelperPriorityAttribute.cs (line 11)
8 /// <summary>
9 /// WARNING: Pubternal API (internal). Do not use. May change during any update.
10 /// </summary>
11 public class HookingHelperPriorityAttribute : Attribute
12 {
13 /// <summary>
14 /// WARNING: Pubternal API (internal). Do not use. May change during any update.
💬 HookingHelperPriorityAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS050 Parameter assigned in constructor 4 hits
📄 src\XUnity.AutoTranslator.Plugin.Core\UntranslatedText.cs (line 208)
205 TemplatedText = originalText.TemplatizeByNumbers();
206 if( TemplatedText != null )
207 {
208 originalText = TemplatedText.Template;
209 }
210 }
211 else
💬 Suspicious assignment of parameter originalText in constructor of UntranslatedText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
📄 src\XUnity.AutoTranslator.Plugin.Core\UntranslatedText.cs (line 216)
213 TemplatedText = templateAllNumbersAway ? originalText.TemplatizeByReplacementsAndNumbers() : originalText.TemplatizeByReplacements();
214 if( TemplatedText != null )
215 {
216 originalText = TemplatedText.Template;
217 }
218 }
219 }
💬 Suspicious assignment of parameter originalText in constructor of UntranslatedText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
SS051 Locking on mutable reference 14 hits
📄 src\XUnity.AutoTranslator.Plugin.Core\SafeFileWatcher.cs (line 86)
83
84 private void UpdateRaisingEvents( bool enabled )
85 {
86 lock( _sync )
87 {
88 if( enabled )
89 {
💬 A lock was obtained on _sync but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 src\XUnity.AutoTranslator.Plugin.Core\SimpleTextTranslationCache.cs (line 284)
281
282 private void QueueNewTranslationForDisk( string key, string value, bool hadTranslated )
283 {
284 lock( _newTranslations )
285 {
286 _newTranslations[ key ] = value;
287
💬 A lock was obtained on _newTranslations but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 4 hits
📄 src\XUnity.Common\Extensions\StringExtensions.cs (line 87)
84 var previousIndex = i - 1;
85 if( previousIndex >= 0 )
86 {
87 fileDirs.RemoveAt( i );
88 fileDirs.RemoveAt( previousIndex );
89 i -= 2;
90 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\XUnity.Common\Extensions\StringExtensions.cs (line 88)
85 if( previousIndex >= 0 )
86 {
87 fileDirs.RemoveAt( i );
88 fileDirs.RemoveAt( previousIndex );
89 i -= 2;
90 }
91 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 18 hits
📄 src\Translators\GoogleTranslateCompat.ExtProtocol\GoogleTranslateCompatTranslate.cs (line 145)
142 if( current >= translatedLines.Length ) context.Fail( "Batch operation received incorrect number of translations." );
143
144 var translatedLine = translatedLines[ current++ ];
145 translatedText += translatedLine;
146
147 if( i != untranslatedLinesCount - 1 ) translatedText += '\n';
148 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Translators\GoogleTranslateCompat.ExtProtocol\GoogleTranslateCompatTranslate.cs (line 147)
144 var translatedLine = translatedLines[ current++ ];
145 translatedText += translatedLine;
146
147 if( i != untranslatedLinesCount - 1 ) translatedText += '\n';
148 }
149
150 translatedTexts.Add( translatedText );
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 18 hits
📄 src\Translators\DeepLTranslate.ExtProtocol\ExtDeepLTranslate.cs (line 83)
80 private static readonly string Referer = Referers[ RandomNumbers.Next( Referers.Length ) ];
81 private static readonly string Origin = Origins[ RandomNumbers.Next( Origins.Length ) ];
82
83 private SemaphoreSlim _sem;
84
85 private HttpClient _client;
86 private HttpClientHandler _handler;
💬 Disposable field _sem in type ExtDeepLTranslate is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Translators\DeepLTranslate.ExtProtocol\ExtDeepLTranslate.cs (line 85)
82
83 private SemaphoreSlim _sem;
84
85 private HttpClient _client;
86 private HttpClientHandler _handler;
87 private bool _hasSetup = false;
88 private int _translationCount = 0;
💬 Disposable field _client in type ExtDeepLTranslate is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

WeiXinMPSDK

224 total diagnostics across 10 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 12 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Tools\ForTestController.cs (line 33)
30
31 Response.Cookies.Append("TestCookie", SystemTime.Now.ToString());
32
33 return Content(data + " Ajax:" + isAjax + " Server Time:" + DateTime.Now);
34 }
35
36 [HttpGet]
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Tools\ForTestController.cs (line 43)
40
41 Response.Cookies.Append("TestCookie", SystemTime.Now.ToString());
42
43 return Content(data + " Ajax:" + isAjax + " Server Time:" + DateTime.Now);
44 }
45 }
46}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 2 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\MP\WeixinController_OldPost.cs (line 191)
188 //根据MsgId去重结束
189
190 string responseXml = null;//响应消息XML
191 var responseTime = (SystemTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000 - 8 * 60 * 60;
192
193 switch (msgType)
194 {
💬 The operands in the divisive expression (SystemTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\MP\WeixinController_OldPost.cs (line 191)
188 //根据MsgId去重结束
189
190 string responseXml = null;//响应消息XML
191 var responseTime = (SystemTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000 - 8 * 60 * 60;
192
193 switch (msgType)
194 {
💬 The operands in the divisive expression (SystemTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\HomeController.cs (line 62)
59 sdkList.Add(new Home_IndexVD_AssemblyModel("开放平台", "Senparc.Weixin.Open", typeof(Senparc.Weixin.Open.Register), gitHubUrl: sdkGitHubUrl));
60 //TempData["QYVersion"] = getDisplayVersion(getFileVersionInfo("Senparc.Weixin.QY.dll"));//已经停止更新
61 sdkList.Add(new Home_IndexVD_AssemblyModel("企业微信", "Senparc.Weixin.Work", typeof(Senparc.Weixin.Work.Register), gitHubUrl: sdkGitHubUrl));
62 vd.AssemblyModelCollection[sdkGroup] = sdkList;
63
64
65 var aspnetGroup = new Home_IndexVD_GroupInfo()
💬 Type Home_IndexVD_GroupInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\HomeController.cs (line 77)
74 aspnetList.Add(new Home_IndexVD_AssemblyModel("公众号消息中间件", "Senparc.Weixin.MP.Middleware", typeof(Senparc.Weixin.MP.MessageHandlers.Middleware.MessageHandlerMiddlewareExtension), gitHubUrl: sdkGitHubUrl));
75 aspnetList.Add(new Home_IndexVD_AssemblyModel("小程序消息中间件", "Senparc.Weixin.WxOpen.Middleware", typeof(Senparc.Weixin.WxOpen.MessageHandlers.Middleware.MessageHandlerMiddlewareExtension), gitHubUrl: sdkGitHubUrl));
76 aspnetList.Add(new Home_IndexVD_AssemblyModel("企业微信消息中间件", "Senparc.Weixin.Work.Middleware", typeof(Senparc.Weixin.Work.MessageHandlers.Middleware.MessageHandlerMiddlewareExtension), gitHubUrl: sdkGitHubUrl));
77 vd.AssemblyModelCollection[aspnetGroup] = aspnetList;
78
79 var cacheAndExtensionGroup = new Home_IndexVD_GroupInfo()
80 {
💬 Type Home_IndexVD_GroupInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS032 Thread.Sleep used in async method 2 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Tools\SimulateToolController.cs (line 315)
312 }
313
314 var responseMessageXml = await MessageAgent.RequestXmlAsync(null, _serviceProvider, url, token, requestMessaageDoc.ToString(), autoFillUrlParameters, 1000 * 20);
315 Thread.Sleep(sleepMillionSeconds); //模拟服务器响应时间
316
317 _responseMessageXml = responseMessageXml;
318 return responseMessageXml;
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Tools\SimulateToolController.cs (line 315)
312 }
313
314 var responseMessageXml = await MessageAgent.RequestXmlAsync(null, _serviceProvider, url, token, requestMessaageDoc.ToString(), autoFillUrlParameters, 1000 * 20);
315 Thread.Sleep(sleepMillionSeconds); //模拟服务器响应时间
316
317 _responseMessageXml = responseMessageXml;
318 return responseMessageXml;
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 54 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\MP\WeixinController.cs (line 138)
135
136 using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt")))
137 {
138 tw.WriteLine("ExecptionMessage:" + ex.Message);
139 tw.WriteLine(ex.Source);
140 tw.WriteLine(ex.StackTrace);
141 //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\MP\WeixinController.cs (line 139)
136 using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt")))
137 {
138 tw.WriteLine("ExecptionMessage:" + ex.Message);
139 tw.WriteLine(ex.Source);
140 tw.WriteLine(ex.StackTrace);
141 //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);
142
💬 Async overload available for TextWriter.WriteLine (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 8 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\MP\AsyncMethodsController.cs (line 88)
85 public ActionResult DeadLockTest()
86 {
87 var result =
88 RequestUtility.HttpGetAsync(CommonDI.CommonSP, "https://sdk.weixin.senparc.com",
89 cookieContainer: null).Result;
90 return Content(result);
91 }
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\MP\AsyncMethodsController.cs (line 122)
119 /// <returns></returns>
120 public ActionResult DeadLockTest2()
121 {
122 var result = GetRemoteData().Result;
123 return Content(result);
124 }
125
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS049 Comparing strings without StringComparison 4 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Tools\SimulateToolController.cs (line 298)
295 }
296
297 //修改文字内容
298 if (requestMessaageDoc.Root.Element("MsgType") != null && requestMessaageDoc.Root.Element("MsgType").Value.ToUpper() == "TEXT")
299 {
300 var values = requestMessaageDoc.Root.Element("Content").Value.Split('|').Select(z => z.Trim()).ToList();
301 if (values.Count == 1)
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\TenPay\TenPayV3Controller.cs (line 489)
486
487 resHandler.SetKey(TenPayV3Info.Key);
488 //验证请求是否从微信发过来(安全)
489 if (resHandler.IsTenpaySign() && return_code.ToUpper() == "SUCCESS")
490 {
491 res = "success";//正确的订单处理
492 //直到这里,才能认为交易真正成功了,可以进行数据库操作,但是别忘了返回规定格式的消息!
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS056 HttpRequest.Form read synchronously 112 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\TenPay\TenPayController.cs (line 97)
94 string packageValue = null;
95 string paySign = null;
96
97 string sp_billno = Request.Form["order_no"];
98 //当前时间 yyyyMMdd
99 string date = SystemTime.Now.ToString("yyyyMMdd");
100
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\TenPay\TenPayController.cs (line 108)
105 }
106 else
107 {
108 sp_billno = Request.Form["order_no"].ToString();
109 }
110
111 sp_billno = TenPayInfo.PartnerId + sp_billno;
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
SS059 IAsyncDisposable not disposed asynchronously 16 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\WxOpen\WxOpenController.cs (line 119)
116 }
117 catch (Exception ex)
118 {
119 using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_WxOpen_" + _getRandomFileName() + ".txt")))
120 {
121 await tw.WriteLineAsync("ExecptionMessage:" + ex.Message);
122 await tw.WriteLineAsync(ex.Source);
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\MP\WeixinController.cs (line 136)
133 #region 异常处理
134 WeixinTrace.Log("MessageHandler错误:{0}", ex.Message);
135
136 using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt")))
137 {
138 tw.WriteLine("ExecptionMessage:" + ex.Message);
139 tw.WriteLine(ex.Source);
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 2 hits
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\TenPay\TenPayV3Controller.cs (line 998)
995 }
996 }
997
998 private Stream _fileStream = null;
999
1000 /// <summary>
1001 /// 显示二维码
💬 Disposable field _fileStream in type TenPayV3Controller is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Samples\All\net10-mvc\Senparc.Weixin.Sample.Net10\Controllers\Weixin\TenPay\TenPayV3Controller.cs (line 998)
995 }
996 }
997
998 private Stream _fileStream = null;
999
1000 /// <summary>
1001 /// 显示二维码
💬 Disposable field _fileStream in type TenPayV3Controller is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

VPet

222 total diagnostics across 13 rules

SS001 Async method with void return type 2 hits
📄 VPet-Simulator.Core\Graph\PNGAnimation.cs (line 110)
107 /// </summary>
108 public static int MaxLoadMemory = 2000;
109
110 private async void startup(string path, FileInfo[] paths)
111 {
112 while (Function.MemoryUsage() > MaxLoadMemory)
113 {
💬 Method startup is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 VPet-Simulator.Core\Graph\PNGAnimation.cs (line 110)
107 /// </summary>
108 public static int MaxLoadMemory = 2000;
109
110 private async void startup(string path, FileInfo[] paths)
111 {
112 while (Function.MemoryUsage() > MaxLoadMemory)
113 {
💬 Method startup is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 46 hits
📄 VPet-Simulator.Core\Display\MessageBar.xaml.cs (line 252)
249 /// <summary>
250 /// 流式传输用的阻断文字显示用的计时器
251 /// </summary>
252 DateTime nextshow = DateTime.Now;
253 /// <summary>
254 /// 增加显示新词
255 /// </summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 VPet-Simulator.Core\Display\MainLogic.cs (line 31)
28 /// <summary>
29 /// 上次交互时间
30 /// </summary>
31 public DateTime LastInteractionTime { get; set; } = DateTime.Now;
32 /// <summary>
33 /// 事件Timer
34 /// </summary>
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 10 hits
📄 VPet-Simulator.Core\Display\Main.xaml.cs (line 254)
251 {
252 Dispatcher.Invoke(() =>
253 {
254 LabelDisplay.Opacity = labeldisplaycount / 50;
255 });
256 }
257 }
💬 The operands in the divisive expression labeldisplaycount / 50 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 VPet-Simulator.Core\Handle\GameSave.cs (line 268)
265 if (Health <= realhel)
266 {
267 //可以确认从状态不佳和生病二选一
268 if (Health <= realhel / 2)
269 {//生病
270 return ModeType.Ill;
271 }
💬 The operands in the divisive expression realhel / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 114 hits
📄 VPet-Simulator.Core\Graph\FoodAnimation.cs (line 51)
48
49 public static void LoadGraph(GraphCore graph, FileSystemInfo path, ILine info)
50 {
51 bool isLoop = info[(gbol)"loop"];
52 FoodAnimation pa = new FoodAnimation(graph, new GraphInfo(path, info), info[(gstr)"front_lay"], info[(gstr)"back_lay"], info, isLoop);
53 graph.AddGraph(pa);
54 }
💬 Type gbol is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 VPet-Simulator.Core\Graph\FoodAnimation.cs (line 52)
49 public static void LoadGraph(GraphCore graph, FileSystemInfo path, ILine info)
50 {
51 bool isLoop = info[(gbol)"loop"];
52 FoodAnimation pa = new FoodAnimation(graph, new GraphInfo(path, info), info[(gstr)"front_lay"], info[(gstr)"back_lay"], info, isLoop);
53 graph.AddGraph(pa);
54 }
55 /// <summary>
💬 Type gstr is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 VPet-Simulator.Core\Display\WorkTimer.xaml.cs (line 44)
41 /// <summary>
42 /// 完成工作信息
43 /// </summary>
44 public struct FinishWorkInfo
45 {
46 /// <summary>
47 /// 当前完成工作
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FinishWorkInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 VPet-Simulator.Core\Display\WorkTimer.xaml.cs (line 44)
41 /// <summary>
42 /// 完成工作信息
43 /// </summary>
44 public struct FinishWorkInfo
45 {
46 /// <summary>
47 /// 当前完成工作
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FinishWorkInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 VPet-Simulator.Core\Graph\GraphHelper.cs (line 475)
472 {
473 if (m.MoveTimerSmartMove)
474 {
475 switch (LocateType)
476 {
477 case DirectionType.Top:
478 m.Core.Controller.MoveWindows(0, -m.Core.Controller.GetWindowsDistanceUp() / m.Core.Controller.ZoomRatio - LocateLength);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 VPet-Simulator.Core\Graph\GraphHelper.cs (line 475)
472 {
473 if (m.MoveTimerSmartMove)
474 {
475 switch (LocateType)
476 {
477 case DirectionType.Top:
478 m.Core.Controller.MoveWindows(0, -m.Core.Controller.GetWindowsDistanceUp() / m.Core.Controller.ZoomRatio - LocateLength);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 14 hits
📄 VPet-Simulator.Core\Display\ToolBar.xaml.cs (line 347)
344 {
345 clickCallback?.Invoke();
346 };
347 switch (parentMenu)
348 {
349 case MenuType.Feed:
350 MenuFeed.Items.Add(menuItem);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 VPet-Simulator.Core\Graph\FoodAnimation.cs (line 171)
168 //然后等待帧时间毫秒
169 Thread.Sleep(Time);
170 //判断是否要下一步
171 switch (Control.Type)
172 {
173 case TaskControl.ControlType.Stop:
174 Control.EndAction?.Invoke();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 2 hits
📄 VPet-Simulator.Core\Display\MainLogic.cs (line 62)
59 }
60 sayInfo.GraphName = SayRndFunction(sayInfo.CurrentText.ToString());
61 if (sayInfo.IsFinishGen)
62 Say(sayInfo.ToNoneStream().Result);
63 else
64 Say(sayInfo);
65 });
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 VPet-Simulator.Core\Display\MainLogic.cs (line 62)
59 }
60 sayInfo.GraphName = SayRndFunction(sayInfo.CurrentText.ToString());
61 if (sayInfo.IsFinishGen)
62 Say(sayInfo.ToNoneStream().Result);
63 else
64 Say(sayInfo);
65 });
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS051 Locking on mutable reference 4 hits
📄 VPet-Simulator.Core\Display\Main.xaml.cs (line 134)
131 {
132 if (ig3.IsFail)
133 {
134 lock (ErrorMessage) // 确保线程安全
135 {
136 ErrorMessage.Add(ig3.FailMessage);
137 ig2.Remove(ig3);
💬 A lock was obtained on ErrorMessage but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 VPet-Simulator.Core\Display\MessageBar.xaml.cs (line 263)
260 Task.Run(() =>
261 {
262 int sleeptime = 0;
263 lock (oldsaystream)
264 if (DateTime.Now < nextshow)
265 {
266 sleeptime = (int)(nextshow - DateTime.Now).TotalMilliseconds;
💬 A lock was obtained on oldsaystream but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS057 Collection manipulated during traversal 6 hits
📄 VPet-Simulator.Core\Display\Main.xaml.cs (line 95)
92 if (ig3.IsFail)
93 {
94 ErrorMessage.Add(ig3.FailMessage);
95 ig2.Remove(ig3);
96 break;
97 }
98 else
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 VPet-Simulator.Core\Display\MainDisplay.cs (line 116)
113 }
114 else
115 {
116 list.RemoveAt(i);
117 }
118 }
119 return false;
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 2 hits
📄 VPet-Simulator.Core\Display\MessageBar.xaml.cs (line 108)
105
106 for (int i = 0; i < batchSize; i++)
107 {
108 textToAdd += outputtext[0];
109 outputtext.RemoveAt(0);
110 }
111 outputtextsample.Append(textToAdd);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 VPet-Simulator.Core\Display\MessageBar.xaml.cs (line 108)
105
106 for (int i = 0; i < batchSize; i++)
107 {
108 textToAdd += outputtext[0];
109 outputtext.RemoveAt(0);
110 }
111 outputtextsample.Append(textToAdd);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 VPet-Simulator.Core\Graph\PNGAnimation.cs (line 176)
173 // Save the combined image to the cache path
174 using (var image = SKImage.FromBitmap(combinedBitmap))
175 using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
176 using (var stream = File.OpenWrite(Path))
177 {
178 data.SaveTo(stream);
179 }
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 VPet-Simulator.Core\Graph\PNGAnimation.cs (line 176)
173 // Save the combined image to the cache path
174 using (var image = SKImage.FromBitmap(combinedBitmap))
175 using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
176 using (var stream = File.OpenWrite(Path))
177 {
178 data.SaveTo(stream);
179 }
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 16 hits
📄 VPet-Simulator.Core\Display\MessageBar.xaml.cs (line 67)
64 public partial class MessageBar : UserControl, IDisposable, IMassageBar
65 {
66 public Control This => this;
67 Main m;
68 public MessageBar(Main m)
69 {
70 InitializeComponent();
💬 Disposable field m in type MessageBar is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 VPet-Simulator.Core\Display\Main.xaml.cs (line 52)
49 /// 是否开始运行
50 /// </summary>
51 public bool IsWorking { get; private set; } = false;
52 public SoundPlayer soundPlayer = new SoundPlayer();
53 public bool windowMediaPlayerAvailable = true;
54
55 public void Load_0_BaseConsole()
💬 Disposable field soundPlayer in type Main is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

slskd

206 total diagnostics across 11 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 src\slskd\Search\Types\Search.cs (line 56)
53 }
54
55 public string SearchText { get; init; }
56 public DateTime StartedAt { get; init; } = DateTime.Now;
57 public SearchStates State { get; set; }
58 public int Token { get; init; }
59 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\slskd\Search\Types\Search.cs (line 56)
53 }
54
55 public string SearchText { get; init; }
56 public DateTime StartedAt { get; init; } = DateTime.Now;
57 public SearchStates State { get; set; }
58 public int Token { get; init; }
59 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 26 hits
📄 src\slskd\Common\Cryptography\Aes.cs (line 31)
28 public static class Aes
29 {
30 private static readonly int BlockSizeInBits = 128;
31 private static readonly int BlockSizeInBytes = BlockSizeInBits / 8;
32 private static readonly int KeySizeInBits = 256;
33 private static readonly int KeySizeInBytes = KeySizeInBits / 8;
34
💬 The operands in the divisive expression BlockSizeInBits / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\slskd\Common\Cryptography\Aes.cs (line 33)
30 private static readonly int BlockSizeInBits = 128;
31 private static readonly int BlockSizeInBytes = BlockSizeInBits / 8;
32 private static readonly int KeySizeInBits = 256;
33 private static readonly int KeySizeInBytes = KeySizeInBits / 8;
34
35 /// <summary>
36 /// Decrypts the specified <paramref name="encryptedBytes"/> with the specified <paramref name="key"/>.
💬 The operands in the divisive expression KeySizeInBits / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 30 hits
📄 src\slskd\Core\Data\ConnectionStringDictionary.cs (line 34)
31
32 private Dictionary<Database, ConnectionString> Strings { get; } = [];
33
34 public ConnectionString this[Database database] => Strings[database];
35}
💬 Type Database is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\slskd\Core\Data\Migrations\Z12282025_AdditionalTransferIndexesMigration.cs (line 32)
29{
30 public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings)
31 {
32 ConnectionString = connectionStrings[Database.Transfers];
33 }
34
35 private ILogger Log { get; } = Serilog.Log.ForContext<Z12282025_AdditionalTransferIndexesMigration>();
💬 Type Database is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS033 Async overload is available 54 hits
📄 src\slskd\Common\CommonExtensions.cs (line 57)
54
55 if (completedTask == task)
56 {
57 timeoutCancellationTokenSource.Cancel();
58 return await task;
59 }
60 else
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\slskd\Common\CommonExtensions.cs (line 81)
78
79 if (completedTask == task)
80 {
81 timeoutCancellationTokenSource.Cancel();
82 await task;
83 }
84 else
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 2 hits
📄 src\slskd\Core\Options.cs (line 1284)
1281 try
1282 {
1283 // async not supported here, .Result is all we have
1284 _ = slskd.Blacklist.DetectFormat(File).Result;
1285 }
1286 catch
1287 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\slskd\Core\Options.cs (line 1284)
1281 try
1282 {
1283 // async not supported here, .Result is all we have
1284 _ = slskd.Blacklist.DetectFormat(File).Result;
1285 }
1286 catch
1287 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS037 HttpClient instantiated directly 8 hits
📄 src\slskd\Common\Dumper.cs (line 97)
94
95 private async Task Download(string url, string destination)
96 {
97 using var http = new HttpClient();
98
99 using var localStream = new FileStream(destination, FileMode.OpenOrCreate);
100 using var remoteStream = await http.GetStreamAsync(url);
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 src\slskd\Common\GitHub.cs (line 34)
31
32 try
33 {
34 using var http = new HttpClient();
35 http.DefaultRequestHeaders.UserAgent.TryParseAdd(userAgent);
36
37 var response = await http.GetFromJsonAsync<JsonDocument>(url);
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 src\slskd\Shares\ShareService.cs (line 566)
563 return;
564 }
565
566 var shares = options.Shares.Directories
567 .Select(share => share.TrimEnd('/', '\\'))
568 .ToHashSet() // remove duplicates
569 .Select(share => new Share(share)) // convert to Shares
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\slskd\Shares\ShareService.cs (line 566)
563 return;
564 }
565
566 var shares = options.Shares.Directories
567 .Select(share => share.TrimEnd('/', '\\'))
568 .ToHashSet() // remove duplicates
569 .Select(share => new Share(share)) // convert to Shares
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS044 Attribute must specify [AttributeUsage] 18 hits
📄 src\slskd\Common\Validation\AbsoluteFilePathAttribute.cs (line 26)
23 /// <summary>
24 /// Validates that the specified path is absolute.
25 /// </summary>
26 public class AbsoluteFilePathAttribute : ValidationAttribute
27 {
28 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
29 {
💬 AbsoluteFilePathAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\slskd\Common\Validation\DirectoryExistsAttributes.cs (line 28)
25 /// <summary>
26 /// Validates that the directory at the specified path exists.
27 /// </summary>
28 public class DirectoryExistsAttribute : ValidationAttribute
29 {
30 /// <summary>
31 /// Initializes a new instance of the <see cref="DirectoryExistsAttribute"/> class.
💬 DirectoryExistsAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS056 HttpRequest.Form read synchronously 4 hits
📄 src\slskd\Relay\API\Controllers\RelayController.cs (line 294)
291
292 try
293 {
294 shares = Request.Form["shares"].ToString().FromJson<IEnumerable<Share>>();
295 database = Request.Form.Files[0];
296 }
297 catch (Exception ex)
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
📄 src\slskd\Relay\API\Controllers\RelayController.cs (line 295)
292 try
293 {
294 shares = Request.Form["shares"].ToString().FromJson<IEnumerable<Share>>();
295 database = Request.Form.Files[0];
296 }
297 catch (Exception ex)
298 {
💬 Synchronously accessed HttpRequest.Form. Use HttpRequest.ReadFormAsync() instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS056-FormReadSynchronously.md)
SS059 IAsyncDisposable not disposed asynchronously 42 hits
📄 src\slskd\Common\Dumper.cs (line 99)
96 {
97 using var http = new HttpClient();
98
99 using var localStream = new FileStream(destination, FileMode.OpenOrCreate);
100 using var remoteStream = await http.GetStreamAsync(url);
101
102 await remoteStream.CopyToAsync(localStream);
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\slskd\Common\Dumper.cs (line 100)
97 using var http = new HttpClient();
98
99 using var localStream = new FileStream(destination, FileMode.OpenOrCreate);
100 using var remoteStream = await http.GetStreamAsync(url);
101
102 await remoteStream.CopyToAsync(localStream);
103 }
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 18 hits
📄 src\slskd\Relay\RelayClient.cs (line 71)
68 public IStateMonitor<RelayClientState> StateMonitor { get; }
69
70 private FileService Files { get; }
71 private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1);
72 private bool Disposed { get; set; }
73 private IHttpClientFactory HttpClientFactory { get; }
74 private HubConnection HubConnection { get; set; }
💬 Disposable field ConfigurationSyncRoot in type RelayClient is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\slskd\Relay\RelayClient.cs (line 81)
78 private TaskCompletionSource LoggedInTaskCompletionSource { get; set; }
79 private IOptionsMonitor<Options> OptionsMonitor { get; }
80 private IShareService Shares { get; }
81 private CancellationTokenSource StartCancellationTokenSource { get; set; }
82 private bool StartRequested { get; set; }
83 private ManagedState<RelayClientState> State { get; } = new();
84 private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1);
💬 Disposable field StartCancellationTokenSource in type RelayClient is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

pythonnet

182 total diagnostics across 18 rules

SS003 Integer divided by integer causing implicit rounding 26 hits
📄 src\runtime\Native\LibraryLoader.cs (line 149)
146 while (bytes < needsBytes)
147 {
148 bytes = needsBytes;
149 result = new IntPtr[bytes / IntPtr.Size];
150 if (!EnumProcessModules(self.Handle, result, bytes, out needsBytes))
151 throw new Win32Exception();
152 }
💬 The operands in the divisive expression bytes / IntPtr.Size are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\runtime\Native\LibraryLoader.cs (line 153)
150 if (!EnumProcessModules(self.Handle, result, bytes, out needsBytes))
151 throw new Win32Exception();
152 }
153 return result.Take((int)(needsBytes / IntPtr.Size)).ToArray();
154 }
155
156 [DllImport(NativeDll, SetLastError = true)]
💬 The operands in the divisive expression needsBytes / IntPtr.Size are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS005 Equals() and GetHashCode() not implemented together 10 hits
📄 src\runtime\PythonTypes\PyDict.cs (line 13)
10 /// for details.
11 /// </summary>
12 [Serializable]
13 public class PyDict : PyIterable
14 {
15 internal PyDict(BorrowedReference reference) : base(reference) { }
16 internal PyDict(in StolenReference reference) : base(reference) { }
💬 Equals() and GetHashcode() must be implemented together on PyDict (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\runtime\PythonTypes\PyFloat.cs (line 11)
8 /// PY3: https://docs.python.org/3/c-api/float.html
9 /// for details.
10 /// </summary>
11 public partial class PyFloat : PyNumber
12 {
13 internal PyFloat(in StolenReference ptr) : base(ptr)
14 {
💬 Equals() and GetHashcode() must be implemented together on PyFloat (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 src\runtime\Codecs\PyObjectConversions.cs (line 152)
149 }
150
151 public override int GetHashCode()
152 => this.ClrType.GetHashCode() ^ this.PyType.GetHashCode();
153
154 public bool Equals(TypePair other)
155 => this.PyType == other.PyType && this.ClrType == other.ClrType;
💬 GetHashCode() refers to mutable field ClrType (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\runtime\PythonTypes\PyDict.cs (line 173)
170 Runtime.PyDict_Clear(obj);
171 }
172
173 public override int GetHashCode() => rawPtr.GetHashCode();
174
175 public override bool Equals(PyObject? other)
176 {
💬 GetHashCode() refers to mutable field rawPtr (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 56 hits
📄 src\runtime\Native\NewReference.cs (line 12)
9 /// Represents a reference to a Python object, that is tracked by Python's reference counting.
10 /// </summary>
11 [NonCopyable]
12 ref struct NewReference
13 {
14 IntPtr pointer;
15
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NewReference. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\runtime\StateSerialization\MaybeMemberInfo.cs (line 8)
5namespace Python.Runtime
6{
7 [Serializable]
8 internal struct MaybeMemberInfo<T> : ISerializable where T : MemberInfo
9 {
10 // .ToString() of the serialized object
11 const string SerializationDescription = "d";
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MaybeMemberInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 src\runtime\Types\ClassBase.cs (line 638)
635 TypeManager.InitializeSlotIfEmpty(pyType, TypeOffset.mp_length, new Interop.B_P(MpLengthSlot.impl), slotsHolder);
636 }
637
638 switch (Type.GetTypeCode(type.Value))
639 {
640 case TypeCode.Boolean:
641 case TypeCode.SByte:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\runtime\Types\ClassBase.cs (line 638)
635 TypeManager.InitializeSlotIfEmpty(pyType, TypeOffset.mp_length, new Interop.B_P(MpLengthSlot.impl), slotsHolder);
636 }
637
638 switch (Type.GetTypeCode(type.Value))
639 {
640 case TypeCode.Boolean:
641 case TypeCode.SByte:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 8 hits
📄 src\runtime\ClassManager.cs (line 436)
433 {
434 var mi = (MemberInfo)items[i];
435
436 switch (mi.MemberType)
437 {
438 case MemberTypes.Method:
439 meth = (MethodInfo)mi;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\runtime\Types\ClassObject.cs (line 250)
247 {
248 if (ManagedType.GetManagedObject(op) is CLRObject clrObject)
249 {
250 switch (clrObject.inst)
251 {
252 case nint val:
253 result = new IntPtr(val);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 4 hits
📄 src\embed_tests\Codecs.cs (line 387)
384 }
385 }
386
387 public static void AcceptsDateTime(DateTime v) {}
388
389 [Test]
390 public void As_Object_AffectedByDecoders()
💬 Method AcceptsDateTime might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 src\embed_tests\Codecs.cs (line 387)
384 }
385 }
386
387 public static void AcceptsDateTime(DateTime v) {}
388
389 [Test]
390 public void As_Object_AffectedByDecoders()
💬 Method AcceptsDateTime might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS023 Exception thrown from property getter 18 hits
📄 src\runtime\Native\StrPtr.cs (line 46)
43 {
44 get
45 {
46 if (this.RawPointer == IntPtr.Zero) throw new NullReferenceException();
47
48 nuint zeroIndex = 0;
49 while (this.Bytes[zeroIndex] != 0)
💬 An exception is thrown from the getter of property ByteCount (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\runtime\PythonEngine.cs (line 67)
64 {
65 if (delegateManager == null)
66 {
67 throw new InvalidOperationException(
68 "DelegateManager has not yet been initialized using Python.Runtime.PythonEngine.Initialize().");
69 }
70 return delegateManager;
💬 An exception is thrown from the getter of property DelegateManager (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 6 hits
📄 src\runtime\InternString.cs (line 22)
19 var validNames = new HashSet<string>(identifierNames);
20 if (validNames.Count != _builtinNames.Length)
21 {
22 throw new InvalidOperationException("Identifiers args not matching");
23 }
24 foreach (var name in _builtinNames)
25 {
💬 An exception is thrown from InternString its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 src\runtime\InternString.cs (line 28)
25 {
26 if (!validNames.Contains(name))
27 {
28 throw new InvalidOperationException($"{name} is not declared");
29 }
30 }
31 }
💬 An exception is thrown from InternString its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS026 Exception thrown from equality operator 4 hits
📄 src\runtime\PythonTypes\PyObject.cs (line 1454)
1451
1452 using var _ = Py.GIL();
1453 int result = Runtime.PyObject_RichCompareBool(a.obj, b.obj, Runtime.Py_EQ);
1454 if (result < 0) throw PythonException.ThrowLastAsClrException();
1455 return result != 0;
1456 }
1457
💬 An exception is thrown from the == operator between PyObject? and PyObject? in type PyObject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS026-ExceptionThrownFromEqualityOperator.md)
📄 src\runtime\PythonTypes\PyObject.cs (line 1471)
1468
1469 using var _ = Py.GIL();
1470 int result = Runtime.PyObject_RichCompareBool(a.obj, b.obj, Runtime.Py_NE);
1471 if (result < 0) throw PythonException.ThrowLastAsClrException();
1472 return result != 0;
1473 }
1474
💬 An exception is thrown from the != operator between PyObject? and PyObject? in type PyObject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS026-ExceptionThrownFromEqualityOperator.md)
SS027 Exception thrown from Dispose 6 hits
📄 src\runtime\Py.cs (line 55)
52 public override void Dispose()
53 {
54 if (this.owner != Thread.CurrentThread)
55 throw new InvalidOperationException("GIL must always be released from the same thread, that acquired it");
56
57 base.Dispose();
58 }
💬 An exception is thrown from the Dispose() method in type DebugGILState (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
📄 src\runtime\PythonTypes\PyObject.cs (line 196)
193
194 if (Runtime.Py_IsInitialized() == 0 && Runtime._Py_IsFinalizing() != true)
195 {
196 throw new InvalidOperationException("Python runtime must be initialized");
197 }
198
199 nint refcount = Runtime.Refcount(this.obj);
💬 An exception is thrown from the Dispose(bool) method in type PyObject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS027-ExceptionThrownFromDispose.md)
SS028 Exception thrown from finalizer 2 hits
📄 src\runtime\Py.cs (line 41)
38
39 ~GILState()
40 {
41 throw new InvalidOperationException("GIL must always be released, and it must be released from the same thread that acquired it.");
42 }
43 }
44
💬 An exception is thrown from the finalizer method in type GILState (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS028-ExceptionThrownFromFinalizer.md)
📄 src\runtime\Py.cs (line 41)
38
39 ~GILState()
40 {
41 throw new InvalidOperationException("GIL must always be released, and it must be released from the same thread that acquired it.");
42 }
43 }
44
💬 An exception is thrown from the finalizer method in type GILState (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS028-ExceptionThrownFromFinalizer.md)
SS029 Exception thrown from GetHashCode 2 hits
📄 src\runtime\PythonTypes\PyObject.cs (line 1111)
1108 nint pyHash = Runtime.PyObject_Hash(obj);
1109 if (pyHash == -1 && Exceptions.ErrorOccurred())
1110 {
1111 throw PythonException.ThrowLastAsClrException();
1112 }
1113 return pyHash.GetHashCode();
1114 }
💬 An exception is thrown from the GetHashCode() method in type PyObject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS029-ExceptionThrownFromGetHashCode.md)
📄 src\runtime\PythonTypes\PyObject.cs (line 1111)
1108 nint pyHash = Runtime.PyObject_Hash(obj);
1109 if (pyHash == -1 && Exceptions.ErrorOccurred())
1110 {
1111 throw PythonException.ThrowLastAsClrException();
1112 }
1113 return pyHash.GetHashCode();
1114 }
💬 An exception is thrown from the GetHashCode() method in type PyObject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS029-ExceptionThrownFromGetHashCode.md)
SS030 Exception thrown from Equals 2 hits
📄 src\runtime\PythonTypes\PyObject.cs (line 1092)
1089 return true;
1090 }
1091 int result = Runtime.PyObject_RichCompareBool(obj, other.obj, Runtime.Py_EQ);
1092 if (result < 0) throw PythonException.ThrowLastAsClrException();
1093 return result != 0;
1094 }
1095
💬 An exception is thrown from the Equals(PyObject?) method in type PyObject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
📄 src\runtime\PythonTypes\PyObject.cs (line 1092)
1089 return true;
1090 }
1091 int result = Runtime.PyObject_RichCompareBool(obj, other.obj, Runtime.Py_EQ);
1092 if (result < 0) throw PythonException.ThrowLastAsClrException();
1093 return result != 0;
1094 }
1095
💬 An exception is thrown from the Equals(PyObject?) method in type PyObject (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS030-ExceptionThrownFromEquals.md)
SS034 Accessing Task.Result without await 4 hits
📄 src\embed_tests\TestInterrupt.cs (line 93)
90 Assert.That(asyncCall.Wait(TimeSpan.FromSeconds(5)), Is.True, "Async thread was not interrupted in time");
91 PythonEngine.EndAllowThreads(threadState);
92
93 Assert.That(asyncCall.Result, Is.EqualTo(0));
94 }
95 }
96}
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\embed_tests\TestInterrupt.cs (line 93)
90 Assert.That(asyncCall.Wait(TimeSpan.FromSeconds(5)), Is.True, "Async thread was not interrupted in time");
91 PythonEngine.EndAllowThreads(threadState);
92
93 Assert.That(asyncCall.Result, Is.EqualTo(0));
94 }
95 }
96}
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS057 Collection manipulated during traversal 2 hits
📄 src\runtime\Util\EventHandlerCollection.cs (line 101)
98 {
99 continue;
100 }
101 list.RemoveAt(i);
102 if (list.Count == 0)
103 {
104 Remove(key);
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 src\runtime\Util\EventHandlerCollection.cs (line 101)
98 {
99 continue;
100 }
101 list.RemoveAt(i);
102 if (list.Count == 0)
103 {
104 Remove(key);
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 12 hits
📄 src\runtime\Types\ClassObject.cs (line 45)
42 {
43 if (str.Length > 0)
44 {
45 str += Environment.NewLine;
46 }
47 str += t.ToString();
48 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\runtime\Types\ClassObject.cs (line 47)
44 {
45 str += Environment.NewLine;
46 }
47 str += t.ToString();
48 }
49 return Runtime.PyString_FromString(str);
50 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 6 hits
📄 src\runtime\Native\NativeTypeSpec.cs (line 10)
7 [StructLayout(LayoutKind.Sequential)]
8 struct NativeTypeSpec : IDisposable
9 {
10 public readonly StrPtr Name;
11 public readonly int BasicSize;
12 public readonly int ItemSize;
13 public readonly int Flags;
💬 Disposable field Name in type NativeTypeSpec is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\runtime\PythonTypes\PyBuffer.cs (line 11)
8{
9 public sealed class PyBuffer : IDisposable
10 {
11 private PyObject _exporter;
12 private Py_buffer _view;
13
14 internal PyBuffer(PyObject exporter, PyBUF flags)
💬 Disposable field _exporter in type PyBuffer is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

VFSForGit

180 total diagnostics across 10 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 34 hits
📄 GVFS\GVFS.Tests\NUnitRunner.cs (line 152)
149 this.args.Add(filters);
150 }
151
152 DateTime now = DateTime.Now;
153 int result = new AutoRun(Assembly.GetEntryAssembly()).Execute(this.args.ToArray());
154
155 Console.WriteLine("Completed test pass in {0}", DateTime.Now - now);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 GVFS\GVFS.Tests\NUnitRunner.cs (line 155)
152 DateTime now = DateTime.Now;
153 int result = new AutoRun(Assembly.GetEntryAssembly()).Execute(this.args.ToArray());
154
155 Console.WriteLine("Completed test pass in {0}", DateTime.Now - now);
156 Console.WriteLine();
157
158 return result;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 14 hits
📄 GVFS\GVFS.Common\ConsoleHelper.cs (line 79)
76 }
77 else
78 {
79 output.Write("\r{0}...{1}", message, waiting[(retries / 2) % waiting.Length]);
80 initialMessageWritten = true;
81 actionIsDone.WaitOne(100);
82 }
💬 The operands in the divisive expression retries / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 GVFS\GVFS.Common\SHA1Util.cs (line 62)
59
60 public static byte[] BytesFromHexString(string sha)
61 {
62 byte[] arr = new byte[sha.Length / 2];
63
64 for (int i = 0; i < arr.Length; ++i)
65 {
💬 The operands in the divisive expression sha.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 10 hits
📄 GVFS\GVFS.Common\Prefetch\Git\DiffHelper.cs (line 225)
222
223 if (result.TargetIsDirectory)
224 {
225 if (!this.stagedDirectoryOperations.Add(result))
226 {
227 EventMetadata metadata = new EventMetadata();
228 metadata.Add(nameof(result.TargetPath), result.TargetPath);
💬 Type DiffTreeResult is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 GVFS\GVFS.Common\Prefetch\Git\DiffHelper.cs (line 234)
231
232 // Since we match only on filename, re-adding is the easiest way to update the set.
233 this.stagedDirectoryOperations.Remove(result);
234 this.stagedDirectoryOperations.Add(result);
235 }
236 }
237 else
💬 Type DiffTreeResult is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 28 hits
📄 GVFS\GVFS.MSBuild\GenerateGVFSConstants.cs (line 92)
89 return false;
90 }
91
92 private struct GitVersion
93 {
94 public int Major { get; set; }
95 public int Minor { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct GitVersion. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 GVFS\GVFS.GVFlt\GVFltCallbacks.cs (line 15)
12 /// This struct should only be used by the upgrader, it has been replaced by GVFS.Virtualization.Background.FileSystemTask
13 /// </remarks>
14 [Serializable]
15 public struct BackgroundGitUpdate
16 {
17 // This enum must be present or the BinarySerializer will always deserialze Operation as 0
18 public enum OperationType
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BackgroundGitUpdate. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 8 hits
📄 GVFS\GVFS.Common\Git\LibGit2Repo.cs (line 80)
77
78 try
79 {
80 switch (Native.Object.GetType(objHandle))
81 {
82 case Native.ObjectTypes.Commit:
83 GitOid output = Native.IntPtrToGitOid(Native.Commit.GetTreeId(objHandle));
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 GVFS\GVFS.Common\Tracing\TelemetryDaemonEventListener.cs (line 69)
66 QueuedPipeStringWriterState state,
67 Exception exception)
68 {
69 switch (state)
70 {
71 case QueuedPipeStringWriterState.Failing:
72 this.RaiseListenerFailure(exception?.ToString());
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 18 hits
📄 GVFS\GVFS.Hooks\Program.cs (line 86)
83 private static void RunPreCommands(string[] args)
84 {
85 string command = GetGitCommand(args);
86 switch (command)
87 {
88 case "fetch":
89 case "pull":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 GVFS\GVFS.Common\ConsoleHelper.cs (line 110)
107 }
108 finally
109 {
110 switch (result)
111 {
112 case ActionResult.Success:
113 if (initialMessageWritten)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS040 Unused result on immutable object 2 hits
📄 GVFS\GVFS.Common\HealthCalculator\EnlistmentPathData.cs (line 176)
173 {
174 if (path.Last() == GVFSConstants.GitPathSeparator)
175 {
176 path.TrimEnd(GVFSConstants.GitPathSeparator);
177 this.ModifiedFolderPaths.Add(path);
178 }
179 else
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
📄 GVFS\GVFS.Common\HealthCalculator\EnlistmentPathData.cs (line 176)
173 {
174 if (path.Last() == GVFSConstants.GitPathSeparator)
175 {
176 path.TrimEnd(GVFSConstants.GitPathSeparator);
177 this.ModifiedFolderPaths.Add(path);
178 }
179 else
💬 The result of an operation on an immutable object is unused (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md)
SS051 Locking on mutable reference 24 hits
📄 GVFS\GVFS.Common\Database\SparseTable.cs (line 38)
35 command.CommandText = "INSERT OR REPLACE INTO Sparse (path) VALUES (@path);";
36 command.AddParameter("@path", DbType.String, GVFSDatabase.NormalizePath(directoryPath));
37
38 lock (this.writerLock)
39 {
40 command.ExecuteNonQuery();
41 }
💬 A lock was obtained on writerLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 GVFS\GVFS.Common\Database\SparseTable.cs (line 86)
83 command.CommandText = "DELETE FROM Sparse WHERE path = @path;";
84 command.AddParameter("@path", DbType.String, GVFSDatabase.NormalizePath(directoryPath));
85
86 lock (this.writerLock)
87 {
88 command.ExecuteNonQuery();
89 }
💬 A lock was obtained on writerLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 2 hits
📄 GVFS\GVFS.Common\ModifiedPathsDatabase.cs (line 247)
244 parentFolder = string.Empty;
245 for (int i = 0; i < pathParts.Length - 1; i++)
246 {
247 parentFolder += pathParts[i] + GVFSConstants.GitPathSeparatorString;
248 if (this.modifiedPaths.Contains(parentFolder))
249 {
250 return true;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 GVFS\GVFS.Common\ModifiedPathsDatabase.cs (line 247)
244 parentFolder = string.Empty;
245 for (int i = 0; i < pathParts.Length - 1; i++)
246 {
247 parentFolder += pathParts[i] + GVFSConstants.GitPathSeparatorString;
248 if (this.modifiedPaths.Contains(parentFolder))
249 {
250 return true;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 40 hits
📄 GVFS\GVFS.Common\Git\LibGit2Repo.cs (line 49)
46 this.Dispose(false);
47 }
48
49 protected ITracer Tracer { get; }
50 protected IntPtr RepoHandle { get; private set; }
51
52 public Native.ObjectTypes? GetObjectType(string sha)
💬 Disposable field Tracer in type LibGit2Repo is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 GVFS\GVFS.Common\Git\LibGit2RepoInvoker.cs (line 10)
7 public class LibGit2RepoInvoker : IDisposable
8 {
9 private readonly Func<LibGit2Repo> createRepo;
10 private readonly ITracer tracer;
11 private readonly object sharedRepoLock = new object();
12 private volatile bool disposing;
13 private volatile int activeCallers;
💬 Disposable field tracer in type LibGit2RepoInvoker is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Papercut-SMTP

174 total diagnostics across 10 rules

SS001 Async method with void return type 2 hits
📄 src\Papercut.Service.TrayNotification\AppLayer\ServiceTrayCoordinator.cs (line 128)
125 }
126 }
127
128 private async void OnServiceStatusChanged(object? sender, ServiceControllerStatus status)
129 {
130 UpdateTrayIcon();
131 }
💬 Method OnServiceStatusChanged is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Papercut.Service.TrayNotification\AppLayer\ServiceTrayCoordinator.cs (line 128)
125 }
126 }
127
128 private async void OnServiceStatusChanged(object? sender, ServiceControllerStatus status)
129 {
130 UpdateTrayIcon();
131 }
💬 Method OnServiceStatusChanged is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 76 hits
📄 src\Papercut.Core\Domain\Message\MessageEntry.cs (line 116)
113 _created = _info.CreationTime;
114 }
115
116 if (_created > DateTime.Now.Add(-TimeSpan.FromMinutes(5)))
117 {
118 _hasBeenSeen = false;
119 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Papercut.Core\Domain\Network\EndpointDefinition.cs (line 114)
111 }
112
113 // Log warnings for certificate validity issues
114 var now = DateTime.Now;
115 if (cert2.NotBefore > now)
116 {
117 Log.Warning(
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS019 Switch is missing default label 8 hits
📄 src\Papercut.Infrastructure.IPComm\PapercutIPCommClientFactory.cs (line 34)
31{
32 public PapercutIPCommClient GetClient(PapercutIPCommClientConnectTo connectTo)
33 {
34 switch (connectTo)
35 {
36 case PapercutIPCommClientConnectTo.Service:
37 return new PapercutIPCommClient(endpoints.Service, logger.ForContext<PapercutIPCommClient>());
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Papercut.Message\MessageRepository.cs (line 170)
167 var repl = replacement ?? '\0';
168 if (fancy)
169 {
170 switch (ch)
171 {
172 case '"':
173 // U+201D right double quotation mark
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 2 hits
📄 test\Papercut.Rules.Tests\MailRetentionRuleDispatchTests.cs (line 303)
300 _mockRepository.Setup(r => r.LoadMessages()).Returns(oldMessages);
301
302 var cts = new CancellationTokenSource();
303 cts.Cancel();
304
305 var action = async () => await _dispatch.DispatchAsync(rule, null, cts.Token);
306 await action.Should().ThrowAsync<OperationCanceledException>();
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 test\Papercut.Rules.Tests\MailRetentionRuleDispatchTests.cs (line 303)
300 _mockRepository.Setup(r => r.LoadMessages()).Returns(oldMessages);
301
302 var cts = new CancellationTokenSource();
303 cts.Cancel();
304
305 var action = async () => await _dispatch.DispatchAsync(rule, null, cts.Token);
306 await action.Should().ThrowAsync<OperationCanceledException>();
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 2 hits
📄 src\Papercut.Core\Infrastructure\Async\AsyncHelpers.cs (line 61)
58 {
59 SynchronizationContext.SetSynchronizationContext(null);
60
61 return task.Result;
62 }
63 finally
64 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Papercut.Core\Infrastructure\Async\AsyncHelpers.cs (line 61)
58 {
59 SynchronizationContext.SetSynchronizationContext(null);
60
61 return task.Result;
62 }
63 finally
64 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 src\Papercut.Common\Extensions\CollectionExtensions.cs (line 64)
61
62 var count = 0;
63
64 foreach (var key in keys.ToList().Where(dictionary.ContainsKey)) {
65 dictionary.Remove(key);
66 count++;
67 }
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\Papercut.Common\Extensions\CollectionExtensions.cs (line 64)
61
62 var count = 0;
63
64 foreach (var key in keys.ToList().Where(dictionary.ContainsKey)) {
65 dictionary.Remove(key);
66 count++;
67 }
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS048 Locking on discouraged object (string, Type, this) 4 hits
📄 src\Papercut.Infrastructure.IPComm\Network\PapercutIPCommServer.cs (line 57)
54 {
55 get
56 {
57 lock (this)
58 {
59 return this._isActive;
60 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 src\Papercut.Infrastructure.IPComm\Network\PapercutIPCommServer.cs (line 64)
61 }
62 private set
63 {
64 lock (this)
65 {
66 this._isActive = value;
67 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 10 hits
📄 src\Papercut.Infrastructure.IPComm\Network\PapercutIPCommClient.cs (line 118)
115 {
116 string response = (await stream.ReadStringBufferedAsync(token: token)).Trim();
117
118 if (response != AppConstants.ApplicationName.ToUpper()) return false;
119
120 var eventJson = PapercutIPCommSerializer.ToJson(@event);
121
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\Papercut.UI\Helpers\HtmlPreviewVisitor.cs (line 180)
177 // Remove any existing oncontextmenu attribute to allow WebView2 custom context menus
178 foreach (var attribute in ctx.Attributes)
179 {
180 if (attribute.Name.ToLowerInvariant() == "oncontextmenu")
181 continue;
182
183 htmlWriter.WriteAttribute(attribute);
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS059 IAsyncDisposable not disposed asynchronously 12 hits
📄 src\Papercut.Common\Extensions\FileInfoExtensions.cs (line 47)
44
45 try
46 {
47 using var ms = new MemoryStream();
48 await using var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
49
50 await fileStream.CopyToAsync(ms);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Papercut.Infrastructure.IPComm\StreamExtensions.cs (line 34)
31 {
32 if (stream == null) throw new ArgumentNullException(nameof(stream));
33
34 using var ms = new MemoryStream();
35 await stream.CopyBufferedToAsync(ms, maxBytes, bufferSize, token: token);
36
37 return ms.ToArray();
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 56 hits
📄 src\Papercut.Core\Infrastructure\BackgroundTasks\BackgroundTaskRunner.cs (line 33)
30{
31 private readonly CancellationTokenSource _cancellationTokenSource;
32 private readonly ILogger _logger;
33 private readonly Task _processingTask;
34 private readonly Channel<Func<CancellationToken, Task>> _taskChannel;
35
36 public BackgroundTaskRunner(ILogger logger)
💬 Disposable field _processingTask in type BackgroundTaskRunner is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Papercut.Message\MimeMessageLoader.cs (line 36)
33{
34 public static MemoryCache MimeMessageCache;
35
36 private readonly Task _backgroundLoader;
37
38 private readonly CancellationTokenSource _cancellationSource;
39
💬 Disposable field _backgroundLoader in type MimeMessageLoader is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

BruteShark

172 total diagnostics across 11 rules

SS001 Async method with void return type 4 hits
📄 BruteShark\BruteSharkDesktop\MainForm.cs (line 427)
424 StartLiveCaptureAsync();
425 }
426
427 private async void StartLiveCaptureAsync()
428 {
429 this.progressBar.CustomText = "Live capture is ON...";
430 this.progressBar.Refresh();
💬 Method StartLiveCaptureAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 BruteShark\BruteSharkDesktop\MainForm.cs (line 521)
518 modulesTreeView.SelectedNode = modulesTreeView.Nodes[0];
519 }
520
521 private async void CheckForUpdates()
522 {
523 try
524 {
💬 Method CheckForUpdates is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS003 Integer divided by integer causing implicit rounding 6 hits
📄 BruteShark\BruteSharkCli\PrintDataExtensions.cs (line 786)
783 if (lastRowFilledCellsCount == 0)
784 lastRowFilledCellsCount = repeatColumns;
785 int lastRowEmptyCellsCount = repeatColumns - lastRowFilledCellsCount;
786 int rowsCount = (dataRows.Count() / repeatColumns) + (dataRows.Count() % repeatColumns > 0 ? 1 : 0);
787
788 if (delimiter == null)
789 delimiter = string.Empty;
💬 The operands in the divisive expression dataRows.Count() / repeatColumns are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 BruteShark\BruteSharkDesktop\UserControls\TextProgressBar.cs (line 50)
47 SizeF len = g.MeasureString(text, f);
48 // Calculate the location of the text (the middle of progress bar)
49 // Point location = new Point(Convert.ToInt32((rect.Width / 2) - (len.Width / 2)), Convert.ToInt32((rect.Height / 2) - (len.Height / 2)));
50 Point location = new Point(Convert.ToInt32((Width / 2) - len.Width / 2), Convert.ToInt32((Height / 2) - len.Height / 2));
51 // The commented-out code will centre the text into the highlighted area only. This will centre the text regardless of the highlighted area.
52 // Draw the custom text
53 g.DrawString(text, f, Brushes.Red, location);
💬 The operands in the divisive expression Width / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 BruteShark\PcapProcessor\ProcessingPrecentsPredicator.cs (line 62)
59
60 public void NotifyAboutProcessedFile(FileInfo fileProcessed)
61 {
62 this.FilesProcessed.Add(fileProcessed);
63 this.DataProcessed = this.FilesProcessed.Sum(fi => fi.Length);
64 }
65
💬 Type FileInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 BruteShark\PcapAnalyzer\Modules\DnsModule\DnsModule.cs (line 99)
96 return;
97 }
98
99 if (_mappings.Add(response))
100 {
101 this.ParsedItemDetected(this, new ParsedItemDetectedEventArgs()
102 {
💬 Type DnsNameMapping is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 52 hits
📄 BruteShark\PcapAnalyzer\Modules\FilesExtractingModule\NetworkFile.cs (line 42)
39 public override int GetHashCode()
40 {
41 return base.GetHashCode() ^
42 this.FileData.GetHashCode() ^
43 this.Extention.GetHashCode() ^
44 this.Algorithm.GetHashCode();
45 }
💬 GetHashCode() refers to mutable property FileData (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 BruteShark\PcapAnalyzer\Modules\FilesExtractingModule\NetworkFile.cs (line 43)
40 {
41 return base.GetHashCode() ^
42 this.FileData.GetHashCode() ^
43 this.Extention.GetHashCode() ^
44 this.Algorithm.GetHashCode();
45 }
46
💬 GetHashCode() refers to mutable property Extention (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 BruteShark\BruteSharkDesktop\GithubAutoUpdater.cs (line 15)
12 public string LatestVersionUrl { get; set; }
13 }
14
15 public struct GithubUpdateReleaseResponse
16 {
17 public bool ShouldUpdate { get; set; }
18 public string NewVersionUrl { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct GithubUpdateReleaseResponse. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 BruteShark\BruteSharkDesktop\GithubAutoUpdater.cs (line 9)
6
7namespace BruteSharkDesktop
8{
9 public struct GithubReleaseVersion
10 {
11 public string Version { get; set; }
12 public string LatestVersionUrl { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct GithubReleaseVersion. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 4 hits
📄 BruteShark\PcapAnalyzer\Modules\VoipCallsModule\VoipCallsModule.cs (line 81)
78 // Check if the voip calls set already contains this call.
79 if (_voipCalls.Contains(call))
80 {
81 switch (sipRequest.Method)
82 {
83 case SIPMethodsEnum.ACK:
84 GetCall(call).CallState = CallState.InCall;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 BruteShark\PcapAnalyzer\Modules\VoipCallsModule\VoipCallsModule.cs (line 122)
119 // Check if the voip calls hash set already contains this call.
120 if (_voipCalls.Contains(call))
121 {
122 switch (sipRequest.Method)
123 {
124 case SIPMethodsEnum.ACK:
125 GetCall(call).CallState = CallState.InCall;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 8 hits
📄 BruteShark\PcapAnalyzer\Modules\PasswordsModule\CredentialsParsers\KerberosPackets\KerberosPacketParser.cs (line 47)
44 AsnElt asn_object = AsnElt.Decode(asn_buffer);
45
46 // Get the application number.
47 switch (asn_object.TagValue)
48 {
49 case (int)MessageType.krb_tgs_rep:
50 result = new KerberosTgsRepPacket(kdc_rep: asn_object.Sub[0].Sub);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 BruteShark\PcapAnalyzer\Modules\PasswordsModule\CredentialsParsers\KerberosPackets\KerberosPrincipalName.cs (line 60)
57
58 foreach (AsnElt s in principalNameData.Sub)
59 {
60 switch (s.TagValue)
61 {
62 case 0:
63 this.NameType = Convert.ToInt32(s.Sub[0].GetInteger());
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 14 hits
📄 BruteShark\PcapProcessorTest\PcapProcessorTest.cs (line 14)
11 [TestClass]
12 public class PcapProcessorTest
13 {
14 public string UdpFilePath { get; set; }
15 public string TcpFivePacketsFilePath { get; set; }
16 public string HttpSmallFilePath { get; set; }
17 public string PcapNGFile { get; set; }
💬 Method set_UdpFilePath might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 BruteShark\PcapProcessorTest\PcapProcessorTest.cs (line 16)
13 {
14 public string UdpFilePath { get; set; }
15 public string TcpFivePacketsFilePath { get; set; }
16 public string HttpSmallFilePath { get; set; }
17 public string PcapNGFile { get; set; }
18
19
💬 Method set_HttpSmallFilePath might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS051 Locking on mutable reference 6 hits
📄 BruteShark\PcapProcessor\Sniffer.cs (line 251)
248 {
249 var packet = PacketDotNet.Packet.ParsePacket(e.GetPacket().LinkLayerType, e.GetPacket().Data);
250
251 lock (_packetsQueueLock)
252 {
253 _packets.Enqueue(packet);
254 }
💬 A lock was obtained on _packetsQueueLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 BruteShark\PcapProcessor\Sniffer.cs (line 261)
258 {
259 while (true)
260 {
261 lock (_packetsQueueLock)
262 {
263 while (_packets.Count > 0)
264 {
💬 A lock was obtained on _packetsQueueLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS058 String concatenated in a loop 30 hits
📄 BruteShark\PcapAnalyzer\Modules\PasswordsModule\CredentialsParsers\TelnetPasswordParser.cs (line 73)
70 // Buffer the username (relevant for char mode).
71 // NOTE: Telnet username can be passed a char by char (Character-Mode) or
72 // at once (Line-Mode).
73 username += getNvtAsciiDataString(packet.Data);
74 }
75 else if (packetData.Contains("Password:") && state == TelnetServerState.WaitForUsername)
76 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 BruteShark\PcapAnalyzer\Modules\PasswordsModule\CredentialsParsers\TelnetPasswordParser.cs (line 82)
79 else if (state == TelnetServerState.WaitForPassword && packet.SourceIp == clientIp)
80 {
81 // Buffer the password (relevant for char mode).
82 password += getNvtAsciiDataString(packet.Data);
83 }
84 else if (packet.SourceIp == serverIp && packet.Data.Length > 0 && state == TelnetServerState.WaitForPassword)
85 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 32 hits
📄 BruteShark\BruteSharkDesktop\MainForm.cs (line 20)
17{
18 public partial class MainForm : Form
19 {
20 private CancellationTokenSource _cts;
21 private HashSet<string> _files;
22 private CommonUi.NetworkContext _networkContext;
23 private PcapProcessor.Processor _processor;
💬 Disposable field _cts in type MainForm is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 BruteShark\BruteSharkDesktop\MainForm.cs (line 27)
24 private PcapProcessor.Sniffer _sniffer;
25 private PcapAnalyzer.Analyzer _analyzer;
26
27 private GenericTableUserControl _passwordsUserControl;
28 private HashesUserControl _hashesUserControl;
29 private NetworkMapUserControl _networkMapUserControl;
30 private SessionsExplorerUserControl _sessionsExplorerUserControl;
💬 Disposable field _passwordsUserControl in type MainForm is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

FlaUI

170 total diagnostics across 8 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 10 hits
📄 src\FlaUI.Core\Capturing\InfoOverlay.cs (line 117)
114 .Replace("{mem.v.used.perc}", $"{SystemInfo.VirtualMemoryUsedPercent,5:##.00}%");
115
116 // Replace the date/time
117 var now = DateTime.Now;
118 overlayString = Regex.Replace(overlayString, @"\{dt:?(.*?)\}", m => now.ToString(m.Groups[1].Value));
119
120 // Replace the custom timespan
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\FlaUI.TestUtilities\FlaUITestBase.cs (line 67)
64 /// <summary>
65 /// static member which holds the current execution date and time
66 /// </summary>
67 private static string _testDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
68
69 /// <summary>
70 /// Path of the directory for the screenshots and videos for the tests.
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 72 hits
📄 src\FlaUI.Core\Capturing\InfoOverlay.cs (line 90)
87 }
88 else if (IsPositionCenter())
89 {
90 textPosX = bgWidth / 2 - textSize.Width / 2 - textOffsetToBg / 2;
91 }
92 // Draw the background
93 g.FillRectangle(bgBrush, bgPosX, bgPosY, bgWidth, bgHeight);
💬 The operands in the divisive expression bgWidth / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\FlaUI.Core\Capturing\InfoOverlay.cs (line 90)
87 }
88 else if (IsPositionCenter())
89 {
90 textPosX = bgWidth / 2 - textSize.Width / 2 - textOffsetToBg / 2;
91 }
92 // Draw the background
93 g.FillRectangle(bgBrush, bgPosX, bgPosY, bgWidth, bgHeight);
💬 The operands in the divisive expression textOffsetToBg / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS005 Equals() and GetHashCode() not implemented together 12 hits
📄 src\FlaUI.UIA2\UIA2FrameworkAutomationElement.cs (line 20)
17
18namespace FlaUI.UIA2
19{
20 public partial class UIA2FrameworkAutomationElement : FrameworkAutomationElementBase
21 {
22 public UIA2FrameworkAutomationElement(UIA2Automation automation, UIA.AutomationElement nativeElement) : base(automation)
23 {
💬 Equals() and GetHashcode() must be implemented together on UIA2FrameworkAutomationElement (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\FlaUI.UIA3\UIA3FrameworkAutomationElement.cs (line 18)
15
16namespace FlaUI.UIA3
17{
18 public partial class UIA3FrameworkAutomationElement : FrameworkAutomationElementBase
19 {
20 public UIA3FrameworkAutomationElement(UIA3Automation automation, UIA.IUIAutomationElement nativeElement) : base(automation)
21 {
💬 Equals() and GetHashcode() must be implemented together on UIA3FrameworkAutomationElement (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS019 Switch is missing default label 6 hits
📄 src\FlaUI.Core\Capturing\CaptureImage.cs (line 51)
48 {
49 var imageFormat = ImageFormat.Png;
50 var ext = Path.GetExtension(filePath)?.ToLower();
51 switch (ext)
52 {
53 case ".jpg":
54 case ".jpeg":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\FlaUI.Core\Capturing\CaptureImage.cs (line 51)
48 {
49 var imageFormat = ImageFormat.Png;
50 var ext = Path.GetExtension(filePath)?.ToLower();
51 switch (ext)
52 {
53 case ".jpg":
54 case ".jpeg":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 30 hits
📄 src\FlaUI.Core\AutomationElements\ComboBox.cs (line 96)
93 {
94 return edit.AsTextBox();
95 }
96 throw new Exception("ComboBox is not editable.");
97 }
98 }
99
💬 An exception is thrown from the getter of property EditableItem (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\FlaUI.Core\AutomationElements\DateTimePicker.cs (line 66)
63 return date;
64 }
65
66 throw new Exception("Unable to get the selected date from this DateTimePicker");
67 }
68 set
69 {
💬 An exception is thrown from the getter of property SelectedDate (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 6 hits
📄 src\FlaUI.Core\Input\Touch.cs (line 26)
23 {
24 if (!User32.InitializeTouchInjection())
25 {
26 throw new Win32Exception();
27 }
28 }
29
💬 An exception is thrown from Touch its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 src\FlaUI.Core\Input\Touch.cs (line 26)
23 {
24 if (!User32.InitializeTouchInjection())
25 {
26 throw new Win32Exception();
27 }
28 }
29
💬 An exception is thrown from Touch its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS033 Async overload is available 4 hits
📄 src\FlaUI.Core\Capturing\VideoRecorder.cs (line 270)
267 {
268 // Download
269 byte[] fileBytes = await _httpClient.GetByteArrayAsync(uri);
270 File.WriteAllBytes(archivePath, fileBytes);
271 // Extract
272 Directory.CreateDirectory(targetFolder);
273 await Task.Run(() =>
💬 Async overload available for File.WriteAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\FlaUI.Core\Capturing\VideoRecorder.cs (line 270)
267 {
268 // Download
269 byte[] fileBytes = await _httpClient.GetByteArrayAsync(uri);
270 File.WriteAllBytes(archivePath, fileBytes);
271 // Extract
272 Directory.CreateDirectory(targetFolder);
273 await Task.Run(() =>
💬 Async overload available for File.WriteAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS066 Disposable field is not disposed 30 hits
📄 src\FlaUI.Core\Capturing\VideoRecorder.cs (line 24)
21 {
22 private readonly VideoRecorderSettings _settings;
23 private readonly Func<VideoRecorder, CaptureImage> _captureMethod;
24 private readonly BlockingCollection<ImageData> _frames;
25 private Task? _recordTask;
26 private bool _shouldRecord;
27 private Task? _writeTask;
💬 Disposable field _frames in type VideoRecorder is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\FlaUI.Core\Capturing\VideoRecorder.cs (line 25)
22 private readonly VideoRecorderSettings _settings;
23 private readonly Func<VideoRecorder, CaptureImage> _captureMethod;
24 private readonly BlockingCollection<ImageData> _frames;
25 private Task? _recordTask;
26 private bool _shouldRecord;
27 private Task? _writeTask;
28 private DateTime _recordStartTime;
💬 Disposable field _recordTask in type VideoRecorder is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

DotnetSpider

156 total diagnostics across 15 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 52 hits
📄 src\DotnetSpider\Infrastructure\DateTimeHelper.cs (line 14)
11 {
12 get
13 {
14 var now = DateTime.Now.Date;
15 return now.AddDays(now.Day * -1 + 1);
16 }
17 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\DotnetSpider\Infrastructure\DateTimeHelper.cs (line 37)
34 /// <summary>
35 /// 当天
36 /// </summary>
37 public static DateTime Today => DateTime.Now.Date;
38
39 /// <summary>
40 /// 星期一
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 8 hits
📄 src\DotnetSpider\Proxy\ProxyService.cs (line 42)
39 _queue = new ConcurrentQueue<ProxyEntry>();
40 _dict = new ConcurrentDictionary<Uri, ProxyEntry>();
41 _ignoreCount = 6;
42 _reDetectCount = _ignoreCount / 2;
43 }
44
45 public async Task ReturnAsync(Uri proxy, HttpStatusCode statusCode)
💬 The operands in the divisive expression _ignoreCount / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\DotnetSpider\Infrastructure\BloomFilter.cs (line 147)
144 digest = KeyedHashAlgorithm.ComputeHash(data);
145 }
146
147 for (var i = 0; i < digest.Length / 4 && k < hashes; i++)
148 {
149 var h = 0;
150 for (var j = i * 4; j < i * 4 + 4; j++)
💬 The operands in the divisive expression digest.Length / 4 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 src\DotnetSpider\DataFlow\Storage\Entity\EntityBase.cs (line 121)
118 throw new SpiderException("索引列不能为空");
119 }
120
121 _tableMetadata.Value.Indexes.Add(new IndexMetadata(columns.ToArray(), isUnique));
122 return this as T;
123 }
124
💬 Type IndexMetadata is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\DotnetSpider\DataFlow\Storage\Entity\EntityBase.cs (line 121)
118 throw new SpiderException("索引列不能为空");
119 }
120
121 _tableMetadata.Value.Indexes.Add(new IndexMetadata(columns.ToArray(), isUnique));
122 return this as T;
123 }
124
💬 Type IndexMetadata is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS005 Equals() and GetHashCode() not implemented together 4 hits
📄 src\DotnetSpider\Selector\XPathSelector.cs (line 11)
8/// <summary>
9/// Xpath 查询器
10/// </summary>
11public class XPathSelector : ISelector
12{
13 private static readonly Regex AttributeXPathRegex =
14 new(@"@[\w\s-]+", RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
💬 Equals() and GetHashcode() must be implemented together on XPathSelector (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\DotnetSpider\DataFlow\Storage\Entity\IndexMetadata.cs (line 8)
5/// <summary>
6/// 索引元数据
7/// </summary>
8public class IndexMetadata
9{
10 private readonly bool _isUnique;
11 private readonly string _name;
💬 Equals() and GetHashcode() must be implemented together on IndexMetadata (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 18 hits
📄 src\DotnetSpider\HtmlAgilityPack.Css\Either.cs (line 92)
89
90 public override int GetHashCode()
91 {
92 return _value.GetHashCode();
93 }
94
95 public override bool Equals(object obj)
💬 GetHashCode() refers to mutable field _value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\DotnetSpider\HtmlAgilityPack.Css\Either.cs (line 59)
56
57 public override int GetHashCode()
58 {
59 return _value.GetHashCode();
60 }
61
62 public override bool Equals(object obj)
💬 GetHashCode() refers to mutable field _value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 6 hits
📄 src\DotnetSpider\Infrastructure\SpiderId.cs (line 5)
2
3namespace DotnetSpider.Infrastructure;
4
5public readonly struct SpiderId
6{
7 public readonly string Id;
8 public readonly string Name;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SpiderId. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\DotnetSpider\Infrastructure\MachineInfo.cs (line 76)
73 //[StructLayout(LayoutKind.Sequential, Pack = 1)]
74 [SuppressMessage("ReSharper", "InconsistentNaming")]
75#pragma warning disable 649
76 private readonly struct VmStatistics
77 {
78 public readonly int free_count; /* # 空闲内存页数量,没有被占用的 */
79 public readonly int active_count; /* # 活跃内存页数量,正在使用或者最近被使用 */
💬 Implement Equals(), GetHashCode() and ToString() methods on struct VmStatistics. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 6 hits
📄 src\DotnetSpider\HtmlAgilityPack.Css\Parser.cs (line 145)
142 }
143 else
144 {
145 switch (token.Value.Kind)
146 {
147 case TokenKind.Tilde: _generator.GeneralSibling(); break;
148 case TokenKind.Greater: _generator.Child(); break;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\DotnetSpider\Infrastructure\ObjectId.cs (line 715)
712
713 object IConvertible.ToType(Type conversionType, IFormatProvider provider)
714 {
715 switch (Type.GetTypeCode(conversionType))
716 {
717 case TypeCode.String:
718 return ((IConvertible)this).ToString(provider);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 12 hits
📄 src\DotnetSpider\HtmlAgilityPack.Css\Tokener.cs (line 117)
114 if (reader.Read() != '=')
115 throw new FormatException(string.Format("Invalid character at position {0}.", reader.Position));
116
117 switch (ch)
118 {
119 case '^': yield return Token.PrefixMatch(); break;
120 case '$': yield return Token.SuffixMatch(); break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\DotnetSpider\DataFlow\Parser\DataParser`.cs (line 30)
27 {
28 foreach (var followSelector in Model.FollowRequestSelectors)
29 {
30 switch (followSelector.SelectorType)
31 {
32 case SelectorType.Css:
33 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 8 hits
📄 src\DotnetSpider.Tests\DataParserTests.cs (line 24)
21 var request = new Request("http://cnblogs.com");
22 var dataContext =
23 new DataFlowContext(null, new SpiderOptions(), request,
24 new Response { Content = new ByteArrayContent(File.ReadAllBytes("cnblogs.html")) });
25
26
27 var dataParser = new TestDataParser();
💬 Async overload available for File.ReadAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\DotnetSpider.Tests\DataParserTests.cs (line 46)
43 var request = new Request("http://cnblogs.com");
44 var dataContext =
45 new DataFlowContext(null, new SpiderOptions(), request,
46 new Response { Content = new ByteArrayContent(File.ReadAllBytes("cnblogs.html")) });
47
48 var dataParser = new TestDataParser();
49 dataParser.SetLogger(NullLogger.Instance);
💬 Async overload available for File.ReadAllBytes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 12 hits
📄 src\DotnetSpider.Tests\MySqlQueueSchedulerTests.cs (line 60)
57 ParallelUtilities.For(0, 1000, new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = 20},
58 async _ => { await scheduler.DequeueAsync(); });
59
60 Assert.Equal(1002, scheduler.GetTotalAsync().Result);
61 await scheduler.CleanAsync();
62 }
63
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\DotnetSpider.Tests\QueueSchedulerTests.cs (line 34)
31 Parallel.For(0, 1000, new ParallelOptions {MaxDegreeOfParallelism = 20},
32 async i => { await scheduler.DequeueAsync(); });
33
34 Assert.Equal(1002, scheduler.GetTotalAsync().Result);
35 }
36
37 [Fact(DisplayName = "EnqueueAndDequeueQueueBfs")]
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 src\DotnetSpider\DataFlow\Parser\Selector.cs (line 9)
6/// <summary>
7/// 选择器特性
8/// </summary>
9public class Selector : System.Attribute
10{
11 /// <summary>
12 /// 避免被序列化出去
💬 Selector should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\DotnetSpider\DataFlow\Storage\Entity\Schema.cs (line 8)
5/// <summary>
6/// Schema 信息
7/// </summary>
8public class Schema : Attribute
9{
10 /// <summary>
11 /// 数据库名
💬 Schema should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS048 Locking on discouraged object (string, Type, this) 4 hits
📄 src\DotnetSpider\Infrastructure\MachineInfo.cs (line 292)
289 {
290 get
291 {
292 lock (typeof(MachineInfo))
293 {
294 try
295 {
💬 A lock was used on an object of type Type which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 src\DotnetSpider.Tests\RabbitMQTests.cs (line 117)
114 var counter = 0;
115 consumer.Received += async bytes =>
116 {
117 lock (this)
118 {
119 counter += 1;
120 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 2 hits
📄 src\DotnetSpider\DataFlow\Storage\Entity\EntityBase.cs (line 68)
65 // 如果未设置主键, 但实体中有名为 Id 的属性, 则默认把 Id 作为主键
66 if (_tableMetadata.Value.Primary == null || _tableMetadata.Value.Primary.Count == 0)
67 {
68 var primary = properties.FirstOrDefault(x => x.Name.ToLower() == "id");
69 if (primary != null)
70 {
71 _tableMetadata.Value.Primary = [primary.Name];
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\DotnetSpider\DataFlow\Storage\Entity\EntityBase.cs (line 68)
65 // 如果未设置主键, 但实体中有名为 Id 的属性, 则默认把 Id 作为主键
66 if (_tableMetadata.Value.Primary == null || _tableMetadata.Value.Primary.Count == 0)
67 {
68 var primary = properties.FirstOrDefault(x => x.Name.ToLower() == "id");
69 if (primary != null)
70 {
71 _tableMetadata.Value.Primary = [primary.Name];
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 8 hits
📄 src\DotnetSpider\DataFlow\Storage\Entity\SqlServerEntityStorage.cs (line 274)
271 var where = "";
272 foreach (var column in tableMetadata.Primary)
273 {
274 where += $" [{GetNameSql(column)}] = @{column} AND";
275 }
276
277 where = where.Substring(0, where.Length - 3);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\DotnetSpider\DataFlow\Storage\Entity\SqlServerEntityStorage.cs (line 314)
311 var where = "";
312 foreach (var column in tableMetadata.Primary)
313 {
314 where += $" [{GetNameSql(column)}] = @{column} AND";
315 }
316
317 where = where.Substring(0, where.Length - 3);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 10 hits
📄 src\DotnetSpider\Spider.cs (line 33)
30{
31 private readonly FlowBuilder _flowBuilder;
32 private readonly IList<IRequestSupplier> _requestSuppliers;
33 private readonly RequestedQueue _requestedQueue;
34 private AsyncMessageConsumer<byte[]> _consumer;
35 private readonly DependenceServices _services;
36 private readonly IList<DataParser> _dataParsers;
💬 Disposable field _requestedQueue in type Spider is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\DotnetSpider\Spider.cs (line 35)
32 private readonly IList<IRequestSupplier> _requestSuppliers;
33 private readonly RequestedQueue _requestedQueue;
34 private AsyncMessageConsumer<byte[]> _consumer;
35 private readonly DependenceServices _services;
36 private readonly IList<DataParser> _dataParsers;
37 private ResponseDelegate _delegate;
38
💬 Disposable field _services in type Spider is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

openai

154 total diagnostics across 11 rules

SS018 Switch does not handle all enum options 12 hits
📄 OpenAI.SDK\ObjectModels\ResponseModels\FineTuningJobResponseModels\NEpochsConverter.cs (line 10)
7{
8 public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
9 {
10 switch (reader.TokenType)
11 {
12 case JsonTokenType.String:
13 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 OpenAI.SDK\ObjectModels\ResponseModels\FineTuningJobResponseModels\NEpochsConverter.cs (line 10)
7{
8 public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
9 {
10 switch (reader.TokenType)
11 {
12 case JsonTokenType.String:
13 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 36 hits
📄 Betalgo.Ranul.OpenAI.Contracts\Responses\Base\ResponseError.cs (line 32)
29 {
30 set
31 {
32 switch (value)
33 {
34 case string s:
35 Message = s;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Betalgo.Ranul.OpenAI.Contracts\Responses\Base\ResponseError.cs (line 32)
29 {
30 set
31 {
32 switch (value)
33 {
34 case string s:
35 Message = s;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 54 hits
📄 OpenAI.SDK\ObjectModels\RequestModels\ToolDefinition.cs (line 43)
40 {
41 if (FunctionsAsObject != null && Function != null)
42 {
43 throw new ValidationException("FunctionAsObject and Function can not be assigned at the same time. One of them is should be null.");
44 }
45
46 return Function ?? FunctionsAsObject;
💬 An exception is thrown from the getter of property FunctionCalculated (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 OpenAI.SDK\ObjectModels\RequestModels\CompletionCreateRequest.cs (line 39)
36 {
37 if (Prompt != null && PromptAsList != null)
38 {
39 throw new ValidationException("Prompt and PromptAsList can not be assigned at the same time. One of them is should be null.");
40 }
41
42 if (Prompt != null)
💬 An exception is thrown from the getter of property PromptCalculated (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 4 hits
📄 OpenAI.SDK\Managers\OpenAIRealtimeService.cs (line 573)
570 /// <inheritdoc />
571 public async ValueTask DisposeAsync()
572 {
573 _disposeCts.Cancel();
574
575 if (_receiveTask != null)
576 {
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 OpenAI.SDK\Managers\OpenAIRealtimeService.cs (line 573)
570 /// <inheritdoc />
571 public async ValueTask DisposeAsync()
572 {
573 _disposeCts.Cancel();
574
575 if (_receiveTask != null)
576 {
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 2 hits
📄 OpenAI.Utilities\Embedding\EmbeddingTools.cs (line 146)
143 public string CreateContext(string question, DataFrame df, int maxLen = 1800)
144 {
145 // Get the embeddings for the question
146 var questionEmbeddingResult = _sdk.Embeddings.CreateEmbedding(new()
147 {
148 Input = question,
149 Model = _embeddingModel
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 OpenAI.Utilities\Embedding\EmbeddingTools.cs (line 146)
143 public string CreateContext(string question, DataFrame df, int maxLen = 1800)
144 {
145 // Get the embeddings for the question
146 var questionEmbeddingResult = _sdk.Embeddings.CreateEmbedding(new()
147 {
148 Input = question,
149 Model = _embeddingModel
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS037 HttpClient instantiated directly 6 hits
📄 OpenAI.SDK\Managers\OpenAIService.cs (line 27)
24 if (httpClient == null)
25 {
26 _disposeHttpClient = true;
27 _httpClient = new();
28 }
29 else
30 {
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 OpenAI.SDK\Managers\OpenAIService.cs (line 27)
24 if (httpClient == null)
25 {
26 _disposeHttpClient = true;
27 _httpClient = new();
28 }
29 else
30 {
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS041 Unnecessary enumerable materialization 6 hits
📄 OpenAI.SDK\Tokenizer\GPT3\TokenizerGpt3.cs (line 115)
112 return cachedResult;
113 }
114
115 List<string> word = (from x in token.ToList() select x.ToString()).ToList();
116 var pairs = GetPairs(word);
117 if (pairs.Count == 0)
118 {
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 OpenAI.SDK\Tokenizer\GPT3\TokenizerGpt3.cs (line 115)
112 return cachedResult;
113 }
114
115 List<string> word = (from x in token.ToList() select x.ToString()).ToList();
116 var pairs = GetPairs(word);
117 if (pairs.Count == 0)
118 {
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS049 Comparing strings without StringComparison 6 hits
📄 OpenAI.SDK\ObjectModels\ResponseModels\FineTuningJobResponseModels\NEpochsConverter.cs (line 15)
12 case JsonTokenType.String:
13 {
14 var stringValue = reader.GetString();
15 if (stringValue?.ToLower() == "auto")
16 return -1;
17 break;
18 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 OpenAI.SDK\ObjectModels\ResponseModels\FineTuningJobResponseModels\NEpochsConverter.cs (line 15)
12 case JsonTokenType.String:
13 {
14 var stringValue = reader.GetString();
15 if (stringValue?.ToLower() == "auto")
16 return -1;
17 break;
18 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 6 hits
📄 OpenAI.Playground\TestHelpers\ChatCompletionTestHelper.cs (line 377)
374 {
375 if (functionArguments.TryGetValue(i, out var currentArguments))
376 {
377 currentArguments += fn.Arguments;
378 }
379 else
380 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 OpenAI.Playground\TestHelpers\ChatCompletionTestHelper.cs (line 377)
374 {
375 if (functionArguments.TryGetValue(i, out var currentArguments))
376 {
377 currentArguments += fn.Arguments;
378 }
379 else
380 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 OpenAI.Playground\TestHelpers\RealtimeHelpers\VoiceInput.cs (line 110)
107 /// <param name="filePath">Path to the audio file to send</param>
108 public async Task SendAudioFile(string filePath)
109 {
110 using var audioFileReader = new AudioFileReader(filePath);
111 // Calculate buffer size based on minimum buffer duration
112 var bufferSize = (int)(audioFileReader.WaveFormat.AverageBytesPerSecond * (MinimumBufferMs / 1000.0));
113 var buffer = new byte[bufferSize];
💬 AudioFileReader can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 OpenAI.Playground\TestHelpers\RealtimeHelpers\VoiceInput.cs (line 110)
107 /// <param name="filePath">Path to the audio file to send</param>
108 public async Task SendAudioFile(string filePath)
109 {
110 using var audioFileReader = new AudioFileReader(filePath);
111 // Calculate buffer size based on minimum buffer duration
112 var bufferSize = (int)(audioFileReader.WaveFormat.AverageBytesPerSecond * (MinimumBufferMs / 1000.0));
113 var buffer = new byte[bufferSize];
💬 AudioFileReader can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 18 hits
📄 OpenAI.SDK\Managers\OpenAIRealtimeService.cs (line 197)
194 private readonly ILogger<OpenAIRealtimeService> _logger;
195 private readonly OpenAIOptions _openAIOptions;
196 private readonly SemaphoreSlim _sendLock = new(1, 1);
197 private Task? _receiveTask;
198 private ClientWebSocket? _webSocket;
199 private readonly object _webSocketLock = new();
200
💬 Disposable field _receiveTask in type OpenAIRealtimeService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 OpenAI.SDK\Managers\OpenAIRealtimeService.cs (line 198)
195 private readonly OpenAIOptions _openAIOptions;
196 private readonly SemaphoreSlim _sendLock = new(1, 1);
197 private Task? _receiveTask;
198 private ClientWebSocket? _webSocket;
199 private readonly object _webSocketLock = new();
200
201 private readonly ClientEventsImplementation _clientEvents;
💬 Disposable field _webSocket in type OpenAIRealtimeService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

luban

152 total diagnostics across 12 rules

SS003 Integer divided by integer causing implicit rounding 4 hits
📄 src\Luban.Cpp\CodeTarget\CppCodeTargetBase.cs (line 160)
157 GenerateSchemaCpp(ctx,
158 beanTypes.GetRange(startIndex, Math.Min(typeCountPerStubFile, beanTypes.Count - startIndex)),
159 schemaFileName,
160 $"{schemaFileNameWithoutExt}_{startIndex / typeCountPerStubFile}.cpp")));
161 }
162
163 Task.WaitAll(cppTasks.ToArray());
💬 The operands in the divisive expression startIndex / typeCountPerStubFile are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Luban.DataLoader.Builtin\Excel\Cell.cs (line 40)
37
38 private static string ToAlphaString(int column)
39 {
40 int h = column / 26;
41 int n = column % 26;
42 return $"{(h > 0 ? ((char)('A' + h - 1)).ToString() : "")}{(char)('A' + n)}";
43 }
💬 The operands in the divisive expression column / 26 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 62 hits
📄 src\Luban.Core\DataTransformer\DataTransfomerBase.cs (line 218)
215 {
216 DType newKey = ele.Key.Apply(this, mapType.KeyType);
217 DType newValue = ele.Value.Apply(this, mapType.ValueType);
218 newDatas[newKey] = newValue;
219 }
220 return new DMap(data.Type, newDatas);
221 }
💬 Type DType is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Luban.Core\Datas\DSet.cs (line 41)
38 var set = new HashSet<DType>();
39 foreach (var data in datas)
40 {
41 if (!set.Add(data))
42 {
43 throw new Exception($"set 的 value:{data} 重复");
44 }
💬 Type DType is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 6 hits
📄 src\Luban.Core\Serialization\ByteBuf.cs (line 1699)
1696 public override int GetHashCode()
1697 {
1698 int hash = 17;
1699 for (int i = ReaderIndex; i < WriterIndex; i++)
1700 {
1701 hash = hash * 23 + Bytes[i];
1702 }
💬 GetHashCode() refers to mutable property ReaderIndex (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Luban.Core\Serialization\ByteBuf.cs (line 1699)
1696 public override int GetHashCode()
1697 {
1698 int hash = 17;
1699 for (int i = ReaderIndex; i < WriterIndex; i++)
1700 {
1701 hash = hash * 23 + Bytes[i];
1702 }
💬 GetHashCode() refers to mutable property WriterIndex (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 6 hits
📄 src\Luban.Core\Serialization\ByteBuf.cs (line 27)
24
25namespace Luban.Serialization;
26
27public readonly struct SegmentSaveState
28{
29 public SegmentSaveState(int readerIndex, int writerIndex)
30 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SegmentSaveState. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Luban.Core\Serialization\ThreadLocalTemporalByteBufPool.cs (line 23)
20
21namespace Luban.Serialization;
22
23public readonly struct TemporalByteBuf : IDisposable
24{
25 public ByteBuf Buf { get; }
26
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TemporalByteBuf. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 6 hits
📄 src\Luban.Core\DataTarget\DataExporterBase.cs (line 33)
30 public virtual void Handle(GenerationContext ctx, IDataTarget dataTarget, OutputFileManifest manifest)
31 {
32 List<DefTable> tables = dataTarget.ExportAllRecords ? ctx.Tables : ctx.ExportTables;
33 switch (dataTarget.AggregationType)
34 {
35 case AggregationType.Table:
36 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Luban.Core\Defs\DefField.cs (line 131)
128 // throw new Exception($"type:{HostType.FullName} field:{Name} type:{Type} is collection or bean. not support nullable");
129 //}
130
131 switch (CType)
132 {
133 case TArray t:
134 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 src\Luban.DataLoader.Builtin\Excel\TitleRow.cs (line 47)
44 }
45 else
46 {
47 throw new Exception($"简单数据类型字段 不支持子列名或者多行");
48 }
49 }
50 }
💬 An exception is thrown from the getter of property Current (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\Luban.DataLoader.Builtin\Excel\TitleRow.cs (line 106)
103 {
104 return Elements.All(e => e.IsBlank);
105 }
106 throw new Exception();
107 }
108 }
109
💬 An exception is thrown from the getter of property IsBlank (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS034 Accessing Task.Result without await 16 hits
📄 src\Luban.Core\DataLoader\DataLoaderManager.cs (line 64)
61 var records = new List<Record>();
62 foreach (var task in tasks)
63 {
64 records.AddRange(task.Result);
65 }
66 ctx.AddDataTable(table, records, null);
67 }
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Luban.Core\CodeTarget\CodeTargetBase.cs (line 212)
209 Task.WaitAll(tasks.ToArray());
210 foreach (var task in tasks)
211 {
212 manifest.AddFile(task.Result);
213 }
214 }
215
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS044 Attribute must specify [AttributeUsage] 4 hits
📄 src\Luban.Core\PostProcess\PostProcessAttribute.cs (line 34)
31 DataConvert = 0x4,
32}
33
34public class PostProcessAttribute : BehaviourBaseAttribute
35{
36 public TargetFileType TargetFileType { get; }
37
💬 PostProcessAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\Luban.Core\CustomBehaviour\BehaviourBaseAttribute.cs (line 23)
20
21namespace Luban.CustomBehaviour;
22
23public abstract class BehaviourBaseAttribute : Attribute, ICustomBehaviour
24{
25 public string Name { get; }
26
💬 BehaviourBaseAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS048 Locking on discouraged object (string, Type, this) 22 hits
📄 src\Luban.Core\GenerationContext.cs (line 261)
258
259 public object GetUniqueObject(string key)
260 {
261 lock (this)
262 {
263 return _uniqueObjects[key];
264 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 src\Luban.Core\GenerationContext.cs (line 269)
266
267 public object TryGetUniqueObject(string key)
268 {
269 lock (this)
270 {
271 _uniqueObjects.TryGetValue(key, out var obj);
272 return obj;
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS049 Comparing strings without StringComparison 4 hits
📄 src\Luban.Core\Utils\TimeZoneUtil.cs (line 48)
45 }
46 }
47 }
48 if (timeZoneName.ToLower() == "local")
49 {
50 return TimeZoneInfo.Local;
51 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\Luban.Core\Utils\TimeZoneUtil.cs (line 52)
49 {
50 return TimeZoneInfo.Local;
51 }
52 if (timeZoneName.ToLower() == "utc")
53 {
54 return TimeZoneInfo.Utc;
55 }
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 14 hits
📄 src\Luban.Java\TypeVisitors\JavaJsonUnderlyingDeserializeVisitor.cs (line 97)
94 typeStr = $"{type.FinalElementType.Apply(JavaDeclaringTypeNameVisitor.Ins)}[{__n}]";
95 for (int i = 0; i < type.Dimension - 1; i++)
96 {
97 typeStr += "[]";
98 }
99 }
100 return $"{{ com.google.gson.JsonArray _json{depth}_ = {json}.getAsJsonArray(); int {__n} = _json{depth}_.size(); {x} = new {typeStr}; int {__index}=0; for(JsonElement {__e} : _json{depth}_) {{ {type.ElementType.Apply(JavaDeclaringTypeNameVisitor.Ins)} {__v}; {type.ElementType.Apply(this, $"{__e}", $"{__v}", depth + 1)} {x}[{__index}++] = {__v}; }} }}";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Luban.Java\TypeVisitors\JavaBinUnderlyingDeserializeVisitor.cs (line 97)
94 typeStr = $"{type.FinalElementType.Apply(JavaDeclaringTypeNameVisitor.Ins)}[{__n}]";
95 for (int i = 0; i < type.Dimension - 1; i++)
96 {
97 typeStr += "[]";
98 }
99 }
100 return $"{{int {__n} = {bufName}.readSize(); {fieldName} = new {typeStr};for(int {__i} = 0 ; {__i} < {__n} ; {__i}++) {{ {type.ElementType.Apply(JavaDeclaringTypeNameVisitor.Ins)} {__e};{type.ElementType.Apply(this, bufName, __e, depth + 1)} {fieldName}[{__i}] = {__e};}}}}";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 src\Luban.Core\Utils\FileUtil.cs (line 179)
176 public static async Task<byte[]> ReadAllBytesAsync(string file)
177 {
178 // File.ReadAllBytesAsync 无法读取被打开的excel文件,只好重新实现了一个
179 using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
180 long count = fs.Length;
181 var bytes = new byte[count];
182 int writeIndex = 0;
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Luban.Core\Utils\FileUtil.cs (line 223)
220
221 public static async Task WriteAllBytesAsync(string file, byte[] bytes)
222 {
223 using var fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
224 long count = bytes.LongLength;
225 fs.SetLength(count);
226 fs.Seek(0, SeekOrigin.Begin);
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)

netch

146 total diagnostics across 10 rules

SS001 Async method with void return type 2 hits
📄 Netch\Forms\MainForm.cs (line 1276)
1273 Hide();
1274 }
1275
1276 public async void Exit(bool forceExit = false, bool saveConfiguration = true)
1277 {
1278 if (!IsWaiting() && !Global.Settings.StopWhenExited && !forceExit)
1279 {
💬 Method Exit is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Netch\Forms\MainForm.cs (line 1276)
1273 Hide();
1274 }
1275
1276 public async void Exit(bool forceExit = false, bool saveConfiguration = true)
1277 {
1278 if (!IsWaiting() && !Global.Settings.StopWhenExited && !forceExit)
1279 {
💬 Method Exit is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS003 Integer divided by integer causing implicit rounding 10 hits
📄 Netch\Utils\DelayTestHelper.cs (line 15)
12
13 private static readonly AsyncSemaphore PoolLock = new(16);
14
15 public static readonly NumberRange Range = new(0, int.MaxValue / 1000);
16
17 private static bool _enabled = true;
18
💬 The operands in the divisive expression int.MaxValue / 1000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Netch\Forms\MainForm.cs (line 106)
103
104 private void RecordSize()
105 {
106 _numberBoxWidth = ServerComboBox.Width / 10;
107 _numberBoxX = _numberBoxWidth * 9;
108 _numberBoxWrap = _numberBoxWidth / 30;
109
💬 The operands in the divisive expression ServerComboBox.Width / 10 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 40 hits
📄 Netch\Forms\BindingForm.cs (line 20)
17 protected virtual void BindTextBox<T>(TextBoxBase control, Func<T, bool> check, Action<T> save, object value)
18 {
19 control.Text = value.ToString();
20 _checkActions.Add(control,
21 s =>
22 {
23 try
💬 Type Control is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Netch\Forms\BindingForm.cs (line 33)
30 }
31 });
32
33 _saveActions.Add(control, c => save((T)Convert.ChangeType(((TextBoxBase)c).Text, typeof(T))));
34 }
35
36 protected void BindCheckBox(CheckBox control, Action<bool> save, bool value)
💬 Type Control is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 10 hits
📄 Netch\Models\NatTypeTestResult.cs (line 3)
1namespace Netch.Models;
2
3public struct NatTypeTestResult
4{
5 public string? Result;
6 public string? LocalEnd;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NatTypeTestResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Netch\Models\NetRoute.cs (line 6)
3
4namespace Netch.Models;
5
6public struct NetRoute
7{
8 public static NetRoute TemplateBuilder(string gateway, int interfaceIndex, int metric = 0)
9 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NetRoute. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 8 hits
📄 Netch\Controllers\Guard.cs (line 88)
85 for (var i = 0; i < 1000; i++)
86 {
87 await Task.Delay(50);
88 switch (State)
89 {
90 case State.Started:
91 OnStarted();
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Netch\Forms\MainForm.cs (line 992)
989 DelayTestHelper.Enabled = IsWaiting(_state);
990
991 StatusText();
992 switch (value)
993 {
994 case State.Waiting:
995 ControlButton.Enabled = true;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 40 hits
📄 Netch\Controllers\Guard.cs (line 88)
85 for (var i = 0; i < 1000; i++)
86 {
87 await Task.Delay(50);
88 switch (State)
89 {
90 case State.Started:
91 OnStarted();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Netch\Utils\Utils.cs (line 148)
145 public static void ComponentIterator(in Component component, in Action<Component> func)
146 {
147 func.Invoke(component);
148 switch (component)
149 {
150 case ListView listView:
151 // ListView sub item
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 2 hits
📄 Netch\Forms\SubscriptionForm.cs (line 26)
23 get
24 {
25 if (SubscriptionLinkListView.MultiSelect)
26 throw new Exception();
27
28 return SubscriptionLinkListView.SelectedIndices.Count == 0 ? -1 : SubscriptionLinkListView.SelectedIndices[0];
29 }
💬 An exception is thrown from the getter of property SelectedIndex (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 Netch\Forms\SubscriptionForm.cs (line 26)
23 get
24 {
25 if (SubscriptionLinkListView.MultiSelect)
26 throw new Exception();
27
28 return SubscriptionLinkListView.SelectedIndices.Count == 0 ? -1 : SubscriptionLinkListView.SelectedIndices[0];
29 }
💬 An exception is thrown from the getter of property SelectedIndex (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS034 Accessing Task.Result without await 4 hits
📄 Netch\Controllers\TUNController.cs (line 137)
134 string binDriver = Path.Combine(Global.NetchDir, Constants.WintunDllFile);
135 string sysDriver = $@"{Environment.SystemDirectory}\wintun.dll";
136
137 var binHash = Utils.Utils.Sha256CheckSumAsync(binDriver).Result;
138 var sysHash = Utils.Utils.Sha256CheckSumAsync(sysDriver).Result;
139 Log.Information("Built-in wintun.dll Hash: {Hash}", binHash);
140 Log.Information("Installed wintun.dll Hash: {Hash}", sysHash);
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Netch\Controllers\TUNController.cs (line 138)
135 string sysDriver = $@"{Environment.SystemDirectory}\wintun.dll";
136
137 var binHash = Utils.Utils.Sha256CheckSumAsync(binDriver).Result;
138 var sysHash = Utils.Utils.Sha256CheckSumAsync(sysDriver).Result;
139 Log.Information("Built-in wintun.dll Hash: {Hash}", binHash);
140 Log.Information("Installed wintun.dll Hash: {Hash}", sysHash);
141 if (binHash == sysHash)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS047 LINQ traversal before filter 2 hits
📄 Netch\Forms\MainForm.cs (line 52)
49
50 private void AddAddServerToolStripMenuItems()
51 {
52 foreach (var serversUtil in ServerHelper.ServerUtilDictionary.Values.OrderBy(i => i.Priority).Where(i => !string.IsNullOrEmpty(i.FullName)))
53 {
54 var fullName = serversUtil.FullName;
55 var control = new ToolStripMenuItem
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 Netch\Forms\MainForm.cs (line 52)
49
50 private void AddAddServerToolStripMenuItems()
51 {
52 foreach (var serversUtil in ServerHelper.ServerUtilDictionary.Values.OrderBy(i => i.Priority).Where(i => !string.IsNullOrEmpty(i.FullName)))
53 {
54 var fullName = serversUtil.FullName;
55 var control = new ToolStripMenuItem
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS066 Disposable field is not disposed 28 hits
📄 Netch\Forms\ServerForm.cs (line 21)
18 private readonly Dictionary<Control, Action<object>> _saveActions = new();
19
20 private int _controlLines = 2;
21 private Label AddressLabel;
22 protected TextBox AddressTextBox;
23
24 private readonly IContainer components = null;
💬 Disposable field AddressLabel in type ServerForm is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Netch\Forms\ServerForm.cs (line 22)
19
20 private int _controlLines = 2;
21 private Label AddressLabel;
22 protected TextBox AddressTextBox;
23
24 private readonly IContainer components = null;
25
💬 Disposable field AddressTextBox in type ServerForm is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

NetCoreServer

138 total diagnostics across 4 rules

SS003 Integer divided by integer causing implicit rounding 64 hits
📄 source\NetCoreServer\Utilities.cs (line 25)
22
23 if (absBytes >= (1024L * 1024L * 1024L * 1024L))
24 {
25 long tb = bytes / (1024L * 1024L * 1024L * 1024L);
26 long gb = (bytes % (1024L * 1024L * 1024L * 1024L)) / (1024 * 1024 * 1024);
27 sb.Append(tb);
28 sb.Append('.');
💬 The operands in the divisive expression bytes / (1024L * 1024L * 1024L * 1024L) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 source\NetCoreServer\Utilities.cs (line 26)
23 if (absBytes >= (1024L * 1024L * 1024L * 1024L))
24 {
25 long tb = bytes / (1024L * 1024L * 1024L * 1024L);
26 long gb = (bytes % (1024L * 1024L * 1024L * 1024L)) / (1024 * 1024 * 1024);
27 sb.Append(tb);
28 sb.Append('.');
29 sb.Append((gb < 100) ? "0" : "");
💬 The operands in the divisive expression (bytes % (1024L * 1024L * 1024L * 1024L)) / (1024 * 1024 * 1024) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS019 Switch is missing default label 2 hits
📄 source\NetCoreServer\WebSocket.cs (line 459)
456 {
457 WsFinalReceived = true;
458
459 switch (WsOpcode)
460 {
461 case WS_PING:
462 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 source\NetCoreServer\WebSocket.cs (line 459)
456 {
457 WsFinalReceived = true;
458
459 switch (WsOpcode)
460 {
461 case WS_PING:
462 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 60 hits
📄 examples\HttpClient\Program.cs (line 60)
57
58 if (commands[0].ToUpper() == "HEAD")
59 {
60 var response = client.SendHeadRequest(commands[1]).Result;
61 Console.WriteLine(response);
62 }
63 else if (commands[0].ToUpper() == "GET")
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 examples\HttpClient\Program.cs (line 65)
62 }
63 else if (commands[0].ToUpper() == "GET")
64 {
65 var response = client.SendGetRequest(commands[1]).Result;
66 Console.WriteLine(response);
67 }
68 else if (commands[0].ToUpper() == "POST")
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS066 Disposable field is not disposed 12 hits
📄 source\NetCoreServer\HttpsSession.cs (line 21)
18 /// <summary>
19 /// Get the static content cache
20 /// </summary>
21 public FileCache Cache { get; }
22
23 /// <summary>
24 /// Get the HTTP request
💬 Disposable field Cache in type HttpsSession is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 source\NetCoreServer\HttpsClient.cs (line 411)
408 #endregion
409
410 private TaskCompletionSource<HttpResponse> _tcs = new TaskCompletionSource<HttpResponse>();
411 private Timer _timer;
412
413 private void SetResultValue(HttpResponse response)
414 {
💬 Disposable field _timer in type HttpsClientEx is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Serilog

134 total diagnostics across 3 rules

SS003 Integer divided by integer causing implicit rounding 14 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 64 hits
No source samples extracted
SS066 Disposable field is not disposed 56 hits
No source samples extracted

OneOf

130 total diagnostics across 3 rules

SS004 Elementary methods of type in collection not overridden 2 hits
📄 OneOf.SourceGenerator.Tests\SourceGeneratorTests.cs (line 102)
99 NestedGeneric nested1 = new List<List<string>> { new() { "a", "b", "c" } };
100 Assert.True(nested1.IsT0);
101
102 NestedGeneric nested2 = new Dictionary<List<string>, string> { { new List<string> { "a", "b", "c" }, "d" } };
103 Assert.True(nested2.IsT2);
104 }
105
💬 Type List is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 OneOf.SourceGenerator.Tests\SourceGeneratorTests.cs (line 102)
99 NestedGeneric nested1 = new List<List<string>> { new() { "a", "b", "c" } };
100 Assert.True(nested1.IsT0);
101
102 NestedGeneric nested2 = new Dictionary<List<string>, string> { { new List<string> { "a", "b", "c" }, "d" } };
103 Assert.True(nested2.IsT2);
104 }
105
💬 Type List is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 120 hits
📄 OneOf\Types\Assorted.cs (line 14)
11 public struct True { }
12 public struct False { }
13
14 public struct All { }
15 public struct Some { }
16
17 public struct None
💬 Implement Equals(), GetHashCode() and ToString() methods on struct All. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 OneOf\Types\Assorted.cs (line 12)
9
10 public struct Unknown { }
11 public struct True { }
12 public struct False { }
13
14 public struct All { }
15 public struct Some { }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct False. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS033 Async overload is available 8 hits
📄 Generator\Program.cs (line 14)
11for (var i = 1; i < 10; i++) {
12 var output = GetContent(true, i);
13 var outpath = Combine(sourceRoot, $"OneOf\\OneOfT{i - 1}.generated.cs");
14 File.WriteAllText(outpath, output);
15
16 var output2 = GetContent(false, i);
17 var outpath2 = Combine(sourceRoot, $"OneOf\\OneOfBaseT{i - 1}.generated.cs");
💬 Async overload available for File.WriteAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Generator\Program.cs (line 18)
15
16 var output2 = GetContent(false, i);
17 var outpath2 = Combine(sourceRoot, $"OneOf\\OneOfBaseT{i - 1}.generated.cs");
18 File.WriteAllText(outpath2, output2);
19}
20
21for (var i = 10; i < 33; i++) {
💬 Async overload available for File.WriteAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)

Flow.Launcher

126 total diagnostics across 11 rules

SS001 Async method with void return type 14 hits
📄 Plugins\Flow.Launcher.Plugin.WebSearch\SearchSourceSetting.xaml.cs (line 34)
31 }
32
33 [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "<Pending>")]
34 private async void Initialize(IList<SearchSource> sources, PluginInitContext context, Action action)
35 {
36 InitializeComponent();
37 DataContext = _viewModel;
💬 Method Initialize is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Plugins\Flow.Launcher.Plugin.WebSearch\SearchSourceSetting.xaml.cs (line 34)
31 }
32
33 [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "<Pending>")]
34 private async void Initialize(IList<SearchSource> sources, PluginInitContext context, Action action)
35 {
36 InitializeComponent();
37 DataContext = _viewModel;
💬 Method Initialize is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 26 hits
📄 Plugins\Flow.Launcher.Plugin.Explorer\ViewModels\SettingsViewModel.cs (line 207)
204 }
205 }
206
207 public string PreviewPanelDateFormatDemo => DateTime.Now.ToString(PreviewPanelDateFormat, CultureInfo.CurrentCulture);
208 public string PreviewPanelTimeFormatDemo => DateTime.Now.ToString(PreviewPanelTimeFormat, CultureInfo.CurrentCulture);
209
210 public bool ShowPreviewPanelDateTimeChoices => ShowCreatedDateInPreviewPanel || ShowModifiedDateInPreviewPanel;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Plugins\Flow.Launcher.Plugin.Explorer\ViewModels\SettingsViewModel.cs (line 208)
205 }
206
207 public string PreviewPanelDateFormatDemo => DateTime.Now.ToString(PreviewPanelDateFormat, CultureInfo.CurrentCulture);
208 public string PreviewPanelTimeFormatDemo => DateTime.Now.ToString(PreviewPanelTimeFormat, CultureInfo.CurrentCulture);
209
210 public bool ShowPreviewPanelDateTimeChoices => ShowCreatedDateInPreviewPanel || ShowModifiedDateInPreviewPanel;
211
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 6 hits
📄 Flow.Launcher.Infrastructure\StringMatcher.cs (line 204)
201 // return acronym match if all query char matched
202 if (acronymsMatched > 0 && acronymsMatched == query.Length)
203 {
204 int acronymScore = acronymsMatched * 100 / acronymsTotalCount;
205
206 if (acronymScore >= (int)UserSettingSearchPrecision)
207 {
💬 The operands in the divisive expression acronymsMatched * 100 / acronymsTotalCount are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Flow.Launcher.Infrastructure\StringMatcher.cs (line 321)
318 // A match found near the beginning of a string is scored more than a match found near the end
319 // A match is scored more if the characters in the patterns are closer to each other,
320 // while the score is lower if they are more spread out
321 var score = 100 * (query.Length + 1) / ((1 + firstIndex) + (matchLen + 1));
322
323 // Give more weight to a match that is closer to the start of the string.
324 // if the first matched char is immediately before space and all strings are contained in the compare string e.g. 'world' matching 'hello world'
💬 The operands in the divisive expression 100 * (query.Length + 1) / ((1 + firstIndex) + (matchLen + 1)) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 6 hits
📄 Plugins\Flow.Launcher.Plugin.Explorer\Search\SearchManager.cs (line 157)
154 if (IsResultTypeFilteredByActionKeyword(search.Type, actions))
155 continue;
156
157 results.Add(ResultManager.CreateResult(query, search));
158 }
159 }
160 catch (OperationCanceledException)
💬 Type Result is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Plugins\Flow.Launcher.Plugin.Explorer\Search\SearchManager.cs (line 223)
220
221 var retrievedDirectoryPath = FilesFolders.ReturnPreviousDirectoryIfIncompleteString(path);
222
223 results.Add(retrievedDirectoryPath.EndsWith(":\\")
224 ? ResultManager.CreateDriveSpaceDisplayResult(retrievedDirectoryPath, query.ActionKeyword, useIndexSearch)
225 : ResultManager.CreateOpenCurrentFolderResult(retrievedDirectoryPath, query.ActionKeyword, useIndexSearch));
226
💬 Type Result is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 22 hits
📄 Flow.Launcher.Plugin\PluginPair.cs (line 50)
47 /// <returns></returns>
48 public override int GetHashCode()
49 {
50 var hashcode = Metadata.ID?.GetHashCode() ?? 0;
51 return hashcode;
52 }
53 }
💬 GetHashCode() refers to mutable property Metadata (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Plugins\Flow.Launcher.Plugin.Program\Views\Models\ProgramSource.cs (line 85)
82
83 public override int GetHashCode()
84 {
85 return uniqueIdentifier.GetHashCode();
86 }
87 }
88}
💬 GetHashCode() refers to mutable field uniqueIdentifier (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 14 hits
📄 Plugins\Flow.Launcher.Plugin.Explorer\Helper\ShellContextMenuDisplayHelper.cs (line 477)
474}
475
476[StructLayout(LayoutKind.Sequential)]
477public struct CMINVOKECOMMANDINFO
478{
479 public uint cbSize;
480 public uint fMask;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CMINVOKECOMMANDINFO. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Plugins\Flow.Launcher.Plugin.Explorer\Helper\ShellContextMenuDisplayHelper.cs (line 491)
488}
489
490[StructLayout(LayoutKind.Sequential)]
491public struct MENUITEMINFO
492{
493 public uint cbSize;
494 public uint fMask;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MENUITEMINFO. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 2 hits
📄 Plugins\Flow.Launcher.Plugin.Explorer\Search\ResultManager.cs (line 81)
78 var yOfScreenCenter = screenWithMouseCursor.WorkingArea.Top + screenWithMouseCursor.WorkingArea.Height / 2;
79 var showPosition = new System.Drawing.Point((int)xOfScreenCenter, (int)yOfScreenCenter);
80
81 switch (type)
82 {
83 case ResultType.File:
84 var fileInfo = new FileInfo[] { new(path) };
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Plugins\Flow.Launcher.Plugin.Explorer\Search\ResultManager.cs (line 81)
78 var yOfScreenCenter = screenWithMouseCursor.WorkingArea.Top + screenWithMouseCursor.WorkingArea.Height / 2;
79 var showPosition = new System.Drawing.Point((int)xOfScreenCenter, (int)yOfScreenCenter);
80
81 switch (type)
82 {
83 case ResultType.File:
84 var fileInfo = new FileInfo[] { new(path) };
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 24 hits
📄 Plugins\Flow.Launcher.Plugin.Calculator\Main.cs (line 191)
188 // Find the top-level comma that separates the two arguments of pow.
189 for (var i = 0; i < argsContent.Length; i++)
190 {
191 switch (argsContent[i])
192 {
193 case '(':
194 case '[':
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Plugins\Flow.Launcher.Plugin.Calculator\Main.cs (line 191)
188 // Find the top-level comma that separates the two arguments of pow.
189 for (var i = 0; i < argsContent.Length; i++)
190 {
191 switch (argsContent[i])
192 {
193 case '(':
194 case '[':
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 4 hits
📄 Flow.Launcher.Core\ExternalPlugins\CommunityPluginStore.cs (line 49)
46 // one of the requests completed successfully; keep its results
47 // and cancel the remaining http requests.
48 pluginResults = result;
49 cts.Cancel();
50 }
51 }
52 tasks.Remove(completedTask);
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Flow.Launcher.Core\Plugin\PluginInstaller.cs (line 121)
118 throw new FileNotFoundException("The zip file does not contain a plugin.json file.");
119
120 using Stream stream = pluginJsonEntry.Open();
121 plugin = JsonSerializer.Deserialize<UserPlugin>(stream);
122 plugin.IcoPath = "Images\\zipfolder.png";
123 plugin.LocalInstallPath = filePath;
124 }
💬 Async overload available for JsonSerializer.Deserialize (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS059 IAsyncDisposable not disposed asynchronously 6 hits
📄 Flow.Launcher.Core\Plugin\PluginInstaller.cs (line 120)
117 var pluginJsonEntry = archive.Entries.FirstOrDefault(x => x.Name == "plugin.json") ??
118 throw new FileNotFoundException("The zip file does not contain a plugin.json file.");
119
120 using Stream stream = pluginJsonEntry.Open();
121 plugin = JsonSerializer.Deserialize<UserPlugin>(stream);
122 plugin.IcoPath = "Images\\zipfolder.png";
123 plugin.LocalInstallPath = filePath;
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Flow.Launcher.Core\Plugin\JsonRPCPlugin.cs (line 181)
178 }
179
180 var sourceBuffer = BufferManager.GetStream();
181 using var errorBuffer = BufferManager.GetStream();
182
183 var sourceCopyTask = process.StandardOutput.BaseStream.CopyToAsync(sourceBuffer, token);
184 var errorCopyTask = process.StandardError.BaseStream.CopyToAsync(errorBuffer, token);
💬 RecyclableMemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 2 hits
📄 Flow.Launcher.Infrastructure\DialogJump\Models\WindowsDialog.cs (line 77)
74
75 // After jumping folder, file editor handle of Save / SaveAs file dialogs cannot be found anymore
76 // So we need to cache the current tab and use the original handle
77 private IDialogJumpDialogWindowTab _currentTab { get; set; } = null;
78
79 private readonly DialogType _dialogType;
80
💬 Disposable field _currentTab in type WindowsDialogWindow is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Flow.Launcher.Infrastructure\DialogJump\Models\WindowsDialog.cs (line 77)
74
75 // After jumping folder, file editor handle of Save / SaveAs file dialogs cannot be found anymore
76 // So we need to cache the current tab and use the original handle
77 private IDialogJumpDialogWindowTab _currentTab { get; set; } = null;
78
79 private readonly DialogType _dialogType;
80
💬 Disposable field _currentTab in type WindowsDialogWindow is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Respawn

124 total diagnostics across 3 rules

SS058 String concatenated in a loop 84 hits
📄 Respawn\MySqlAdapter.cs (line 42)
39 {
40 var args = string.Join(",", tableGroup.Tables.Select(table => $"'{table.Schema}.{table.Name}'"));
41
42 commandText += " AND t.TABLE_SCHEMA + '.' + t.TABLE_NAME NOT IN (" + args + ")";
43 }
44 else
45 {
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Respawn\MySqlAdapter.cs (line 48)
45 {
46 var args = string.Join(",", tableGroup.Tables.Select(table => $"'{table.Name}'"));
47
48 commandText += " AND t.TABLE_NAME NOT IN (" + args + ")";
49 }
50 }
51 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 16 hits
📄 Respawn.DatabaseTests\SnowflakeTests.cs (line 52)
49
50 private async Task ExecuteNonQueryAsync(string commandText)
51 {
52 using (var command = _connection.CreateCommand())
53 {
54 command.CommandText = commandText;
55 await command.ExecuteNonQueryAsync();
💬 DbCommand can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Respawn.DatabaseTests\SnowflakeTests.cs (line 257)
254
255 private async Task InsertDataAsync(string tableName, int value)
256 {
257 using (var command = _connection.CreateCommand())
258 {
259 command.CommandText = $"INSERT INTO {tableName} (Value) VALUES ({value})";
260 await command.ExecuteNonQueryAsync();
💬 DbCommand can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 24 hits
📄 Respawn.DatabaseTests\SqliteTests.cs (line 16)
13 public class SqliteTests : IAsyncLifetime
14 {
15 private readonly ITestOutputHelper _output;
16 private SqliteConnection _connection;
17 private Database _database;
18 private string _dbFileName;
19
💬 Disposable field _connection in type SqliteTests is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Respawn.DatabaseTests\SqliteTests.cs (line 17)
14 {
15 private readonly ITestOutputHelper _output;
16 private SqliteConnection _connection;
17 private Database _database;
18 private string _dbFileName;
19
20 public SqliteTests(ITestOutputHelper output) => _output = output;
💬 Disposable field _database in type SqliteTests is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Translumo

122 total diagnostics across 10 rules

SS001 Async method with void return type 8 hits
📄 src\Translumo\MVVM\ViewModels\ChatWindowViewModel.cs (line 175)
172 }
173 }
174
175 private async void OnLoadedCommand()
176 {
177 SendHelpText();
178
💬 Method OnLoadedCommand is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 src\Translumo\MVVM\ViewModels\SettingsViewModel.cs (line 93)
90 }
91 }
92
93 private async void OnAboutDialogOpened()
94 {
95 await DialogService.ShowDialogAsync(new AboutDialogViewModel() {HasUpdates = HasUpdates});
96 }
💬 Method OnAboutDialogOpened is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 src\Translumo.Translation\Papago\PapagoEncodingProvider.cs (line 46)
43
44 private static long GetTimeMs()
45 {
46 var time = (DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1));
47 return (long)(time.TotalMilliseconds + 0.5);
48 }
49
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Translumo.Translation\Papago\PapagoEncodingProvider.cs (line 46)
43
44 private static long GetTimeMs()
45 {
46 var time = (DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1));
47 return (long)(time.TotalMilliseconds + 0.5);
48 }
49
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 10 hits
📄 src\Translumo.Utils\Extensions\StringExtensions.cs (line 20)
17 return 0.0;
18 }
19
20 int distanceSep = (Math.Min(str.Length, anotherStr.Length) / 2) + 1;
21 StringBuilder builder = GetCommonCharacters(str, anotherStr, distanceSep);
22 int length = builder.Length;
23 if (length == 0)
💬 The operands in the divisive expression Math.Min(str.Length, anotherStr.Length) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Translumo.Infrastructure\Encryption\AesEncryptionService.cs (line 10)
7{
8 public class AesEncryptionService : IEncryptionService
9 {
10 private const int AES_BLOCK_BYTE_SIZE = 128 / 8;
11
12 private const int PASSWORD_SALT_BYTE_SIZE = 128 / 8;
13 private const int PASSWORD_BYTE_SIZE = 256 / 8;
💬 The operands in the divisive expression 128 / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS005 Equals() and GetHashCode() not implemented together 8 hits
📄 src\Translumo\HotKeys\GamepadHotKeyInfo.cs (line 5)
2
3namespace Translumo.HotKeys
4{
5 public class GamepadHotKeyInfo
6 {
7 public GamepadKeyCode Key { get; set; }
8
💬 Equals() and GetHashcode() must be implemented together on GamepadHotKeyInfo (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 src\Translumo\HotKeys\HotKeyInfo.cs (line 5)
2
3namespace Translumo.HotKeys
4{
5 public class HotKeyInfo
6 {
7 public Key Key { get; set; }
8
💬 Equals() and GetHashcode() must be implemented together on HotKeyInfo (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS008 GetHashCode() refers to mutable or static member 2 hits
📄 src\Translumo.Infrastructure\Language\LanguageDescriptor.cs (line 46)
43
44 public override int GetHashCode()
45 {
46 return Language.GetHashCode();
47 }
48 }
49}
💬 GetHashCode() refers to mutable property Language (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Translumo.Infrastructure\Language\LanguageDescriptor.cs (line 46)
43
44 public override int GetHashCode()
45 {
46 return Language.GetHashCode();
47 }
48 }
49}
💬 GetHashCode() refers to mutable property Language (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 2 hits
📄 src\Translumo.Utils\Http\HttpReader.cs (line 99)
96 {
97 if (ThrowExceptions)
98 {
99 throw ex;
100 }
101 return new HttpResponse(isSuccessful: false, null, ex);
102 }
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 src\Translumo.Utils\Http\HttpReader.cs (line 99)
96 {
97 if (ThrowExceptions)
98 {
99 throw ex;
100 }
101 return new HttpResponse(isSuccessful: false, null, ex);
102 }
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 12 hits
📄 src\Translumo.Utils\IntertopStruct\Rect.cs (line 6)
3namespace Translumo.Utils.IntertopStruct
4{
5 [StructLayout(LayoutKind.Sequential)]
6 public struct RECT
7 {
8 public int Left; // x position of upper-left corner
9 public int Top; // y position of upper-left corner
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RECT. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\Translumo.Infrastructure\Python\PythonCommand.cs (line 11)
8
9namespace Translumo.Infrastructure.Python
10{
11 public struct PythonCommandResult
12 {
13 public string Output { get; init; }
14
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PythonCommandResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 4 hits
📄 src\Translumo\Utils\ChatWindowConfigurationExtensions.cs (line 16)
13
14 public static Brush GetTextForegroundBrush(this ChatWindowConfiguration configuration, TextTypes textType)
15 {
16 switch (textType)
17 {
18 case TextTypes.Translation:
19 return GetTranslationTextBrush(configuration.FontColor);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Translumo\Utils\ChatWindowConfigurationExtensions.cs (line 16)
13
14 public static Brush GetTextForegroundBrush(this ChatWindowConfiguration configuration, TextTypes textType)
15 {
16 switch (textType)
17 {
18 case TextTypes.Translation:
19 return GetTranslationTextBrush(configuration.FontColor);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 26 hits
📄 src\Translumo.OCR\WindowsOCR\WindowsOCREngine.cs (line 45)
42 using (var randStream = new InMemoryRandomAccessStream())
43 {
44 bitmap.Save(randStream.AsStream(), ImgFormat);
45 var decoder = BitmapDecoder.CreateAsync(randStream).AsTask().Result;
46 softwareBitmap = decoder.GetSoftwareBitmapAsync().AsTask().Result;
47 }
48
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Translumo.OCR\WindowsOCR\WindowsOCREngine.cs (line 46)
43 {
44 bitmap.Save(randStream.AsStream(), ImgFormat);
45 var decoder = BitmapDecoder.CreateAsync(randStream).AsTask().Result;
46 softwareBitmap = decoder.GetSoftwareBitmapAsync().AsTask().Result;
47 }
48
49 OcrResult result = MsEngine.RecognizeAsync(softwareBitmap).AsTask().Result;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS066 Disposable field is not disposed 48 hits
📄 src\Translumo.Infrastructure\MachineLearning\MlPredictor.cs (line 15)
12
13 private readonly MLContext _context;
14 private ITransformer _model;
15 private PredictionEngine<TInput, TOutput> _predictor;
16
17 public MlPredictor()
18 {
💬 Disposable field _predictor in type MlPredictor is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Translumo.OCR\Tesseract\TesseractOCREngine.cs (line 20)
17 public virtual int Confidence => 1;
18 public virtual byte PrimaryPriority => 3;
19
20 protected TesseractEngine Engine;
21 protected bool IsInitialized;
22
23 protected const string LINES_SEPARATOR = "\n";
💬 Disposable field Engine in type TesseractOCREngine is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

modular-monolith-with-ddd

116 total diagnostics across 7 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 20 hits
📄 src\BuildingBlocks\Tests\IntegrationTests\Probing\Timeout.cs (line 14)
11
12 public bool HasTimedOut()
13 {
14 return DateTime.Now > _endTime;
15 }
16 }
17}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\BuildingBlocks\Tests\IntegrationTests\Probing\Timeout.cs (line 9)
6
7 public Timeout(int duration)
8 {
9 this._endTime = DateTime.Now.AddMilliseconds(duration);
10 }
11
12 public bool HasTimedOut()
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 src\API\CompanyName.MyMeetings.API\Configuration\Extensions\SwaggerExtensions.cs (line 37)
34 options.AddSecurityRequirement(new OpenApiSecurityRequirement
35 {
36 {
37 new OpenApiSecurityScheme
38 {
39 Reference = new OpenApiReference
40 {
💬 Type OpenApiSecurityScheme is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\API\CompanyName.MyMeetings.API\Configuration\Extensions\SwaggerExtensions.cs (line 37)
34 options.AddSecurityRequirement(new OpenApiSecurityRequirement
35 {
36 {
37 new OpenApiSecurityScheme
38 {
39 Reference = new OpenApiReference
40 {
💬 Type OpenApiSecurityScheme is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 16 hits
📄 src\BuildingBlocks\Application\Emails\EmailMessage.cs (line 3)
1namespace CompanyName.MyMeetings.BuildingBlocks.Application.Emails
2{
3 public struct EmailMessage
4 {
5 public string To { get; }
6
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EmailMessage. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\BuildingBlocks\Application\Queries\PageData.cs (line 3)
1namespace CompanyName.MyMeetings.BuildingBlocks.Application.Queries
2{
3 public struct PageData
4 {
5 public int Offset { get; }
6
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PageData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS023 Exception thrown from property getter 4 hits
📄 src\API\CompanyName.MyMeetings.API\Configuration\ExecutionContext\ExecutionContextAccessor.cs (line 29)
26 x => x.Type == "sub").Value);
27 }
28
29 throw new ApplicationException("User context is not available");
30 }
31 }
32
💬 An exception is thrown from the getter of property UserId (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\API\CompanyName.MyMeetings.API\Configuration\ExecutionContext\ExecutionContextAccessor.cs (line 44)
41 _httpContextAccessor.HttpContext.Request.Headers[CorrelationMiddleware.CorrelationHeaderKey]);
42 }
43
44 throw new ApplicationException("Http context and correlation id is not available");
45 }
46 }
47
💬 An exception is thrown from the getter of property CorrelationId (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS032 Thread.Sleep used in async method 2 hits
📄 src\Tests\SUT\SeedWork\AsyncOperationsHelper.cs (line 92)
89 return;
90 }
91
92 Thread.Sleep(100);
93 }
94
95 throw new Exception("Timeout for processing elapsed.");
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 src\Tests\SUT\SeedWork\AsyncOperationsHelper.cs (line 92)
89 return;
90 }
91
92 Thread.Sleep(100);
93 }
94
95 throw new Exception("Timeout for processing elapsed.");
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS059 IAsyncDisposable not disposed asynchronously 64 hits
📄 src\Modules\Meetings\Infrastructure\Configuration\EventsBus\IntegrationEventGenericHandler.cs (line 15)
12 {
13 public async Task Handle(T @event)
14 {
15 using (var scope = MeetingsCompositionRoot.BeginLifetimeScope())
16 {
17 using (var connection = scope.Resolve<ISqlConnectionFactory>().GetOpenConnection())
18 {
💬 ILifetimeScope can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Modules\Meetings\Infrastructure\MeetingsModule.cs (line 23)
20
21 public async Task<TResult> ExecuteQueryAsync<TResult>(IQuery<TResult> query)
22 {
23 using (var scope = MeetingsCompositionRoot.BeginLifetimeScope())
24 {
25 var mediator = scope.Resolve<IMediator>();
26
💬 ILifetimeScope can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 8 hits
📄 src\Modules\Meetings\Infrastructure\MeetingsContext.cs (line 38)
35
36 public DbSet<MeetingMemberCommentLike> MeetingMemberCommentLikes { get; set; }
37
38 private readonly ILoggerFactory _loggerFactory;
39
40 public MeetingsContext(DbContextOptions options, ILoggerFactory loggerFactory)
41 : base(options)
💬 Disposable field _loggerFactory in type MeetingsContext is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Modules\UserAccess\Infrastructure\UserAccessContext.cs (line 20)
17
18 public DbSet<InternalCommand> InternalCommands { get; set; }
19
20 private readonly ILoggerFactory _loggerFactory;
21
22 public UserAccessContext(DbContextOptions options, ILoggerFactory loggerFactory)
23 : base(options)
💬 Disposable field _loggerFactory in type UserAccessContext is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

imewlconverter

108 total diagnostics across 8 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 16 hits
📄 src\ImeWlConverterCore\ConsoleRun.cs (line 358)
355
356 private void MainBody_ProcessNotice(string message)
357 {
358 Console.WriteLine(DateTime.Now.ToString("HH:mm:ss") + "\t" + message);
359 }
360
361 [RequiresUnreferencedCode("Calls System.Reflection.Assembly.GetTypes()")]
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\ImeWlConverterCore\IME\Win10MsWubi.cs (line 115)
112 bw.Write(BitConverter.GetBytes(0x40 + 4 * wlList.Count)); //phrase_start=phrase_offset_start + 4*phrase_count
113 bw.Write(BitConverter.GetBytes(0)); //phrase_end input after process all!
114 bw.Write(BitConverter.GetBytes(wlList.Count)); //phrase_count
115 bw.Write(BitConverter.GetBytes(DateTime.Now.Ticks)); //timestamp
116 bw.Write(BitConverter.GetBytes((long)0)); //0
117 bw.Write(BitConverter.GetBytes((long)0)); //0
118 bw.Write(BitConverter.GetBytes((long)0)); //0
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 26 hits
📄 src\ImeWlConverterCore\IME\ZiGuangPinyinUwl.cs (line 118)
115 var wl = new WordLibrary();
116 var lenWord = stream.ReadByte();
117 var lenCode = stream.ReadByte();
118 lenCode = lenCode % 0x10 * 2 + lenWord / 0x80;
119 lenWord = lenWord % 0x80 - 1;
120 lenByte = 4 + lenWord + lenCode * 2;
121
💬 The operands in the divisive expression lenWord / 0x80 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\ImeWlConverterCore\Filters\RankPercentageFilter.cs (line 29)
26 public WordLibraryList Filter(WordLibraryList list)
27 {
28 if (Percentage == 100) return list;
29 var count = list.Count * Percentage / 100;
30 list.Sort((a, b) => a.Rank - b.Rank);
31 var result = new WordLibraryList();
32 for (var i = 0; i < count; i++) result.Add(list[i]);
💬 The operands in the divisive expression list.Count * Percentage / 100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 20 hits
📄 src\ImeWlConverterCore\Generaters\Cangjie5Generater.cs (line 31)
28{
29 public bool IgnoreContainRule { get; set; }
30
31 public struct Cangjie
32 {
33 public string Code { get; set; }
34 public string SplitCode { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Cangjie. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\ImeWlConverterCore\Generaters\ZhengmaGenerater.cs (line 79)
76
77 #region Nested type: Zhengma
78
79 private struct Zhengma
80 {
81 /// <summary>
82 /// 构词码
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Zhengma. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 6 hits
📄 src\ImeWlConverterCore\IME\Rime.cs (line 83)
80
81 private string GetLineSplit(OperationSystem os)
82 {
83 switch (os)
84 {
85 case OperationSystem.Windows:
86 return "\r\n";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\ImeWlConverterCore\IME\RimeUserDb.cs (line 81)
78
79 private string GetLineSplit(OperationSystem os)
80 {
81 switch (os)
82 {
83 case OperationSystem.Windows:
84 return "\r\n";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS044 Attribute must specify [AttributeUsage] 2 hits
📄 src\ImeWlConverterCore\ComboBoxShowAttribute.cs (line 22)
19
20namespace Studyzy.IMEWLConverter;
21
22public class ComboBoxShowAttribute : Attribute
23{
24 public ComboBoxShowAttribute(string name, string shortCode, int index)
25 {
💬 ComboBoxShowAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\ImeWlConverterCore\ComboBoxShowAttribute.cs (line 22)
19
20namespace Studyzy.IMEWLConverter;
21
22public class ComboBoxShowAttribute : Attribute
23{
24 public ComboBoxShowAttribute(string name, string shortCode, int index)
25 {
💬 ComboBoxShowAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS049 Comparing strings without StringComparison 6 hits
📄 src\ImeWlConverterCore\ConsoleRun.cs (line 221)
218 _ => BuildType.None
219 };
220
221 pattern.ContainCode = format[6].ToString().ToLower() == "y";
222
223 if (format.Length > 8)
224 {
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\ImeWlConverterCore\ConsoleRun.cs (line 225)
222
223 if (format.Length > 8)
224 {
225 pattern.ContainRank = format[8].ToString().ToLower() == "y";
226 }
227 else
228 {
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS058 String concatenated in a loop 28 hits
📄 src\ImeWlConverterCore\Helpers\CollectionHelper.cs (line 79)
76 //循环当前数组
77 foreach (var item in astr)
78 if (count + 1 < list.Count)
79 temp += Descartes(list, count + 1, result, data + item);
80 else
81 result.Add(data + item);
82
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\ImeWlConverterCore\Generaters\Cangjie5Generater.cs (line 279)
276 if (arr[0].Length > 2) lastCode = arr[0][arr[0].Length - 1];
277 }
278
279 code += lastCode;
280 }
281
282 if (!result.Contains(code))
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 4 hits
📄 src\ImeWlConverterCore\MainBody.cs (line 41)
38 private int currentStatus;
39 private bool isImportProgress;
40 private string processMessage;
41 private Timer timer;
42
43 public MainBody()
44 {
💬 Disposable field timer in type MainBody is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\IME WL Converter Win\Forms\MainForm.cs (line 51)
48 private IWordLibraryImport import;
49
50 //private Encoding ld2WordEncoding=Encoding.UTF8;
51 private MainBody mainBody;
52 private IWordRankGenerater wordRankGenerater = new DefaultWordRankGenerater();
53 private bool exportDirectly => toolStripMenuItemExportDirectly.Checked;
54
💬 Disposable field mainBody in type MainForm is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

C-Sharp-Algorithms

108 total diagnostics across 6 rules

SS003 Integer divided by integer causing implicit rounding 66 hits
📄 DataStructures\Common\Helpers.cs (line 46)
43 int length = text.Length;
44 int charactersToPad = newWidth - length;
45 if (charactersToPad < 0) throw new ArgumentException("New width must be greater than string length.", "newWidth");
46 int padLeft = charactersToPad / 2 + charactersToPad % 2;
47 //add a space to the left if the string is an odd number
48 int padRight = charactersToPad / 2;
49
💬 The operands in the divisive expression charactersToPad / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 DataStructures\Common\Helpers.cs (line 48)
45 if (charactersToPad < 0) throw new ArgumentException("New width must be greater than string length.", "newWidth");
46 int padLeft = charactersToPad / 2 + charactersToPad % 2;
47 //add a space to the left if the string is an odd number
48 int padRight = charactersToPad / 2;
49
50 return new String(fillerCharacter, padLeft) + text + new String(fillerCharacter, padRight);
51 }
💬 The operands in the divisive expression charactersToPad / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS018 Switch does not handle all enum options 2 hits
📄 DataStructures\Heaps\MinPriorityQueue.cs (line 116)
113 {
114 object maxValue = default(TPriority);
115 TypeCode typeCode = Type.GetTypeCode(typeof(TPriority));
116 switch (typeCode)
117 {
118 case TypeCode.Byte:
119 maxValue = byte.MaxValue;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 DataStructures\Heaps\MinPriorityQueue.cs (line 116)
113 {
114 object maxValue = default(TPriority);
115 TypeCode typeCode = Type.GetTypeCode(typeof(TPriority));
116 switch (typeCode)
117 {
118 case TypeCode.Byte:
119 maxValue = byte.MaxValue;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 6 hits
📄 DataStructures\Heaps\MinPriorityQueue.cs (line 116)
113 {
114 object maxValue = default(TPriority);
115 TypeCode typeCode = Type.GetTypeCode(typeof(TPriority));
116 switch (typeCode)
117 {
118 case TypeCode.Byte:
119 maxValue = byte.MaxValue;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 DataStructures\Heaps\BinomialMinHeap.cs (line 142)
139 whichCase += (treeRoot2 == null ? 0 : 2);
140 whichCase += (carryNode == null ? 0 : 4);
141
142 switch (whichCase)
143 {
144 case 0: /* No trees */
145 case 1: /* Only this */
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS020 Test method without public modifier 14 hits
📄 UnitTest\AlgorithmsTests\BinaryTreeRecursiveWalkerTests.cs (line 30)
27 #region <<Test Tree Traversal methods>>
28
29 [Fact]
30 private static void TestPreOrderTraversal()
31 {
32 var preOrder = BinaryTreeRecursiveWalker.TraversalMode.PreOrder;
33
💬 Test method "TestPreOrderTraversal" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
📄 UnitTest\AlgorithmsTests\BinaryTreeRecursiveWalkerTests.cs (line 53)
50 }
51
52 [Fact]
53 private static void TestInOrderTraversal()
54 {
55 var inOrder = BinaryTreeRecursiveWalker.TraversalMode.InOrder;
56
💬 Test method "TestInOrderTraversal" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
SS023 Exception thrown from property getter 18 hits
📄 DataStructures\Lists\Stack.cs (line 71)
68 }
69 catch (Exception)
70 {
71 throw new Exception("Stack is empty.");
72 }
73 }
74 }
💬 An exception is thrown from the getter of property Top (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 DataStructures\Lists\ArrayList.cs (line 169)
166 {
167 if (Count == 0)
168 {
169 throw new IndexOutOfRangeException("List is empty.");
170 }
171
172 return _collection[0];
💬 An exception is thrown from the getter of property First (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS058 String concatenated in a loop 2 hits
📄 DataStructures\Graphs\CliqueGraph.cs (line 39)
36 string ret = "{";
37 foreach (var x in this)
38 {
39 ret += x.ToString() + " ";
40 }
41 ret += "}";
42 return ret;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 DataStructures\Graphs\CliqueGraph.cs (line 39)
36 string ret = "{";
37 foreach (var x in this)
38 {
39 ret += x.ToString() + " ";
40 }
41 ret += "}";
42 return ret;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

videoduplicatefinder

102 total diagnostics across 12 rules

SS001 Async method with void return type 26 hits
📄 VDF.Core\ScanEngine.cs (line 123)
120 public static bool FFprobeExists => !string.IsNullOrEmpty(FFProbeEngine.FFprobePath);
121 public static bool NativeFFmpegExists => FFTools.FFmpegNative.FFmpegHelper.DoFFmpegLibraryFilesExist;
122
123 public async void StartSearch() {
124 PrepareSearch();
125 SearchTimer.Start();
126 ElapsedTimer.Start();
💬 Method StartSearch is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 VDF.Core\ScanEngine.cs (line 148)
145 }
146 }
147
148 public async void StartCompare() {
149 PrepareCompare();
150 SearchTimer.Start();
151 ElapsedTimer.Start();
💬 Method StartCompare is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 10 hits
📄 VDF.Core\ScanEngine.cs (line 59)
56 readonly Stopwatch SearchTimer = new();
57 public Stopwatch ElapsedTimer = new();
58 int processedFiles;
59 DateTime startTime = DateTime.Now;
60 DateTime lastProgressUpdate = DateTime.MinValue;
61 static readonly TimeSpan progressUpdateIntervall = TimeSpan.FromMilliseconds(300);
62 const int maxExcludedLogsPerReason = 5;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 VDF.Core\Utils\Logger.cs (line 29)
26#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
27 static readonly object lockObject = new();
28 public void Info(string text) {
29 LogItemAdded?.Invoke($"{DateTime.Now:HH:mm:ss} => {text}");
30 lock (lockObject) {
31 File.AppendAllText(Path.Combine(CoreUtils.CurrentFolder, "log.txt"), $"{DateTime.Now:HH:mm:ss} => {text}{Environment.NewLine}");
32 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 2 hits
📄 VDF.Core\ScanEngine.cs (line 107)
104 lastProgressUpdate + progressUpdateIntervall < DateTime.UtcNow;
105 if (!pushUpdate) return;
106 lastProgressUpdate = DateTime.UtcNow;
107 var timeRemaining = TimeSpan.FromTicks(DateTime.UtcNow.Subtract(startTime).Ticks *
108 (scanProgressMaxValue - (processedFiles + 1)) / (processedFiles + 1));
109 Progress?.Invoke(this,
110 new ScanProgressChangedEventArgs {
💬 The operands in the divisive expression DateTime.UtcNow.Subtract(startTime).Ticks *
📄 VDF.Core\ScanEngine.cs (line 107)
104 lastProgressUpdate + progressUpdateIntervall < DateTime.UtcNow;
105 if (!pushUpdate) return;
106 lastProgressUpdate = DateTime.UtcNow;
107 var timeRemaining = TimeSpan.FromTicks(DateTime.UtcNow.Subtract(startTime).Ticks *
108 (scanProgressMaxValue - (processedFiles + 1)) / (processedFiles + 1));
109 Progress?.Invoke(this,
110 new ScanProgressChangedEventArgs {
💬 The operands in the divisive expression DateTime.UtcNow.Subtract(startTime).Ticks *
SS004 Elementary methods of type in collection not overridden 8 hits
📄 VDF.GUI\ViewModels\MainWindowVM.cs (line 1536)
1533 else
1534 ScanEngine.RemoveFromDatabase(fe);
1535
1536 actuallyDeleted.Add(dub);
1537 }
1538 catch (Exception ex) {
1539 Logger.Instance.Info($"Failed to delete '{dub.ItemInfo.Path}': {ex.Message}\n{ex.StackTrace}");
💬 Type DuplicateItemVM is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 VDF.GUI\ViewModels\MainWindowVM_Filter.cs (line 250)
247 if (!n.IsGroup)
248 return n.Item!.ItemInfo.GroupId;
249
250 if (_groupNodeToGuid.TryGetValue(n, out var gid))
251 return gid;
252
253 // Find first leaf in AllChildren to read its GroupId
💬 Type RowNode is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 6 hits
📄 VDF.Core\FileEntry.cs (line 120)
117 StringComparison.OrdinalIgnoreCase :
118 StringComparison.Ordinal);
119
120 public override int GetHashCode() => CoreUtils.IsWindows ?
121 StringComparer.OrdinalIgnoreCase.GetHashCode(Path) :
122 HashCode.Combine(Path);
123 }
💬 GetHashCode() refers to mutable field IsWindows (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 VDF.Core\FileEntry.cs (line 121)
118 StringComparison.Ordinal);
119
120 public override int GetHashCode() => CoreUtils.IsWindows ?
121 StringComparer.OrdinalIgnoreCase.GetHashCode(Path) :
122 HashCode.Combine(Path);
123 }
124}
💬 GetHashCode() refers to mutable property Path (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 10 hits
📄 VDF.Core\ScanProgressChangedEventArgs.cs (line 20)
17using System;
18
19namespace VDF.Core {
20 public struct ScanProgressChangedEventArgs {
21
22 public string CurrentFile;
23 public int CurrentPosition;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ScanProgressChangedEventArgs. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 VDF.Core\FFTools\FfmpegEngine.cs (line 278)
275 }
276 }
277
278 internal struct FfmpegSettings {
279 public byte GrayScale;
280 public byte Fullsize;
281 public string File;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FfmpegSettings. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 6 hits
📄 VDF.GUI\ViewModels\MainWindowVM_FfmpegDownloader.cs (line 141)
138
139 Architecture arch = RuntimeInformation.ProcessArchitecture;
140 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
141 switch (arch) {
142 case Architecture.X64:
143 plans.Add(new FfmpegDownloadPlan(
144 new Uri($"https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n{versionTag}-latest-win64-gpl-shared-{versionTag}.zip"),
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 VDF.GUI\ViewModels\MainWindowVM_FfmpegDownloader.cs (line 166)
163 }
164 }
165 else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
166 switch (arch) {
167 case Architecture.X64:
168 plans.Add(new FfmpegDownloadPlan(
169 new Uri($"https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n{versionTag}-latest-linux64-gpl-shared-{versionTag}.tar.xz"),
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 8 hits
📄 VDF.GUI\ViewModels\MainWindowVM_FfmpegDownloader.cs (line 141)
138
139 Architecture arch = RuntimeInformation.ProcessArchitecture;
140 if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
141 switch (arch) {
142 case Architecture.X64:
143 plans.Add(new FfmpegDownloadPlan(
144 new Uri($"https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n{versionTag}-latest-win64-gpl-shared-{versionTag}.zip"),
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 VDF.GUI\ViewModels\MainWindowVM_FfmpegDownloader.cs (line 166)
163 }
164 }
165 else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
166 switch (arch) {
167 case Architecture.X64:
168 plans.Add(new FfmpegDownloadPlan(
169 new Uri($"https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-n{versionTag}-latest-linux64-gpl-shared-{versionTag}.tar.xz"),
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 VDF.GUI\ViewModels\DuplicateItemVM.cs (line 70)
67 if (string.IsNullOrEmpty(ThumbnailKey)) return null;
68 if (ThumbCacheHelpers.Provider == null)
69#if DEBUG
70 throw new InvalidOperationException("No active thumbnail provider");
71#else
72 return null;
73#endif
💬 An exception is thrown from the getter of property Thumbnail (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 VDF.GUI\ViewModels\DuplicateItemVM.cs (line 88)
85 }
86 catch {
87#if DEBUG
88 throw;
89#endif
90 return null;
91 }
💬 An exception is thrown from the getter of property Thumbnail (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 10 hits
📄 VDF.GUI\ViewModels\CustomSelectionVM.cs (line 92)
89 if (string.IsNullOrEmpty(result)) return;
90
91 try {
92 File.WriteAllText(result, JsonSerializer.Serialize(Data));
93 }
94 catch (Exception ex) {
95 await MessageBoxService.Show($"Saving to file has failed: {ex.Message}");
💬 Async overload available for File.WriteAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 VDF.GUI\ViewModels\CustomSelectionVM.cs (line 108)
105 if (string.IsNullOrEmpty(result)) return;
106
107 try {
108 Data = JsonSerializer.Deserialize<CustomSelectionData>(File.ReadAllText(result))!;
109
110 }
111 catch (Exception ex) {
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS059 IAsyncDisposable not disposed asynchronously 10 hits
📄 VDF.GUI\ViewModels\MainWindowVM.cs (line 934)
931
932 if (File.Exists(packPath) && Utils.ThumbCacheHelpers.Provider != null) {
933 var packEntry = zip.CreateEntry("thumbs.pack", CompressionLevel.NoCompression);
934 using var es = packEntry.Open();
935 Utils.ThumbCacheHelpers.Provider.CopyTo(es);
936 }
937
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 VDF.GUI\ViewModels\MainWindowVM.cs (line 940)
937
938 if (File.Exists(idxPath)) {
939 var idxEntry = zip.CreateEntry("thumbs.idx", CompressionLevel.NoCompression);
940 using var es = idxEntry.Open();
941 using var fs2 = File.OpenRead(idxPath);
942 fs2.CopyTo(es);
943 }
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 2 hits
📄 VDF.GUI\Utils\ThumbnailStore.cs (line 192)
189 }
190
191 internal sealed class LengthCountingStream : Stream {
192 readonly Stream _inner;
193 public long BytesWritten { get; private set; }
194 public LengthCountingStream(Stream inner) => _inner = inner;
195 public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true;
💬 Disposable field _inner in type LengthCountingStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 VDF.GUI\Utils\ThumbnailStore.cs (line 192)
189 }
190
191 internal sealed class LengthCountingStream : Stream {
192 readonly Stream _inner;
193 public long BytesWritten { get; private set; }
194 public LengthCountingStream(Stream inner) => _inner = inner;
195 public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true;
💬 Disposable field _inner in type LengthCountingStream is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

CAP

94 total diagnostics across 6 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 52 hits
No source samples extracted
SS033 Async overload is available 24 hits
No source samples extracted
SS044 Attribute must specify [AttributeUsage] 2 hits
No source samples extracted
SS051 Locking on mutable reference 2 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 8 hits
No source samples extracted
SS066 Disposable field is not disposed 6 hits
No source samples extracted

ink

94 total diagnostics across 11 rules

SS003 Integer divided by integer causing implicit rounding 8 hits
📄 ink-engine-runtime\NativeFunctionCall.cs (line 334)
331 AddIntBinaryOp(Add, (x, y) => x + y);
332 AddIntBinaryOp(Subtract, (x, y) => x - y);
333 AddIntBinaryOp(Multiply, (x, y) => x * y);
334 AddIntBinaryOp(Divide, (x, y) => x / y);
335 AddIntBinaryOp(Mod, (x, y) => x % y);
336 AddIntUnaryOp (Negate, x => -x);
337
💬 The operands in the divisive expression x / y are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 ink-engine-runtime\Story.cs (line 2791)
2788
2789 var seqCountVal = state.PopEvaluationStack () as IntValue;
2790 var seqCount = seqCountVal.value;
2791 var loopIndex = seqCount / numElements;
2792 var iterationIndex = seqCount % numElements;
2793
2794 // Generate the same shuffle based on:
💬 The operands in the divisive expression seqCount / numElements are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 ink-engine-runtime\StoryState.cs (line 1145)
1142 foreach (var n in rawList.originNames) {
1143 ListDefinition def = null;
1144 story.listDefinitions.TryListGetDefinition (n, out def);
1145 if( !rawList.origins.Contains(def) )
1146 rawList.origins.Add (def);
1147 }
1148 }
💬 Type ListDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 ink-engine-runtime\StoryState.cs (line 1145)
1142 foreach (var n in rawList.originNames) {
1143 ListDefinition def = null;
1144 story.listDefinitions.TryListGetDefinition (n, out def);
1145 if( !rawList.origins.Contains(def) )
1146 rawList.origins.Add (def);
1147 }
1148 }
💬 Type ListDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 20 hits
📄 ink-engine-runtime\Divert.cs (line 100)
97 {
98 if (hasVariableTarget) {
99 const int variableTargetSalt = 12345;
100 return variableDivertName.GetHashCode() + variableTargetSalt;
101 } else {
102 const int pathTargetSalt = 54321;
103 return targetPath.GetHashCode() + pathTargetSalt;
💬 GetHashCode() refers to mutable property variableDivertName (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 ink-engine-runtime\Divert.cs (line 103)
100 return variableDivertName.GetHashCode() + variableTargetSalt;
101 } else {
102 const int pathTargetSalt = 54321;
103 return targetPath.GetHashCode() + pathTargetSalt;
104 }
105 }
106
💬 GetHashCode() refers to mutable property targetPath (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS013 Rethrow exception without losing stacktrace 2 hits
📄 inklecate\CommandLineTool.cs (line 205)
202 OnError (e.Message, ErrorType.Error);
203 PrintAllMessages ();
204 } else {
205 throw e;
206 }
207 } catch (System.Exception e) {
208 string storyPath = "<END>";
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
📄 inklecate\CommandLineTool.cs (line 205)
202 OnError (e.Message, ErrorType.Error);
203 PrintAllMessages ();
204 } else {
205 throw e;
206 }
207 } catch (System.Exception e) {
208 string storyPath = "<END>";
💬 Rethrown exception loses the stacktrace. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 26 hits
📄 ink-engine-runtime\SearchResult.cs (line 10)
7 // try to recover by finding an approximate result by working up the story hierarchy
8 // in the path to find the closest valid container. Instead of crashing horribly,
9 // we might see some slight oddness in the content, but hopefully it recovers!
10 public struct SearchResult
11 {
12 public Runtime.Object obj;
13 public bool approximate;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SearchResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 ink-engine-runtime\Pointer.cs (line 13)
10 /// possible to increment the pointer (move the story forwards) in a way that's as
11 /// native to the internal engine as possible.
12 /// </summary>
13 public struct Pointer
14 {
15 public Container container;
16 public int index;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Pointer. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 12 hits
📄 ink-engine-runtime\SimpleJson.cs (line 551)
548 if (c < ' ')
549 {
550 // Don't write any control characters except \n and \t
551 switch (c)
552 {
553 case '\n':
554 _writer.Write("\\n");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 ink-engine-runtime\SimpleJson.cs (line 551)
548 if (c < ' ')
549 {
550 // Don't write any control characters except \n and \t
551 switch (c)
552 {
553 case '\n':
554 _writer.Write("\\n");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 2 hits
📄 tests\Tests.cs (line 624)
621 Assert.AreEqual("gather\ntest\nchoice content\ngather\nsecond time round\n", story.ContinueMaximally());
622 }
623
624 public void TestElseBranches()
625 {
626 var storyStr =
627 @"
💬 Method TestElseBranches might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 tests\Tests.cs (line 624)
621 Assert.AreEqual("gather\ntest\nchoice content\ngather\nsecond time round\n", story.ContinueMaximally());
622 }
623
624 public void TestElseBranches()
625 {
626 var storyStr =
627 @"
💬 Method TestElseBranches might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
SS023 Exception thrown from property getter 10 hits
📄 ink-engine-runtime\Value.cs (line 264)
261 {
262 public Path targetPath { get { return this.value; } set { this.value = value; } }
263 public override ValueType valueType { get { return ValueType.DivertTarget; } }
264 public override bool isTruthy { get { throw new System.Exception("Shouldn't be checking the truthiness of a divert target"); } }
265
266 public DivertTargetValue(Path targetPath) : base(targetPath)
267 {
💬 An exception is thrown from the getter of property isTruthy (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 ink-engine-runtime\Value.cs (line 293)
290 {
291 public string variableName { get { return this.value; } set { this.value = value; } }
292 public override ValueType valueType { get { return ValueType.VariablePointer; } }
293 public override bool isTruthy { get { throw new System.Exception("Shouldn't be checking the truthiness of a variable pointer"); } }
294
295 // Where the variable is located
296 // -1 = default, unknown, yet to be determined
💬 An exception is thrown from the getter of property isTruthy (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS024 Exception thrown from static constructor 4 hits
📄 ink-engine-runtime\JsonSerialisation.cs (line 743)
740
741 for (int i = 0; i < (int)ControlCommand.CommandType.TOTAL_VALUES; ++i) {
742 if (_controlCommandNames [i] == null)
743 throw new System.Exception ("Control command not accounted for in serialisation");
744 }
745 }
746
💬 An exception is thrown from Json its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
📄 ink-engine-runtime\JsonSerialisation.cs (line 743)
740
741 for (int i = 0; i < (int)ControlCommand.CommandType.TOTAL_VALUES; ++i) {
742 if (_controlCommandNames [i] == null)
743 throw new System.Exception ("Control command not accounted for in serialisation");
744 }
745 }
746
💬 An exception is thrown from Json its static constructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md)
SS057 Collection manipulated during traversal 4 hits
📄 ink-engine-runtime\StoryState.cs (line 568)
565 // and we can simply ref-copy the choices with their existing threads.
566 if( forBackgroundSave ) {
567 foreach(var choice in _currentFlow.currentChoices)
568 copy._currentFlow.currentChoices.Add(choice.Clone());
569 } else {
570 copy._currentFlow.currentChoices.AddRange(_currentFlow.currentChoices);
571 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 ink-engine-runtime\StoryState.cs (line 568)
565 // and we can simply ref-copy the choices with their existing threads.
566 if( forBackgroundSave ) {
567 foreach(var choice in _currentFlow.currentChoices)
568 copy._currentFlow.currentChoices.Add(choice.Clone());
569 } else {
570 copy._currentFlow.currentChoices.AddRange(_currentFlow.currentChoices);
571 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS058 String concatenated in a loop 2 hits
📄 tests\Tests.cs (line 850)
847 string result = "";
848 for (int i = 0; i < numberOfTimes; i++)
849 {
850 result += str;
851 }
852 return result;
853 });
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 tests\Tests.cs (line 850)
847 string result = "";
848 for (int i = 0; i < numberOfTimes; i++)
849 {
850 result += str;
851 }
852 return result;
853 });
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

AutoMapper

90 total diagnostics across 4 rules

SS004 Elementary methods of type in collection not overridden 30 hits
No source samples extracted
SS015 String placeholders in wrong order 10 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 40 hits
No source samples extracted
SS058 String concatenated in a loop 10 hits
No source samples extracted

hashids.net

90 total diagnostics across 3 rules

SS003 Integer divided by integer causing implicit rounding 24 hits
📄 src\Hashids.net\Hashids.cs (line 343)
340 }
341 }
342
343 var halfLength = _alphabet.Length / 2;
344
345 var stringBuilder = StringBuilderPool.Get();
346#if NETSTANDARD2_0
💬 The operands in the divisive expression _alphabet.Length / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Hashids.net\Hashids.cs (line 368)
365 var excess = stringBuilder.Length - _minHashLength;
366 if (excess > 0)
367 {
368 stringBuilder.Remove(0, excess / 2);
369 stringBuilder.Remove(_minHashLength, stringBuilder.Length - _minHashLength);
370 }
371 }
💬 The operands in the divisive expression excess / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS020 Test method without public modifier 48 hits
📄 test\Hashids.net.test\IssueSpecificTests.cs (line 11)
8 public class IssueSpecificTests
9 {
10 [Fact]
11 void Issue_8_should_not_throw_out_of_range_exception()
12 {
13 var hashids = new Hashids("janottaa", 6);
14 var numbers = hashids.Decode("NgAzADEANAA=");
💬 Test method "Issue_8_should_not_throw_out_of_range_exception" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
📄 test\Hashids.net.test\IssueSpecificTests.cs (line 21)
18 // seems to happen when you are encoding A LOT of longs at the same time.
19 // see if it is possible to make this a faster test (or remove it since it is unlikely that it will reapper).
20 [Fact]
21 void Issue_12_should_not_throw_out_of_range_exception()
22 {
23 var hash = new Hashids("zXZVFf2N38uV");
24 var longs = new List<long>();
💬 Test method "Issue_12_should_not_throw_out_of_range_exception" is not public. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md)
SS046 Unbounded stackalloc 18 hits
📄 src\Hashids.net\Hashids.cs (line 310)
307 var startIndex = 1 + _salt.Length;
308 var length = _alphabet.Length - startIndex;
309
310 Span<char> hashBuffer = stackalloc char[_minBufferSize];
311
312 if (length > 0)
313 alphabet.Slice(0, length).CopyTo(shuffleBuffer.Slice(startIndex));
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
📄 src\Hashids.net\Hashids.cs (line 415)
412 var startIndex = 1 + _salt.Length;
413 var length = _alphabet.Length - startIndex;
414
415 Span<char> hashBuffer = stackalloc char[_minBufferSize];
416
417 for (var i = 0; i < numbers.Length; i++)
418 {
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)

Hearthstone-Deck-Tracker

88 total diagnostics across 6 rules

SS001 Async method with void return type 42 hits
📄 HearthWatcher\BattlegroundsLeaderboardWatcher.cs (line 37)
34
35 public void Stop() => _watch = false;
36
37 private async void Update()
38 {
39 _running = true;
40 while(_watch)
💬 Method Update is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 HearthWatcher\BaconWatcher.cs (line 36)
33
34 public void Stop() => _watch = false;
35
36 private async void Update()
37 {
38 _running = true;
39 while(_watch)
💬 Method Update is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 12 hits
📄 HearthWatcher\LogReader\LogLine.cs (line 38)
35 }
36
37 public string Namespace { get; }
38 public DateTime Time { get; } = DateTime.Now;
39 public string Line { get; }
40 public string LineContent { get; }
41}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 HearthWatcher\LogReader\LogLine.cs (line 30)
27 if(DateTime.TryParse(ts, out time))
28 {
29 Time = DateTime.Today.Add(time.TimeOfDay);
30 if(Time > DateTime.Now)
31 Time = Time.AddDays(-1);
32 }
33 LineContent = match.Groups["line"].Value;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 4 hits
📄 HDTUpdate\Program.cs (line 116)
113 {
114 Console.CursorLeft = 0;
115 Console.CursorTop = 1;
116 Console.WriteLine("Downloading latest version... {0}/{1}KB ({2}%)", e.BytesReceived / (1024), e.TotalBytesToReceive / (1024), e.ProgressPercentage);
117 }
118 };
119 await wc.DownloadFileTaskAsync(url, filePath);
💬 The operands in the divisive expression e.BytesReceived / (1024) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 HDTUpdate\Program.cs (line 116)
113 {
114 Console.CursorLeft = 0;
115 Console.CursorTop = 1;
116 Console.WriteLine("Downloading latest version... {0}/{1}KB ({2}%)", e.BytesReceived / (1024), e.TotalBytesToReceive / (1024), e.ProgressPercentage);
117 }
118 };
119 await wc.DownloadFileTaskAsync(url, filePath);
💬 The operands in the divisive expression e.TotalBytesToReceive / (1024) are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS005 Equals() and GetHashCode() not implemented together 4 hits
📄 HearthWatcher\EventArgs\BattlegroundsLeaderboardArgs.cs (line 3)
1namespace HearthWatcher.EventArgs
2{
3 public class BattlegroundsLeaderboardArgs : System.EventArgs
4 {
5 public int? HoveredEntityId { get; }
6
💬 Equals() and GetHashcode() must be implemented together on BattlegroundsLeaderboardArgs (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
📄 HearthWatcher\EventArgs\BattlegroundsTeammateBoardStateArgs.cs (line 7)
4
5namespace HearthWatcher.EventArgs
6{
7 public class BattlegroundsTeammateBoardStateArgs : System.EventArgs
8 {
9 public bool IsViewingTeammate { get; }
10
💬 Equals() and GetHashcode() must be implemented together on BattlegroundsTeammateBoardStateArgs (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md)
SS011 OnPropertyChanged without nameof operator 24 hits
📄 HDTUninstaller\MainWindow.xaml.cs (line 95)
92 var regKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
93 if(regKey != null)
94 regKey.DeleteValue("Hearthstone Deck Tracker", false);
95 OnPropertyChanged("TextAutostart");
96 OnPropertyChanged("BackgroundAutostart");
97 }
98 catch(Exception ex)
💬 OnPropertyChanged(TextAutostart) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
📄 HDTUninstaller\MainWindow.xaml.cs (line 96)
93 if(regKey != null)
94 regKey.DeleteValue("Hearthstone Deck Tracker", false);
95 OnPropertyChanged("TextAutostart");
96 OnPropertyChanged("BackgroundAutostart");
97 }
98 catch(Exception ex)
99 {
💬 OnPropertyChanged(BackgroundAutostart) can use the nameof() operator. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md)
SS019 Switch is missing default label 2 hits
📄 HDTUpdate\Program.cs (line 50)
47 catch(Exception e)
48 {
49 Console.WriteLine(e);
50 switch(_state)
51 {
52 case UpdatingState.Preparation:
53 Console.WriteLine("Please delete the 'temp' directory and try to update again. Press any key to exit.");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 HDTUpdate\Program.cs (line 50)
47 catch(Exception e)
48 {
49 Console.WriteLine(e);
50 switch(_state)
51 {
52 case UpdatingState.Preparation:
53 Console.WriteLine("Please delete the 'temp' directory and try to update again. Press any key to exit.");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)

XboxDownload

86 total diagnostics across 11 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 12 hits
📄 XboxDownload\Models\Services\ServiceModels.cs (line 34)
31 RequestMethod = method;
32 Content = content;
33 ClientIp = ip;
34 Timestamp = DateTime.Now;
35 }
36
37 [ObservableProperty]
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 XboxDownload\ViewModels\StoreViewModel.cs (line 811)
808
809 private async Task GetGamePackageAsync(PlatformDownloadItem platformDownload, string contentId, CancellationToken token = default)
810 {
811 if (!_platformPackageFetchTimes.TryGetValue(platformDownload.Key, out var value) || DateTime.Compare(value, DateTime.Now) < 0)
812 {
813 _platformPackageFetchTimes[platformDownload.Key] = DateTime.Now.AddMinutes(3);
814
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 XboxDownload\Services\SpeedTestService.cs (line 94)
91 {
92 // Even if the request fails, record the amount of data that was downloaded.
93 response.Dispose();
94 ipResults[ipItem] = totalBytes;
95 }
96 }
97
💬 Type IpItem is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 XboxDownload\Services\SpeedTestService.cs (line 94)
91 {
92 // Even if the request fails, record the amount of data that was downloaded.
93 response.Dispose();
94 ipResults[ipItem] = totalBytes;
95 }
96 }
97
💬 Type IpItem is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS018 Switch does not handle all enum options 4 hits
📄 XboxDownload\Services\DnsConnectionListener.cs (line 654)
651 // 2. Normalize IPv4-mapped IPv6 (e.g., ::ffff:192.168.1.1)
652 var effectiveIp = ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip;
653
654 switch (effectiveIp.AddressFamily)
655 {
656 case AddressFamily.InterNetwork: // IPv4
657 Span<byte> v4 = stackalloc byte[4];
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 XboxDownload\Services\DnsConnectionListener.cs (line 697)
694 var queryName = (dns.Queries[0].QueryName ?? string.Empty).ToLowerInvariant();
695 if (string.IsNullOrWhiteSpace(queryName)) return;
696
697 switch (dns.Queries[0].QueryType)
698 {
699 case QueryType.A:
700 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 38 hits
📄 XboxDownload\ViewModels\Dialog\DohServerDialogViewModel.cs (line 55)
52 [RelayCommand]
53 private void UpdateSelection(string? parameter)
54 {
55 switch (parameter)
56 {
57 case "SelectAll":
58 foreach (var option in SpeedTestMappings)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 XboxDownload\Services\DnsConnectionListener.cs (line 654)
651 // 2. Normalize IPv4-mapped IPv6 (e.g., ::ffff:192.168.1.1)
652 var effectiveIp = ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip;
653
654 switch (effectiveIp.AddressFamily)
655 {
656 case AddressFamily.InterNetwork: // IPv4
657 Span<byte> v4 = stackalloc byte[4];
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 2 hits
📄 XboxDownload\Services\XboxGameManager.cs (line 49)
46 try
47 {
48 // ReSharper disable once MethodHasAsyncOverload
49 _saveCancellationTokenSource?.Cancel();
50
51 _saveCancellationTokenSource = new CancellationTokenSource();
52 var token = _saveCancellationTokenSource.Token;
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 XboxDownload\Services\XboxGameManager.cs (line 49)
46 try
47 {
48 // ReSharper disable once MethodHasAsyncOverload
49 _saveCancellationTokenSource?.Cancel();
50
51 _saveCancellationTokenSource = new CancellationTokenSource();
52 var token = _saveCancellationTokenSource.Token;
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 2 hits
📄 XboxDownload\Services\SpeedTestService.cs (line 111)
108
109 if (result.Task.IsCompletedSuccessfully)
110 {
111 return result.Task.Result;
112 }
113
114 var best = ipResults
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 XboxDownload\Services\SpeedTestService.cs (line 111)
108
109 if (result.Task.IsCompletedSuccessfully)
110 {
111 return result.Task.Result;
112 }
113
114 var best = ipResults
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS037 HttpClient instantiated directly 2 hits
📄 XboxDownload\Helpers\Network\HttpClientHelper.cs (line 225)
222
223 try
224 {
225 using var client = new HttpClient(handler, disposeHandler: true);
226
227 using var request = new HttpRequestMessage(HttpMethod.Get, uri);
228 request.Headers.Range = new RangeHeaderValue(rangeFrom, rangeTo);
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 XboxDownload\Helpers\Network\HttpClientHelper.cs (line 225)
222
223 try
224 {
225 using var client = new HttpClient(handler, disposeHandler: true);
226
227 using var request = new HttpRequestMessage(HttpMethod.Get, uri);
228 request.Headers.Range = new RangeHeaderValue(rangeFrom, rangeTo);
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
SS041 Unnecessary enumerable materialization 4 hits
📄 XboxDownload\ViewModels\Dialog\ResolveDomainDialogViewModel.cs (line 81)
78 return;
79 }
80
81 foreach (var entry in _hostViewModel.HostMappings.ToList().Where(entry => entry.HostName.Equals(HostnameToResolve)))
82 {
83 _hostViewModel.HostMappings.Remove(entry);
84 }
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 XboxDownload\ViewModels\Dialog\LocalProxyDialogViewModel.cs (line 401)
398 const string url = "https://github.com/SpaceTimee/Cealing-Host/raw/main/Cealing-Host.json";
399 using var cts = new CancellationTokenSource();
400
401 var tasks = UpdateService.Proxies1.Concat([""]).ToArray().Select(async proxy => await HttpClientHelper.GetStringContentAsync(proxy + url, token: cts.Token, timeout: 6000)).ToList();
402 while (tasks.Count > 0)
403 {
404 var completedTask = await Task.WhenAny(tasks);
💬 ToArray is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS058 String concatenated in a loop 8 hits
📄 XboxDownload\ViewModels\StoreViewModel.cs (line 491)
488 {
489 platformDownload.Outdated = true;
490 platformDownload.FileSize = xboxGame.FileSize;
491 platformDownload.Display += $" ({ResourceHelper.GetString("Store.UpdateAvailable")})";
492 tasks.Add(Task.Run(async () =>
493 {
494 await GetGamePackageAsync(platformDownload, contentId, token);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 XboxDownload\ViewModels\StoreViewModel.cs (line 529)
526 {
527 platformDownload.Outdated = true;
528 platformDownload.FileSize = xboxGame.FileSize;
529 platformDownload.Display += $" ({ResourceHelper.GetString("Store.UpdateAvailable")})";
530 tasks.Add(Task.Run(async () =>
531 {
532 await GetGamePackageAsync(platformDownload, contentId, token);
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 XboxDownload\Models\Store\StoreSearchResult.cs (line 29)
26 if (response is { IsSuccessStatusCode: true })
27 {
28 var buffer = await response.Content.ReadAsByteArrayAsync();
29 using var stream = new MemoryStream(buffer);
30 IconBitmap = new Bitmap(stream);
31 }
32 }
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 XboxDownload\Helpers\Network\HttpClientHelper.cs (line 89)
86 var url = proxy + (string.IsNullOrEmpty(proxy) ? path : path.Replace("https://", ""));
87 using var response = await SendRequestAsync(url, headers: headers, timeout: timeout, name: HttpClientNames.SpeedTest, token: cts.Token);
88 if (response is not { IsSuccessStatusCode: true }) return null;
89 using var ms = new MemoryStream();
90 try
91 {
92 await using var stream = await response.Content.ReadAsStreamAsync(cts.Token);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 4 hits
📄 XboxDownload\Helpers\Utilities\UsbWatcher.cs (line 12)
9 public event Action<string>? UsbInserted;
10 public event Action<string>? UsbRemoved;
11
12 private ManagementEventWatcher? _insertWatcher;
13 private ManagementEventWatcher? _removeWatcher;
14
15 [SupportedOSPlatform("windows")]
💬 Disposable field _insertWatcher in type UsbWatcher is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 XboxDownload\Helpers\Utilities\UsbWatcher.cs (line 13)
10 public event Action<string>? UsbRemoved;
11
12 private ManagementEventWatcher? _insertWatcher;
13 private ManagementEventWatcher? _removeWatcher;
14
15 [SupportedOSPlatform("windows")]
16 public void Start()
💬 Disposable field _removeWatcher in type UsbWatcher is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

FluentAssertions

86 total diagnostics across 9 rules

SS003 Integer divided by integer causing implicit rounding 8 hits
No source samples extracted
SS004 Elementary methods of type in collection not overridden 18 hits
No source samples extracted
SS005 Equals() and GetHashCode() not implemented together 38 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 6 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
No source samples extracted
SS023 Exception thrown from property getter 4 hits
No source samples extracted
SS034 Accessing Task.Result without await 4 hits
No source samples extracted
SS058 String concatenated in a loop 2 hits
No source samples extracted
SS066 Disposable field is not disposed 4 hits
No source samples extracted

BepInEx

84 total diagnostics across 9 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 18 hits
📄 Runtimes\Unity\BepInEx.Unity.Mono.Preloader\DoorstopEntrypoint.cs (line 17)
14 public static void Start()
15 {
16 // We set it to the current directory first as a fallback, but try to use the same location as the .exe file.
17 var silentExceptionLog = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log";
18
19 try
20 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Runtimes\Unity\BepInEx.Unity.Mono.Preloader\UnityPreloader.cs (line 128)
125 catch { }
126
127 File.WriteAllText(
128 Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
129 log + ex);
130 }
131 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 Runtimes\Unity\BepInEx.Unity.IL2CPP\Il2CppInteropManager.AsmToCecilConverter.cs (line 50)
47
48 private AssemblyDefinition Convert(AsmResolver.DotNet.AssemblyDefinition asmResolverAssembly, ReaderParameters readerParameters)
49 {
50 if (asmToCecil.TryGetValue(asmResolverAssembly, out var cecilAssembly))
51 {
52 return cecilAssembly;
53 }
💬 Type AssemblyDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Runtimes\Unity\BepInEx.Unity.IL2CPP\Il2CppInteropManager.AsmToCecilConverter.cs (line 59)
56 stream.Position = 0;
57 cecilAssembly = AssemblyDefinition.ReadAssembly(stream, readerParameters);
58 cecilDictionary.Add(cecilAssembly.Name.Name, cecilAssembly);
59 asmToCecil.Add(asmResolverAssembly, cecilAssembly);
60 return cecilAssembly;
61 }
62 }
💬 Type AssemblyDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 8 hits
📄 Runtimes\Unity\BepInEx.Unity.Mono\Configuration\KeyboardShortcut.cs (line 176)
173 {
174 if (MainKey == KeyCode.None) return 0;
175
176 return _allKeys.Aggregate(_allKeys.Length, (current, item) => unchecked(current * 31 + (int) item));
177 }
178}
💬 GetHashCode() refers to mutable field _allKeys (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 Runtimes\Unity\BepInEx.Unity.Mono\Configuration\KeyboardShortcut.cs (line 176)
173 {
174 if (MainKey == KeyCode.None) return 0;
175
176 return _allKeys.Aggregate(_allKeys.Length, (current, item) => unchecked(current * 31 + (int) item));
177 }
178}
💬 GetHashCode() refers to mutable field _allKeys (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 24 hits
📄 BepInEx.Core\Console\Windows\Kon.cs (line 28)
25
26 #region Types
27
28 private struct CONSOLE_SCREEN_BUFFER_INFO
29 {
30 internal COORD dwSize;
31 internal COORD dwCursorPosition;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CONSOLE_SCREEN_BUFFER_INFO. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 BepInEx.Core\Console\Windows\Kon.cs (line 37)
34 internal COORD dwMaximumWindowSize;
35 }
36
37 private struct COORD
38 {
39 internal short X;
40 internal short Y;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct COORD. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 4 hits
📄 Runtimes\Unity\BepInEx.Unity.Mono\UnityInput.cs (line 173)
170
171 private static ButtonControl GetControl(KeyCode key, bool silent = false)
172 {
173 switch (key)
174 {
175 case KeyCode.None:
176 break;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Runtimes\Unity\BepInEx.Unity.Mono\UnityInput.cs (line 173)
170
171 private static ButtonControl GetControl(KeyCode key, bool silent = false)
172 {
173 switch (key)
174 {
175 case KeyCode.None:
176 break;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 6 hits
📄 Runtimes\Unity\BepInEx.Unity.Mono\UnityInput.cs (line 173)
170
171 private static ButtonControl GetControl(KeyCode key, bool silent = false)
172 {
173 switch (key)
174 {
175 case KeyCode.None:
176 break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Runtimes\Unity\BepInEx.Unity.IL2CPP\Utils\Collections\Il2CppManagedEnumerator.cs (line 39)
36 ClassInjector.DerivedConstructorBody(this);
37 }
38
39 public Object Current => enumerator.Current switch
40 {
41 Il2CppIEnumerator i => i.Cast<Object>(),
42 IEnumerator e => new Il2CppManagedEnumerator(e),
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS023 Exception thrown from property getter 4 hits
📄 BepInEx.Core\Console\Unix\ConsoleWriter.cs (line 44)
41
42 cStreamWriterConstructor = ctorParams.Select(GetCtor).FirstOrDefault(f => f != null);
43 if (cStreamWriterConstructor == null)
44 throw new AmbiguousMatchException("Failed to find suitable constructor for CStreamWriter");
45 return cStreamWriterConstructor;
46 }
47 }
💬 An exception is thrown from the getter of property CStreamWriterConstructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 BepInEx.Core\Console\Unix\ConsoleWriter.cs (line 44)
41
42 cStreamWriterConstructor = ctorParams.Select(GetCtor).FirstOrDefault(f => f != null);
43 if (cStreamWriterConstructor == null)
44 throw new AmbiguousMatchException("Failed to find suitable constructor for CStreamWriter");
45 return cStreamWriterConstructor;
46 }
47 }
💬 An exception is thrown from the getter of property CStreamWriterConstructor (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS051 Locking on mutable reference 4 hits
📄 Runtimes\Unity\BepInEx.Unity.Mono.Preloader\RuntimeFixes\TraceFix.cs (line 60)
57
58 var type = (TraceEventType) Enum.Parse(typeof(TraceEventType), kind);
59
60 lock (ListenersSyncRoot)
61 {
62 foreach (var obj in Listeners)
63 {
💬 A lock was obtained on ListenersSyncRoot but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Runtimes\Unity\BepInEx.Unity.Mono.Preloader\RuntimeFixes\TraceFix.cs (line 60)
57
58 var type = (TraceEventType) Enum.Parse(typeof(TraceEventType), kind);
59
60 lock (ListenersSyncRoot)
61 {
62 foreach (var obj in Listeners)
63 {
💬 A lock was obtained on ListenersSyncRoot but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS066 Disposable field is not disposed 12 hits
📄 BepInEx.Core\Logging\TraceLogSource.cs (line 29)
26 /// <summary>
27 /// Internal log source.
28 /// </summary>
29 protected ManualLogSource LogSource { get; }
30
31 /// <summary>
32 /// Creates a new trace log source.
💬 Disposable field LogSource in type TraceLogSource is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 BepInEx.Core\Logging\TraceLogSource.cs (line 29)
26 /// <summary>
27 /// Internal log source.
28 /// </summary>
29 protected ManualLogSource LogSource { get; }
30
31 /// <summary>
32 /// Creates a new trace log source.
💬 Disposable field LogSource in type TraceLogSource is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

optick

84 total diagnostics across 7 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 16 hits
📄 gui\InteractiveDataDisplay.WPF\Navigation\MouseNavigation.cs (line 414)
411 selectStart = cursorPosition;
412 this.CaptureMouse();
413 }
414 lastClick = DateTime.Now;
415 }
416 else
417 {
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 gui\InteractiveDataDisplay.WPF\Navigation\MouseNavigation.cs (line 418)
415 }
416 else
417 {
418 DateTime d = DateTime.Now;
419 if ((d - lastClick).TotalMilliseconds < 200)
420 {
421 masterPlot.IsAutoFitEnabled = true;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 4 hits
📄 gui\InteractiveDataDisplay.WPF\Plots\Base\BackgroundBitmapRenderer.cs (line 162)
159
160 WriteableBitmap wr = new WriteableBitmap((int)r.Output.Width, (int)r.Output.Height, 96, 96, PixelFormats.Bgra32, null);
161 // Calculate the number of bytes per pixel.
162 int bytesPerPixel = (wr.Format.BitsPerPixel + 7) / 8;
163 // Stride is bytes per pixel times the number of pixels.
164 // Stride is the byte width of a single rectangle row.
165 int stride = wr.PixelWidth * bytesPerPixel;
💬 The operands in the divisive expression (wr.Format.BitsPerPixel + 7) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 gui\InteractiveDataDisplay.WPF\Plots\Base\BackgroundBitmapRenderer.cs (line 162)
159
160 WriteableBitmap wr = new WriteableBitmap((int)r.Output.Width, (int)r.Output.Height, 96, 96, PixelFormats.Bgra32, null);
161 // Calculate the number of bytes per pixel.
162 int bytesPerPixel = (wr.Format.BitsPerPixel + 7) / 8;
163 // Stride is bytes per pixel times the number of pixels.
164 // Stride is the byte width of a single rectangle row.
165 int stride = wr.PixelWidth * bytesPerPixel;
💬 The operands in the divisive expression (wr.Format.BitsPerPixel + 7) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 24 hits
📄 gui\InteractiveDataDisplay.WPF\Common\Range.cs (line 147)
144 /// <returns>The hash code for current instance</returns>
145 public override int GetHashCode()
146 {
147 return minimum.GetHashCode() ^ maximum.GetHashCode();
148 }
149
150 /// <summary>
💬 GetHashCode() refers to mutable field minimum (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 gui\InteractiveDataDisplay.WPF\Common\Range.cs (line 147)
144 /// <returns>The hash code for current instance</returns>
145 public override int GetHashCode()
146 {
147 return minimum.GetHashCode() ^ maximum.GetHashCode();
148 }
149
150 /// <summary>
💬 GetHashCode() refers to mutable field maximum (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 8 hits
📄 gui\InteractiveDataDisplay.WPF\Common\DataRect.cs (line 15)
12 /// points to bottom (that's why <see cref="System.Windows.Rect"/>'s Bottom property is greater than Top).
13 /// This type describes rectange in usual coordinates, and y axis point to top.
14 /// </summary>
15 public struct DataRect
16 {
17 private Range x;
18 private Range y;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DataRect. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 gui\InteractiveDataDisplay.WPF\PlotCompositionChange.cs (line 7)
4namespace InteractiveDataDisplay.WPF
5{
6 /// <summary>Identifies event when collection of related plots in composition change</summary>
7 public struct PlotCompositionChange
8 {
9 private PlotBase master;
10
💬 Implement Equals(), GetHashCode() and ToString() methods on struct PlotCompositionChange. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 8 hits
📄 gui\InteractiveDataDisplay.WPF\Axes\Axis.cs (line 442)
439 double labelArrangeOriginY = 0;
440
441
442 switch (AxisOrientation)
443 {
444 case AxisOrientation.Top:
445 majorTicksPath.Arrange(new Rect(0, finalSize.Height - tickLength, finalSize.Width, tickLength));
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 gui\InteractiveDataDisplay.WPF\Axes\Axis.cs (line 501)
498 double maxLabelWidth = CalculateMaxLabelWidth();
499 double maxLabelHeight = CalculateMaxLabelHeight();
500
501 switch (AxisOrientation)
502 {
503 case AxisOrientation.Top:
504
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS048 Locking on discouraged object (string, Type, this) 4 hits
📄 gui\InteractiveDataDisplay.WPF\Plots\Markers\MarkerGraph.cs (line 806)
803 {
804 get
805 {
806 lock (this)
807 {
808 return isDrawing;
809 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
📄 gui\InteractiveDataDisplay.WPF\Plots\Markers\MarkerGraph.cs (line 806)
803 {
804 get
805 {
806 lock (this)
807 {
808 return isDrawing;
809 }
💬 A lock was used referencing 'this' which can lead to deadlocks. It is recommended to create a dedicated lock instance of type System.Object instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS048-LockingOnDiscouragedObject.md)
SS051 Locking on mutable reference 20 hits
📄 gui\InteractiveDataDisplay.WPF\Plots\Heatmap\HeatmapGraph.cs (line 75)
72 public long Plot(double[,] data, double[] x, double[] y, double missingValue)
73 {
74 VerifyDimensions(data, x, y);
75 lock (locker)
76 {
77 this.xArr = x;
78 this.yArr = y;
💬 A lock was obtained on locker but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 gui\InteractiveDataDisplay.WPF\Plots\Heatmap\HeatmapGraph.cs (line 166)
163 private static void OnPalettePropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
164 {
165 HeatmapGraph heatmap = (HeatmapGraph)sender;
166 lock (heatmap.locker)
167 {
168 heatmap.paletteRangeUpdateRequired = true;
169 heatmap.palette = (Palette)e.NewValue;
💬 A lock was obtained on locker but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)

fluentmigrator

78 total diagnostics across 9 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 src\FluentMigrator.Runner.Core\StopWatch.cs (line 39)
36 /// This field allows overriding the default behavior of retrieving the current date and time
37 /// (using <see cref="DateTime.Now"/>) for testing or customization purposes.
38 /// </remarks>
39 public static Func<DateTime> TimeNow = () => DateTime.Now;
40
41 private DateTime _startTime;
42 private DateTime _endTime;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\FluentMigrator.Runner.Core\StopWatch.cs (line 39)
36 /// This field allows overriding the default behavior of retrieving the current date and time
37 /// (using <see cref="DateTime.Now"/>) for testing or customization purposes.
38 /// </remarks>
39 public static Func<DateTime> TimeNow = () => DateTime.Now;
40
41 private DateTime _startTime;
42 private DateTime _endTime;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 4 hits
📄 src\FluentMigrator.Runner.Core\MigrationRunner.cs (line 822)
819
820 if (insertCount > 0)
821 {
822 var avg = new TimeSpan(insertTicks / insertCount);
823 var msg = string.Format("-> {0} Insert operations completed in {1} taking an average of {2}", insertCount, new TimeSpan(insertTicks), avg);
824 _logger.LogSay(msg);
825 }
💬 The operands in the divisive expression insertTicks / insertCount are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\FluentMigrator.Runner.Core\MigrationRunner.cs (line 822)
819
820 if (insertCount > 0)
821 {
822 var avg = new TimeSpan(insertTicks / insertCount);
823 var msg = string.Format("-> {0} Insert operations completed in {1} taking an average of {2}", insertCount, new TimeSpan(insertTicks), avg);
824 _logger.LogSay(msg);
825 }
💬 The operands in the divisive expression insertTicks / insertCount are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 12 hits
📄 src\FluentMigrator\Builders\ColumnExpressionBuilderHelper.cs (line 68)
65 {
66 var column = _builder.Column;
67 ExistingRowsData exRowExpr;
68 if (_existingRowsDataByColumn.TryGetValue(column, out exRowExpr))
69 {
70 if (exRowExpr.SetExistingRowsExpression != null)
71 {
💬 Type ColumnDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\FluentMigrator\Builders\ColumnExpressionBuilderHelper.cs (line 130)
127 //ensure an UpdateDataExpression is created and cached for this column
128
129 ExistingRowsData exRowExpr;
130 if (!_existingRowsDataByColumn.TryGetValue(column, out exRowExpr))
131 {
132 exRowExpr = new ExistingRowsData();
133 _existingRowsDataByColumn.Add(column, exRowExpr);
💬 Type ColumnDefinition is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 src\FluentMigrator.Analyzers\MigrationClassDeclaration.cs (line 24)
21 /// <summary>
22 /// Represents a migration class declaration with its associated metadata.
23 /// </summary>
24 public struct MigrationClassDeclaration
25 {
26 /// <summary>
27 /// Initializes a new instance of the <see cref="MigrationClassDeclaration"/> struct.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MigrationClassDeclaration. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\FluentMigrator.Analyzers\MigrationClassDeclaration.cs (line 24)
21 /// <summary>
22 /// Represents a migration class declaration with its associated metadata.
23 /// </summary>
24 public struct MigrationClassDeclaration
25 {
26 /// <summary>
27 /// Initializes a new instance of the <see cref="MigrationClassDeclaration"/> struct.
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MigrationClassDeclaration. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 4 hits
📄 src\FluentMigrator.Runner.Core\Logging\FluentMigratorLogger.cs (line 42)
39 /// <inheritdoc />
40 public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
41 {
42 switch (logLevel)
43 {
44 case LogLevel.Error:
45 case LogLevel.Critical:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\FluentMigrator.Runner.Core\Logging\FluentMigratorLogger.cs (line 42)
39 /// <inheritdoc />
40 public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
41 {
42 switch (logLevel)
43 {
44 case LogLevel.Error:
45 case LogLevel.Critical:
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 20 hits
📄 src\FluentMigrator.Abstractions\ValidationUtilities.cs (line 82)
79 continue;
80 }
81
82 switch (additionalFeaturesValue)
83 {
84 case string _:
85 case decimal _:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\FluentMigrator.Abstractions\ValidationUtilities.cs (line 82)
79 continue;
80 }
81
82 switch (additionalFeaturesValue)
83 {
84 case string _:
85 case decimal _:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS044 Attribute must specify [AttributeUsage] 8 hits
📄 src\FluentMigrator.Runner.Core\Constraints\CurrentVersionMigrationConstraintAttribute.cs (line 23)
20 /// <summary>
21 /// Specifies minimum schema version against which this migration will be run.
22 /// </summary>
23 public class CurrentVersionMigrationConstraintAttribute : MigrationConstraintAttribute
24 {
25 /// <summary>
26 /// Initializes a new instance of the <see cref="CurrentVersionMigrationConstraintAttribute"/> class.
💬 CurrentVersionMigrationConstraintAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 src\FluentMigrator.Runner.Core\Constraints\MigrationConstraintAttribute.cs (line 25)
22 /// <summary>
23 /// Can be used to apply conditions when migrations will be run.
24 /// </summary>
25 public class MigrationConstraintAttribute : Attribute
26 {
27 private readonly Func<MigrationConstraintContext, bool> _predicate;
28
💬 MigrationConstraintAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS058 String concatenated in a loop 4 hits
📄 src\FluentMigrator.Runner.Core\Exceptions\VersionOrderInvalidException.cs (line 95)
92
93 foreach (var pair in InvalidMigrations)
94 {
95 result += $"{Environment.NewLine}{pair.Key} - {pair.Value.Migration.GetType().Name}";
96 }
97
98 return result;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\FluentMigrator.Runner.Core\Exceptions\VersionOrderInvalidException.cs (line 95)
92
93 foreach (var pair in InvalidMigrations)
94 {
95 result += $"{Environment.NewLine}{pair.Key} - {pair.Value.Migration.GetType().Name}";
96 }
97
98 return result;
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 20 hits
📄 src\FluentMigrator.Runner.Core\Initialization\TaskExecutor.cs (line 221)
218 private readonly TaskExecutor _executor;
219
220 [CanBeNull]
221 private readonly IServiceScope _serviceScope;
222
223 private readonly bool _hasCustomRunner;
224
💬 Disposable field _serviceScope in type RunnerScope is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\FluentMigrator.Runner.Core\TransactionalMigrationScope.cs (line 26)
23 /// </summary>
24 public class TransactionalMigrationScope : TrackingMigrationScope
25 {
26 private readonly IMigrationProcessor _migrationProcessor;
27
28 /// <summary>
29 /// Initializes a new instance of the <see cref="TransactionalMigrationScope"/> class.
💬 Disposable field _migrationProcessor in type TransactionalMigrationScope is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

BBDown

76 total diagnostics across 4 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 10 hits
📄 BBDown.Core\Logger.cs (line 13)
10
11 public static void LogError(object text)
12 {
13 Console.Write(DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss.fff]") + " - ");
14 Console.ForegroundColor = ConsoleColor.Red;
15 Console.Write(text);
16 Console.ResetColor();
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 BBDown.Core\Logger.cs (line 7)
4{
5 public static void Log(object text, bool enter = true)
6 {
7 Console.Write(DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss.fff]") + " - " + text);
8 if (enter) Console.WriteLine();
9 }
10
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 34 hits
📄 BBDown.Core\DanmakuUtil.cs (line 122)
119
120 protected class PositionController
121 {
122 readonly int maxLine = MONITOR_HEIGHT * PROTECT_LENGTH / FONT_SIZE / 100; //总行数
123 // 三个位置的弹幕队列,记录弹幕结束时间
124
125 readonly List<double> moveQueue = new();
💬 The operands in the divisive expression MONITOR_HEIGHT * PROTECT_LENGTH / FONT_SIZE / 100 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 BBDown.Core\DanmakuUtil.cs (line 122)
119
120 protected class PositionController
121 {
122 readonly int maxLine = MONITOR_HEIGHT * PROTECT_LENGTH / FONT_SIZE / 100; //总行数
123 // 三个位置的弹幕队列,记录弹幕结束时间
124
125 readonly List<double> moveQueue = new();
💬 The operands in the divisive expression MONITOR_HEIGHT * PROTECT_LENGTH / FONT_SIZE are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 30 hits
📄 BBDown.Core\Entity\Entity.cs (line 178)
175
176 public override int GetHashCode()
177 {
178 return HashCode.Combine(id, dfn, codecs, bandwith, dur);
179 }
180 }
181
💬 GetHashCode() refers to mutable field id (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 BBDown.Core\Entity\Entity.cs (line 178)
175
176 public override int GetHashCode()
177 {
178 return HashCode.Combine(id, dfn, codecs, bandwith, dur);
179 }
180 }
181
💬 GetHashCode() refers to mutable field dfn (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS058 String concatenated in a loop 2 hits
📄 BBDown.Core\Fetcher\BangumiInfoFetcher.cs (line 36)
33 {
34 if (section.ToString().Contains($"/ep{id}"))
35 {
36 title += "[" + section.GetProperty("title").ToString() + "]";
37 pages = section.GetProperty("episodes").EnumerateArray();
38 break;
39 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 BBDown.Core\Fetcher\BangumiInfoFetcher.cs (line 36)
33 {
34 if (section.ToString().Contains($"/ep{id}"))
35 {
36 title += "[" + section.GetProperty("title").ToString() + "]";
37 pages = section.GetProperty("episodes").EnumerateArray();
38 break;
39 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

RyTuneX

76 total diagnostics across 10 rules

SS001 Async method with void return type 10 hits
📄 MainWindow.xaml.cs (line 35)
32 this.AppWindow.Closing += MainWindow_Closing;
33 }
34
35 private async void MainWindow_Closing(Microsoft.UI.Windowing.AppWindow sender, Microsoft.UI.Windowing.AppWindowClosingEventArgs e)
36 {
37 try
38 {
💬 Method MainWindow_Closing is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Views\DebloatSystemPage.xaml.cs (line 91)
88 }
89 }
90
91 private async void LoadInstalledApps(bool uninstallableOnly = true, bool win32Only = false, CancellationToken cancellationToken = default)
92 {
93 try
94 {
💬 Method LoadInstalledApps is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS002 Use DateTime.UtcNow instead of DateTime.Now 12 hits
📄 Helpers\LogHelper.cs (line 15)
12 try
13 {
14 var tempFolder = ApplicationData.Current.TemporaryFolder;
15 var logFile = await tempFolder.CreateFileAsync($"{fileName}_{DateTime.Now:yyyy-MM-dd}.txt", CreationCollisionOption.OpenIfExists);
16
17 // Ensure UTF-8 encoding when appending to the log file
18 using (var stream = await logFile.OpenStreamForWriteAsync())
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Helpers\LogHelper.cs (line 23)
20 stream.Seek(0, SeekOrigin.End); // Append to the file
21 using (var writer = new StreamWriter(stream, new UTF8Encoding(false))) // Disable BOM
22 {
23 await writer.WriteLineAsync($"{DateTime.Now:T}: {message}");
24 }
25 }
26 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 2 hits
📄 Views\HomePage.xaml.cs (line 204)
201 var total = _systemDriveInfo.TotalSize;
202 var free = _systemDriveInfo.TotalFreeSpace;
203 var used = total - free;
204 var percent = total == 0 ? 0 : (int)((used * 100L) / total);
205 return Math.Clamp(percent, 0, 100);
206 }
207 catch
💬 The operands in the divisive expression (used * 100L) / total are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Views\HomePage.xaml.cs (line 204)
201 var total = _systemDriveInfo.TotalSize;
202 var free = _systemDriveInfo.TotalFreeSpace;
203 var used = total - free;
204 var percent = total == 0 ? 0 : (int)((used * 100L) / total);
205 return Math.Clamp(percent, 0, 100);
206 }
207 catch
💬 The operands in the divisive expression (used * 100L) / total are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 14 hits
📄 App.xaml.cs (line 44)
41{
42 // P/Invoke for Taskbar Flashing
43 [StructLayout(LayoutKind.Sequential)]
44 private struct FLASHWINFO
45 {
46 public uint cbSize;
47 public IntPtr hwnd;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct FLASHWINFO. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Helpers\PseudoConsoleHelper.cs (line 43)
40 private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
41
42 [StructLayout(LayoutKind.Sequential)]
43 private struct COORD
44 {
45 public short X, Y;
46 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct COORD. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 8 hits
📄 Views\DebloatSystemPage.xaml.cs (line 439)
436
437 private void appsFilter_SelectionChanged(object sender, RoutedEventArgs e)
438 {
439 switch (appsFilter.SelectedIndex)
440 {
441 case 0:
442 LoadInstalledApps(true, false, cancellationTokenSource.Token);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Views\OptimizeSystemPage.xaml.cs (line 240)
237 key?.SetValue("WindowsUpdatesMode", mode, RegistryValueKind.String);
238
239 // Apply the selected mode
240 switch (mode)
241 {
242 case "Default":
243 await OptimizeSystemHelper.SetWindowsUpdatesDefault();
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 12 hits
📄 Views\GroupPolicyPage.xaml.cs (line 55)
52
53 private async Task ScanPoliciesAsync()
54 {
55 _cancellationTokenSource?.Cancel();
56 if (_cancellationRegistrationId.HasValue)
57 {
58 OperationCancellationManager.Unregister(_cancellationRegistrationId.Value);
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Helpers\OptimizeSystemHelper.cs (line 541)
538 };
539
540 var lines = new List<string>();
541 lines.AddRange(File.ReadAllLines(hostsPath));
542
543 foreach (var host in safeTelemetryHosts)
544 {
💬 Async overload available for File.ReadAllLines (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 4 hits
📄 Helpers\OptimizationOptions.cs (line 57)
54
55 await Task.WhenAll(uwpAppsTask, win32AppsTask);
56
57 var installedApps = uwpAppsTask.Result.Concat(win32AppsTask.Result).ToList();
58
59 installedApps = [.. installedApps
60 .DistinctBy(app => app.Item1) // Remove duplicates based on app name
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Helpers\OptimizationOptions.cs (line 57)
54
55 await Task.WhenAll(uwpAppsTask, win32AppsTask);
56
57 var installedApps = uwpAppsTask.Result.Concat(win32AppsTask.Result).ToList();
58
59 installedApps = [.. installedApps
60 .DistinctBy(app => app.Item1) // Remove duplicates based on app name
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS058 String concatenated in a loop 2 hits
📄 Helpers\OptimizationOptions.cs (line 123)
120 }
121 else if (!string.IsNullOrWhiteSpace(currentLocation) && line.StartsWith(" ", StringComparison.Ordinal))
122 {
123 currentLocation += " " + line.Trim();
124 }
125 }
126
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 Helpers\OptimizationOptions.cs (line 123)
120 }
121 else if (!string.IsNullOrWhiteSpace(currentLocation) && line.StartsWith(" ", StringComparison.Ordinal))
122 {
123 currentLocation += " " + line.Trim();
124 }
125 }
126
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 Helpers\LogHelper.cs (line 18)
15 var logFile = await tempFolder.CreateFileAsync($"{fileName}_{DateTime.Now:yyyy-MM-dd}.txt", CreationCollisionOption.OpenIfExists);
16
17 // Ensure UTF-8 encoding when appending to the log file
18 using (var stream = await logFile.OpenStreamForWriteAsync())
19 {
20 stream.Seek(0, SeekOrigin.End); // Append to the file
21 using (var writer = new StreamWriter(stream, new UTF8Encoding(false))) // Disable BOM
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Helpers\LogHelper.cs (line 21)
18 using (var stream = await logFile.OpenStreamForWriteAsync())
19 {
20 stream.Seek(0, SeekOrigin.End); // Append to the file
21 using (var writer = new StreamWriter(stream, new UTF8Encoding(false))) // Disable BOM
22 {
23 await writer.WriteLineAsync($"{DateTime.Now:T}: {message}");
24 }
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS060 ConcurrentDictionary emptiness check without IsEmpty 4 hits
📄 Helpers\OperationCancellationManager.cs (line 60)
57 var hasTimeout = timeout.HasValue;
58 var to = timeout ?? TimeSpan.Zero;
59
60 while (_ctsMap.Count > 0 || OptimizationOptions.HasPendingToggleOperations)
61 {
62 if (hasTimeout && sw.Elapsed >= to)
63 break;
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)
📄 Helpers\OperationCancellationManager.cs (line 68)
65 await Task.Delay(250).ConfigureAwait(false);
66 }
67
68 return _ctsMap.Count == 0 && !OptimizationOptions.HasPendingToggleOperations;
69 }
70}
💬 Use ConcurrentDictionary.IsEmpty to check for emptiness without locking the entire dictionary (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md)

OpenTabletDriver

74 total diagnostics across 6 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 OpenTabletDriver.Plugin\Logging\LogMessage.cs (line 23)
20 /// <summary>
21 /// The time in which a log message was created.
22 /// </summary>
23 public DateTime Time { set; get; } = DateTime.Now;
24
25 /// <summary>
26 /// The group in which the log message belongs to.
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 OpenTabletDriver.Plugin\Logging\LogMessage.cs (line 23)
20 /// <summary>
21 /// The time in which a log message was created.
22 /// </summary>
23 public DateTime Time { set; get; } = DateTime.Now;
24
25 /// <summary>
26 /// The group in which the log message belongs to.
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 2 hits
📄 OpenTabletDriver.Native\Windows\USB\StringDescriptor.cs (line 26)
23 if (descriptor->bLength == 0)
24 return "";
25
26 var unicodeLength = (descriptor->bLength - 1) / 2;
27 var deviceString = new Span<char>(&descriptor->bString, unicodeLength).ToString();
28 return deviceString;
29 }
💬 The operands in the divisive expression (descriptor->bLength - 1) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 OpenTabletDriver.Native\Windows\USB\StringDescriptor.cs (line 26)
23 if (descriptor->bLength == 0)
24 return "";
25
26 var unicodeLength = (descriptor->bLength - 1) / 2;
27 var deviceString = new Span<char>(&descriptor->bString, unicodeLength).ToString();
28 return deviceString;
29 }
💬 The operands in the divisive expression (descriptor->bLength - 1) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 58 hits
📄 OpenTabletDriver.Plugin\Tablet\DeviceReport.cs (line 3)
1namespace OpenTabletDriver.Plugin.Tablet
2{
3 public struct DeviceReport : IDeviceReport
4 {
5 public DeviceReport(byte[] report)
6 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DeviceReport. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 OpenTabletDriver.Plugin\Tablet\AuxReport.cs (line 3)
1namespace OpenTabletDriver.Plugin.Tablet
2{
3 public struct AuxReport : IAuxReport
4 {
5 public AuxReport(byte[] report)
6 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct AuxReport. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 4 hits
📄 OpenTabletDriver.Plugin\Output\PipelineManager.cs (line 13)
10 {
11 if (source != null && destination != null)
12 {
13 switch (destination)
14 {
15 case IPipelineElement<T> nextElement:
16 source.Emit += nextElement.Consume;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 OpenTabletDriver.Plugin\Output\PipelineManager.cs (line 32)
29 {
30 if (source != null && destination != null)
31 {
32 switch (destination)
33 {
34 case IPipelineElement<T> nextElement:
35 source.Emit -= nextElement.Consume;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS044 Attribute must specify [AttributeUsage] 6 hits
📄 OpenTabletDriver.Plugin\Attributes\ModifierAttribute.cs (line 8)
5 /// <summary>
6 /// Base attribute class for attributes which provide extra information to a property.
7 /// </summary>
8 public abstract class ModifierAttribute : Attribute
9 {
10 }
11}
💬 ModifierAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 OpenTabletDriver.Plugin\Attributes\ToolTipAttribute.cs (line 8)
5 /// <summary>
6 /// Applies a tooltip to a property on the client.
7 /// </summary>
8 public class ToolTipAttribute : ModifierAttribute
9 {
10 public ToolTipAttribute(string tooltip)
11 {
💬 ToolTipAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS051 Locking on mutable reference 2 hits
📄 OpenTabletDriver.Native\Linux\Xorg\XLib.cs (line 20)
17 private extern unsafe static IntPtr sys_XOpenDisplay(char* display);
18 public static unsafe IntPtr XOpenDisplay(char* display)
19 {
20 lock (Lock)
21 return sys_XOpenDisplay(display);
22 }
23
💬 A lock was obtained on Lock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 OpenTabletDriver.Native\Linux\Xorg\XLib.cs (line 20)
17 private extern unsafe static IntPtr sys_XOpenDisplay(char* display);
18 public static unsafe IntPtr XOpenDisplay(char* display)
19 {
20 lock (Lock)
21 return sys_XOpenDisplay(display);
22 }
23
💬 A lock was obtained on Lock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)

CSharpRepl

72 total diagnostics across 11 rules

SS003 Integer divided by integer causing implicit rounding 2 hits
📄 CSharpRepl.Services\Roslyn\Formatting\CustomObjectFormatters\IEnumerableFormatter.cs (line 41)
38 sb.Append(", ");
39
40 if (maxParagraphLength > sb.Length &&
41 sb.Length > formatter.ConsoleProfile.Width / 2) //just heuristic
42 {
43 sb.Append(", ...");
44 break;
💬 The operands in the divisive expression formatter.ConsoleProfile.Width / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 CSharpRepl.Services\Roslyn\Formatting\CustomObjectFormatters\IEnumerableFormatter.cs (line 41)
38 sb.Append(", ");
39
40 if (maxParagraphLength > sb.Length &&
41 sb.Length > formatter.ConsoleProfile.Width / 2) //just heuristic
42 {
43 sb.Append(", ...");
44 break;
💬 The operands in the divisive expression formatter.ConsoleProfile.Width / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 4 hits
📄 CSharpRepl.Services\Roslyn\References\AssemblyReferenceService.cs (line 55)
52 this.loadedReferenceAssemblies = new(new AssemblyReferenceComparer());
53 this.loadedImplementationAssemblies = new(new AssemblyReferenceComparer());
54
55 this.usings = new[] {
56 "System", "System.IO", "System.Collections.Generic",
57 "System.Linq", "System.Net.Http",
58 "System.Text", "System.Threading.Tasks"
💬 Type UsingDirectiveSyntax is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 CSharpRepl.Services\Roslyn\MetadataResolvers\SolutionFileMetadataResolver.cs (line 69)
66 console.WriteErrorLine(error.Message);
67 }
68
69 return projects
70 .SelectMany(p =>
71 p.MetadataReferences
72 .OfType<PortableExecutableReference>()
💬 Type PortableExecutableReference is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 2 hits
📄 CSharpRepl.Services\Roslyn\MetadataResolvers\CompositeMetadataReferenceResolver.cs (line 57)
54 && EqualityComparer<IIndividualMetadataReferenceResolver[]>.Default.Equals(resolvers, other.resolvers);
55
56 public override int GetHashCode() =>
57 HashCode.Combine(resolvers);
58}
💬 GetHashCode() refers to mutable field resolvers (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 CSharpRepl.Services\Roslyn\MetadataResolvers\CompositeMetadataReferenceResolver.cs (line 57)
54 && EqualityComparer<IIndividualMetadataReferenceResolver[]>.Default.Equals(resolvers, other.resolvers);
55
56 public override int GetHashCode() =>
57 HashCode.Combine(resolvers);
58}
💬 GetHashCode() refers to mutable field resolvers (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 28 hits
📄 CSharpRepl.Services\Roslyn\Microsoft.CodeAnalysis.PooledObjects\ObjectPool`1.cs (line 45)
42internal class ObjectPool<T> where T : class
43{
44 [DebuggerDisplay("{Value,nq}")]
45 private struct Element
46 {
47 internal T? Value;
48 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Element. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 CSharpRepl.Services\Theming\SyntaxHighlightingColor.cs (line 10)
7
8namespace CSharpRepl.Services.Theming;
9
10public readonly struct SyntaxHighlightingColor
11{
12 [JsonConstructor]
13 public SyntaxHighlightingColor(string name, string foreground)
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SyntaxHighlightingColor. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 6 hits
📄 CSharpRepl.Services\Roslyn\Microsoft.CodeAnalysis.CSharp\ObjectDisplay.cs (line 37)
34 private static bool TryReplaceChar(char c, out string replaceWith)
35 {
36 replaceWith = null;
37 switch (c)
38 {
39 case '\\':
40 replaceWith = "\\\\";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 CSharpRepl\ReadEvalPrintLoop.cs (line 119)
116
117 private static async Task PrintAsync(RoslynServices roslyn, IConsoleEx console, EvaluationResult result, Level level)
118 {
119 switch (result)
120 {
121 case EvaluationResult.Success ok:
122 if (ok.ReturnValue.HasValue)
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 8 hits
📄 CSharpRepl.Services\Roslyn\RoslynServices.cs (line 438)
435 {
436 if (runtimeHelperStream != null)
437 {
438 var runtimeHelperText = new StreamReader(runtimeHelperStream).ReadToEnd();
439 evaluationTask = EvaluateAsync(runtimeHelperText, args);
440 }
441 else
💬 Async overload available for StreamReader.ReadToEnd (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 CSharpRepl.Services\Roslyn\RoslynServices.cs (line 467)
464
465 if ((await scriptRunner.HasValueReturningStatement(input, cancellationToken).ConfigureAwait(false)).TryGet(out var result))
466 {
467 var root = result.Expression.SyntaxTree.GetRoot(cancellationToken);
468 var expressionToBeWrapped = result.Expression;
469 var wrappedExpression = expressionToBeWrapped;
470 if (result.Type is { Name: "Span" or "ReadOnlySpan", ContainingNamespace.Name: "System" })
💬 Async overload available for SyntaxTree.GetRoot (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS050 Parameter assigned in constructor 2 hits
📄 CSharpRepl.Services\Configuration.cs (line 99)
96 }
97 else
98 {
99 if (string.IsNullOrEmpty(theme)) theme = DefaultThemeRelativePath;
100 bool themeExists = File.Exists(theme);
101 if (!themeExists)
102 {
💬 Suspicious assignment of parameter theme in constructor of Configuration (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
📄 CSharpRepl.Services\Configuration.cs (line 99)
96 }
97 else
98 {
99 if (string.IsNullOrEmpty(theme)) theme = DefaultThemeRelativePath;
100 bool themeExists = File.Exists(theme);
101 if (!themeExists)
102 {
💬 Suspicious assignment of parameter theme in constructor of Configuration (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS050-ParameterAssignedInConstructor.md)
SS057 Collection manipulated during traversal 2 hits
📄 CSharpRepl.Services\Nuget\ConsoleNugetLogger.cs (line 71)
68 {
69 if (!lines[i].IsError)
70 {
71 lines.RemoveAt(i);
72 break;
73 }
74 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
📄 CSharpRepl.Services\Nuget\ConsoleNugetLogger.cs (line 71)
68 {
69 if (!lines[i].IsError)
70 {
71 lines.RemoveAt(i);
72 break;
73 }
74 }
💬 Attempted to manipulate a collection while traversing. Ensure modifications don't affect the original collection. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 CSharpRepl.Services\Roslyn\RoslynServices.cs (line 434)
431
432 const string RuntimeHelperName = "CSharpRepl.Services.RuntimeHelper.cs";
433 Task evaluationTask;
434 using (var runtimeHelperStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(RuntimeHelperName))
435 {
436 if (runtimeHelperStream != null)
437 {
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 CSharpRepl.Services\Roslyn\RoslynServices.cs (line 434)
431
432 const string RuntimeHelperName = "CSharpRepl.Services.RuntimeHelper.cs";
433 Task evaluationTask;
434 using (var runtimeHelperStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(RuntimeHelperName))
435 {
436 if (runtimeHelperStream != null)
437 {
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS064 Unnecessary ToString() on Span 8 hits
📄 CSharpRepl.Tests\FakeConsole.cs (line 306)
303 public void Write(ReadOnlySpan<char> value) => Write(value.ToString());
304 public void WriteError(ReadOnlySpan<char> value) => WriteError(value.ToString());
305 public void WriteErrorLine(ReadOnlySpan<char> value) => WriteErrorLine(value.ToString());
306 public void WriteLine(ReadOnlySpan<char> value) => WriteLine(value.ToString());
307}
💬 Unnecessary ToString() call, an overload that accepts ReadOnlySpan<char> is available (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS064-UnnecessaryToStringOnSpan.md)
📄 CSharpRepl.Tests\FakeConsole.cs (line 303)
300 public abstract void WriteLine(string? value);
301
302 //following implementations is needed because NSubstitute does not support ROS
303 public void Write(ReadOnlySpan<char> value) => Write(value.ToString());
304 public void WriteError(ReadOnlySpan<char> value) => WriteError(value.ToString());
305 public void WriteErrorLine(ReadOnlySpan<char> value) => WriteErrorLine(value.ToString());
306 public void WriteLine(ReadOnlySpan<char> value) => WriteLine(value.ToString());
💬 Unnecessary ToString() call, an overload that accepts ReadOnlySpan<char> is available (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS064-UnnecessaryToStringOnSpan.md)
SS066 Disposable field is not disposed 8 hits
📄 CSharpRepl.Tests\ProgramTests.cs (line 61)
58{
59 private static readonly Semaphore semaphore = new(1, 1);
60
61 private readonly TextWriter normalStandardOutput;
62 private readonly TextWriter normalStandardError;
63 private readonly StringWriter fakeConsoleOutput;
64 private readonly StringWriter fakeConsoleError;
💬 Disposable field normalStandardOutput in type OutputCollector is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 CSharpRepl.Tests\ProgramTests.cs (line 62)
59 private static readonly Semaphore semaphore = new(1, 1);
60
61 private readonly TextWriter normalStandardOutput;
62 private readonly TextWriter normalStandardError;
63 private readonly StringWriter fakeConsoleOutput;
64 private readonly StringWriter fakeConsoleError;
65
💬 Disposable field normalStandardError in type OutputCollector is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

orleans

64 total diagnostics across 6 rules

SS005 Equals() and GetHashCode() not implemented together 2 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 12 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 10 hits
No source samples extracted
SS018 Switch does not handle all enum options 4 hits
No source samples extracted
SS019 Switch is missing default label 34 hits
No source samples extracted
SS046 Unbounded stackalloc 2 hits
No source samples extracted

VsVim

64 total diagnostics across 5 rules

SS003 Integer divided by integer causing implicit rounding 4 hits
📄 Src\VimWpf\Implementation\Mouse\VimMouseProcessor.cs (line 34)
31 _mouseDevice = InputManager.Current.PrimaryMouseDevice;
32 _mouseCaptured = false;
33 _scrollTimer = new DispatcherTimer(
34 new TimeSpan(0, 0, 0, 0, 1000 / s_linesPerSecond),
35 DispatcherPriority.Normal,
36 protectedOperations.GetProtectedEventHandler(OnScrollTimer),
37 Dispatcher.CurrentDispatcher);
💬 The operands in the divisive expression 1000 / s_linesPerSecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Src\VimWpf\Implementation\CharDisplay\CharDisplayTaggerSource.cs (line 174)
171
172 do
173 {
174 mid = (min + max) / 2;
175 current = _adornmentCache[mid].Position;
176
177 if (current == position)
💬 The operands in the divisive expression (min + max) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 12 hits
📄 Src\VimTestUtils\Extensions.cs (line 42)
39 TaskScheduler.Default);
40 }
41
42 internal readonly struct SemaphoreDisposer : IDisposable
43 {
44 private readonly Semaphore _semaphore;
45
💬 Implement Equals(), GetHashCode() and ToString() methods on struct SemaphoreDisposer. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Src\VimEditorHost\KeyboardInputSimulation.cs (line 176)
173
174 #region KeyData
175
176 private readonly struct KeyData
177 {
178 internal readonly Key Key;
179 internal readonly ModifierKeys ModifierKeys;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct KeyData. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 18 hits
📄 Src\VimEditorHost\KeyboardInputSimulation.cs (line 415)
412
413 private Key VimKeyToKey(VimKey vimKey)
414 {
415 switch (vimKey)
416 {
417 case VimKey.Escape:
418 return Key.Escape;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 Src\VimApp\VimAppHost.cs (line 241)
238 }
239
240 var target = -1;
241 switch (windowKind)
242 {
243 case WindowKind.Up:
244 target = i - 1;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 26 hits
📄 Src\VimEditorHost\KeyboardInputSimulation.cs (line 415)
412
413 private Key VimKeyToKey(VimKey vimKey)
414 {
415 switch (vimKey)
416 {
417 case VimKey.Escape:
418 return Key.Escape;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Src\VimApp\VimAppHost.cs (line 241)
238 }
239
240 var target = -1;
241 switch (windowKind)
242 {
243 case WindowKind.Up:
244 target = i - 1;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS066 Disposable field is not disposed 4 hits
📄 Src\VimTestUtils\Extensions.cs (line 44)
41
42 internal readonly struct SemaphoreDisposer : IDisposable
43 {
44 private readonly Semaphore _semaphore;
45
46 public SemaphoreDisposer(Semaphore semaphore)
47 {
💬 Disposable field _semaphore in type SemaphoreDisposer is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Src\VimWpf\Implementation\RelativeLineNumbers\RelativeLineNumbersMargin.cs (line 18)
15 private readonly IWpfTextView _textView;
16 private readonly ILineFormatTracker _formatTracker;
17 private readonly IVimLocalSettings _localSettings;
18 private readonly IWpfTextViewMargin _marginContainer;
19 private readonly IProtectedOperations _protectedOperations;
20
21 private readonly LineNumbersTracker _linesTracker;
💬 Disposable field _marginContainer in type RelativeLineNumbersMargin is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Emby.Plugins.JavScraper

64 total diagnostics across 7 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 32 hits
📄 Emby.Actress\EmbyActressImportService.cs (line 32)
29
30 sb.AppendLine($@"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>
31<movie>
32 <dateadded>{DateTime.Now:yyyy-MM-dd HH:mm}</dateadded>
33 <title>全部女优</title>");
34
35 foreach (var a in ls)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Emby.Plugins.JavScraper\Baidu\BaiduAccessToken.cs (line 53)
50 /// <summary>
51 /// 创建时间
52 /// </summary>
53 public DateTime created { get; set; } = DateTime.Now;
54
55 /// <summary>
56 /// 过期时间
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 8 hits
📄 Emby.Plugins.JavScraper\Services\ImageProxyService.cs (line 186)
183 {
184 var h = bitmap.Height;
185 var w = bitmap.Width;
186 var w2 = h * 2 / 3; //封面宽度
187
188 if (w2 < w) //需要剪裁
189 {
💬 The operands in the divisive expression h * 2 / 3 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Emby.Plugins.JavScraper\Services\ImageProxyService.cs (line 195)
192
193 if (x > 0) //百度人体识别,中心点位置
194 {
195 if (x + w2 / 2 > w) //右边
196 start_w = w - w2;
197 else if (x - w2 / 2 < 0)//左边
198 start_w = 0;
💬 The operands in the divisive expression w2 / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS032 Thread.Sleep used in async method 4 hits
📄 Emby.Plugins.JavScraper\Extensions\NamedLockerAsync.cs (line 43)
40 finally
41 {
42 locker.Release();
43 Thread.Sleep(1);
44 if (locker.CurrentCount == 1)
45 {
46 _lockDict.TryRemove(name, out locker);
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
📄 Emby.Plugins.JavScraper\Extensions\NamedLockerAsync.cs (line 71)
68 finally
69 {
70 locker.Release();
71 Thread.Sleep(1);
72 if (locker.CurrentCount == 1)
73 {
74 _lockDict.TryRemove(name, out locker);
💬 Synchronously sleeping thread in an async method (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS032-ThreadSleepInAsyncMethod.md)
SS033 Async overload is available 8 hits
📄 Emby.Plugins.JavScraper\Services\UpdateService.cs (line 84)
81
82 if (resp.StatusCode == System.Net.HttpStatusCode.OK)
83 {
84 var data = jsonSerializer.DeserializeFromStream<Rootobject>(await resp.Content.ReadAsStreamAsync());
85 r.UpdateMessage = data.body;
86
87 string key =
💬 Async overload available for IJsonSerializer.DeserializeFromStream (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Emby.Actress\EmbyActressImportService.cs (line 67)
64
65 try
66 {
67 File.WriteAllText(nfo_name, nfo_txt);
68 Console.WriteLine($"保存 {nfo_name} 文件成功,如何使用请参阅 https://github.com/JavScraper/Emby.Plugins.JavScraper/Emby.Actress");
69 }
70 catch
💬 Async overload available for File.WriteAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 6 hits
📄 Emby.Plugins.JavScraper\Extensions\NamedLockerAsync.cs (line 95)
92 return wait.IsCompleted ?
93 m_releaser :
94 wait.ContinueWith((_, state) => (IDisposable)state,
95 m_releaser.Result, CancellationToken.None,
96 TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
97 }
98
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Emby.Plugins.JavScraper\JavMovieProvider.cs (line 301)
298 scrapers = scrapers.Where(o => enableScrapers.Contains(o.Name)).ToList();
299 var tasks = scrapers.Select(o => o.Query(key)).ToArray();
300 await Task.WhenAll(tasks);
301 var all = tasks.Where(o => o.Result?.Any() == true).SelectMany(o => o.Result).ToList();
302
303 _logger?.Info($"{nameof(GetSearchResults)} name:{searchInfo.Name} id:{javid?.id} count:{all.Count}");
304
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS047 LINQ traversal before filter 4 hits
📄 Emby.Plugins.JavScraper\FixChineseSubtitleGenreTask.cs (line 78)
75 dir.LibraryOptions.TypeOptions?.Any(o => o.MetadataFetchers?.Contains(Plugin.NAME) == true) == true)
76 .SelectMany(o => o.Locations).ToList();
77
78 var eligibleFiles = libraryFolderPaths.SelectMany(GetVideoFiles)
79 .OrderBy(_fileSystem.GetCreationTimeUtc)
80 .Where(i => IsVideoFile(i))
81 .ToList();
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
📄 Emby.Plugins.JavScraper\JavOrganizeTask.cs (line 98)
95 .Where(o => IsValidWatchLocation(o, libraryFolderPaths))
96 .ToList();
97
98 var eligibleFiles = watchLocations.SelectMany(GetFilesToOrganize)
99 .OrderBy(_fileSystem.GetCreationTimeUtc)
100 .Where(i => EnableOrganization(i, options))
101 .ToList();
💬 Unexpected collection traversal before Where() clause. Could the traversal be more efficient if filtering is performed first? (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 Emby.Plugins.JavScraper\Services\ImageProxyService.cs (line 177)
174 logger?.Info($"{nameof(CutImage)}: staring...");
175 try
176 {
177 using (var ms = new MemoryStream(bytes))
178 {
179 ms.Position = 0;
180 using (var inputStream = new SKManagedStream(ms))
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Emby.Plugins.JavScraper\Services\ImageProxyService.cs (line 177)
174 logger?.Info($"{nameof(CutImage)}: staring...");
175 try
176 {
177 using (var ms = new MemoryStream(bytes))
178 {
179 ms.Position = 0;
180 using (var inputStream = new SKManagedStream(ms))
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)

FluentTerminal

62 total diagnostics across 1 rules

SS008 GetHashCode() refers to mutable or static member 62 hits
📄 FluentTerminal.Models\ExportedTerminalTheme.cs (line 28)
25
26 public override int GetHashCode()
27 {
28 return -1751912210 + EqualityComparer<string>.Default.GetHashCode(EncodedImage);
29 }
30 }
31}
💬 GetHashCode() refers to mutable property EncodedImage (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 FluentTerminal.Models\TerminalTheme.cs (line 42)
39
40 public override int GetHashCode()
41 {
42 return HashCode.Combine(Name, Author, Colors);
43 }
44 }
45}
💬 GetHashCode() refers to mutable property Name (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)

YoutubePlaylistDownloader

56 total diagnostics across 4 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 YoutubePlaylistDownloader\GlobalConsts.cs (line 252)
249 public static async Task Log(string message, object sender)
250 {
251 using StreamWriter sw = new(ErrorFilePath, true);
252 await sw.WriteLineAsync($"[{DateTime.Now.ToUniversalTime()}], [{sender}]:\n\n{message}\n\n").ConfigureAwait(false);
253
254 }
255 public static string CleanFileName(string filename)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 YoutubePlaylistDownloader\GlobalConsts.cs (line 252)
249 public static async Task Log(string message, object sender)
250 {
251 using StreamWriter sw = new(ErrorFilePath, true);
252 await sw.WriteLineAsync($"[{DateTime.Now.ToUniversalTime()}], [{sender}]:\n\n{message}\n\n").ConfigureAwait(false);
253
254 }
255 public static string CleanFileName(string filename)
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 12 hits
📄 YoutubePlaylistDownloader\GlobalConsts.cs (line 281)
278 {
279 using var imageBuffer = new MemoryStream(imageBytes);
280 using var image = System.Drawing.Image.FromStream(imageBuffer);
281 var cropRectangle = new Rectangle((image.Width - image.Height) / 2, 0, image.Height, image.Height);
282 using var bitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height);
283 using var graphics = Graphics.FromImage(bitmap);
284 graphics.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height), cropRectangle, GraphicsUnit.Pixel);
💬 The operands in the divisive expression (image.Width - image.Height) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 YoutubePlaylistDownloader\DownloadPage.xaml.cs (line 370)
367 {
368 try
369 {
370 var percent = Convert.ToInt32(args.StreamLength * 100 / bestQuality.Size.Bytes);
371 CurrentProgressPercent = percent;
372 double speedInMB = 0;
373 var delta = sw.Elapsed - ts;
💬 The operands in the divisive expression args.StreamLength * 100 / bestQuality.Size.Bytes are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS059 IAsyncDisposable not disposed asynchronously 24 hits
📄 YoutubePlaylistDownloader\GlobalConsts.cs (line 251)
248 }
249 public static async Task Log(string message, object sender)
250 {
251 using StreamWriter sw = new(ErrorFilePath, true);
252 await sw.WriteLineAsync($"[{DateTime.Now.ToUniversalTime()}], [{sender}]:\n\n{message}\n\n").ConfigureAwait(false);
253
254 }
💬 StreamWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 YoutubePlaylistDownloader\DownloadUpdate.xaml.cs (line 116)
113 private async Task StartUpdate()
114 {
115 await Dispatcher.InvokeAsync(() => HeadlineTextBlock.Text = $"{FindResource("DownloadingUpdateSetup")}");
116 using var fs = new ProgressStream(new FileStream(GlobalConsts.UpdateSetupLocation, FileMode.Create));
117 fs.BytesWritten += DownloadProgressChanged;
118 var latestVersionLink = await httpClient.GetAsync("https://raw.githubusercontent.com/shaked6540/YoutubePlaylistDownloader/master/YoutubePlaylistDownloader/latestVersionLink.txt").ConfigureAwait(false);
119 var response = await httpClient.GetAsync(await latestVersionLink.Content.ReadAsStringAsync().ConfigureAwait(false)).ConfigureAwait(false);
💬 ProgressStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 16 hits
📄 YoutubePlaylistDownloader\DownloadUpdate.xaml.cs (line 81)
78 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentStatus)));
79 }
80 }
81 private HttpClient httpClient;
82 private readonly CancellationTokenSource cancellationTokenSource;
83
84 public DownloadUpdate(Version latestVersion, string changelog, bool updateLater = false)
💬 Disposable field httpClient in type DownloadUpdate is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 YoutubePlaylistDownloader\DownloadUpdate.xaml.cs (line 82)
79 }
80 }
81 private HttpClient httpClient;
82 private readonly CancellationTokenSource cancellationTokenSource;
83
84 public DownloadUpdate(Version latestVersion, string changelog, bool updateLater = false)
85 {
💬 Disposable field cancellationTokenSource in type DownloadUpdate is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

parsec-vdd

54 total diagnostics across 6 rules

SS003 Integer divided by integer causing implicit rounding 6 hits
📄 app\Components\CustomPage.xaml.cs (line 42)
39 // Check negative values & limit 8K resolution
40 if (width < 0 || width > 7680 || height < 0 || height > 4320 || hz < 0)
41 {
42 MessageBox.Show(App.GetTranslation("t_msg_custom_invalid_slot", i / 3 + 1),
43 Program.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
44 return;
45 }
💬 The operands in the divisive expression i / 3 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 app\MirrorWindow.cs (line 254)
251 }
252
253 // center the viewport
254 viewportX = (clientWidth - viewportWidth) / 2;
255 viewportY = (clientHeight - viewportHeight) / 2;
256
257 return new Viewport
💬 The operands in the divisive expression (clientWidth - viewportWidth) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 30 hits
📄 app\Helper.cs (line 107)
104 static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
105
106 [StructLayout(LayoutKind.Sequential)]
107 struct MARGINS
108 {
109 public int leftWidth;
110 public int rightWidth;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MARGINS. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 app\PowerEvents.cs (line 233)
230 public delegate uint DeviceNotifyCallbackRoutine(IntPtr Context, uint Type, IntPtr Setting);
231
232 [StructLayout(LayoutKind.Sequential)]
233 public struct DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS
234 {
235 [MarshalAs(UnmanagedType.FunctionPtr)]
236 public DeviceNotifyCallbackRoutine Callback;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 2 hits
📄 app\Tray.cs (line 178)
175 }
176 else if (ex is Vdd.ErrorOperationFailed errOperation)
177 {
178 switch (errOperation.Type)
179 {
180 case Vdd.ErrorOperationFailed.Operation.AddDisplay:
181 message = App.GetTranslation("t_msg_failed_to_add_display");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 app\Tray.cs (line 178)
175 }
176 else if (ex is Vdd.ErrorOperationFailed errOperation)
177 {
178 switch (errOperation.Type)
179 {
180 case Vdd.ErrorOperationFailed.Operation.AddDisplay:
181 message = App.GetTranslation("t_msg_failed_to_add_display");
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 2 hits
📄 app\MirrorWindow.cs (line 66)
63
64 private void MirrorWorker(string displayDevice, int fps)
65 {
66 var hwnd = WhenHwnd.Task.Result;
67
68 var dcDest = Native.GetDC(hwnd);
69 var bgBrush = Native.GetStockObject(/*BLACK_BRUSH*/ 4);
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 app\MirrorWindow.cs (line 66)
63
64 private void MirrorWorker(string displayDevice, int fps)
65 {
66 var hwnd = WhenHwnd.Task.Result;
67
68 var dcDest = Native.GetDC(hwnd);
69 var bgBrush = Native.GetStockObject(/*BLACK_BRUSH*/ 4);
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS046 Unbounded stackalloc 4 hits
📄 app\Device.cs (line 163)
160 {
161 uint propType;
162 int length = 128 * sizeof(ushort);
163 var buffer = stackalloc byte[length];
164
165 Native.CM_Get_DevNode_PropertyW(devInst,
166 ref Native.DEVPROPKEY.Device_DeviceDesc, &propType, buffer, &length, 0);
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
📄 app\Device.cs (line 202)
199 public static Version GetDeviceDriverVersion(uint devInst)
200 {
201 int length = 64;
202 var buffer = stackalloc byte[length];
203
204 uint propType;
205 Native.CM_Get_DevNode_PropertyW(devInst,
💬 An array is stack allocated without checking the length. Explicitly check the length against a constant value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS046-UnboundedStackalloc.md)
SS066 Disposable field is not disposed 10 hits
📄 app\Tray.cs (line 18)
15 NotifyIcon TrayIcon;
16 Thread GuiThread;
17
18 ToolStripMenuItem MI_Language;
19
20 ToolStripMenuItem MI_RunOnStartup;
21 ToolStripMenuItem MI_RestoreDisplays;
💬 Disposable field MI_Language in type Tray is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 app\Tray.cs (line 20)
17
18 ToolStripMenuItem MI_Language;
19
20 ToolStripMenuItem MI_RunOnStartup;
21 ToolStripMenuItem MI_RestoreDisplays;
22 ToolStripMenuItem MI_FallbackDisplay;
23 ToolStripMenuItem MI_KeepScreenOn;
💬 Disposable field MI_RunOnStartup in type Tray is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Seq.Api

52 total diagnostics across 5 rules

SS017 Struct without Equals/GetHashCode/ToString overridden 24 hits
No source samples extracted
SS033 Async overload is available 12 hits
No source samples extracted
SS034 Accessing Task.Result without await 6 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 4 hits
No source samples extracted
SS066 Disposable field is not disposed 6 hits
No source samples extracted

qmk_toolbox

50 total diagnostics across 6 rules

SS001 Async method with void return type 10 hits
📄 windows\QMK Toolbox\MainWindow.cs (line 312)
309 }
310 }
311
312 private async void ResetAllAsync()
313 {
314 string selectedMcu = (string)mcuBox.SelectedValue;
315
💬 Method ResetAllAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 windows\QMK Toolbox\MainWindow.cs (line 277)
274 }
275 }
276
277 private async void FlashAllAsync()
278 {
279 string selectedMcu = (string)mcuBox.SelectedValue;
280 string filePath = filepathBox.Text;
💬 Method FlashAllAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS019 Switch is missing default label 22 hits
📄 windows\QMK Toolbox\LogTextBox.cs (line 64)
61
62 foreach (string line in lines)
63 {
64 switch (type)
65 {
66 case MessageType.Bootloader:
67 AppendText($"{line}\n", Color.Yellow);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 windows\QMK Toolbox\KeyTester\KeyTesterWindow.cs (line 198)
195 // If scancode is 0 but marked as extended, switch on VK instead as it's most likely a media key that won't change with keyboard layout anyway
196 if (scanCode == 0x100)
197 {
198 switch (vKey)
199 {
200 case VK_VOLUME_MUTE:
201 return keyMute;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS034 Accessing Task.Result without await 2 hits
📄 windows\QMK Toolbox\Hid\HidConsoleDevice.cs (line 22)
19
20 private void RegisterReportTask()
21 {
22 Task.Run(async () => await ReadReportAsync()).ContinueWith(t => HidDeviceReportEvent(t.Result));
23 }
24
25 private async Task<HidReport> ReadReportAsync()
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 windows\QMK Toolbox\Hid\HidConsoleDevice.cs (line 22)
19
20 private void RegisterReportTask()
21 {
22 Task.Run(async () => await ReadReportAsync()).ContinueWith(t => HidDeviceReportEvent(t.Result));
23 }
24
25 private async Task<HidReport> ReadReportAsync()
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 windows\QMK Toolbox\Usb\UsbListener.cs (line 30)
27
28 private void EnumerateUsbDevices(bool connected)
29 {
30 var enumeratedDevices = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity WHERE DeviceID LIKE 'USB%'").Get()
31 .Cast<ManagementBaseObject>().ToList()
32 .Where(d => (d.GetPropertyValue("HardwareID") as string[])?.Any(s => UsbIdRegex.Match(s).Success) ?? false);
33
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 windows\QMK Toolbox\Usb\UsbListener.cs (line 30)
27
28 private void EnumerateUsbDevices(bool connected)
29 {
30 var enumeratedDevices = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity WHERE DeviceID LIKE 'USB%'").Get()
31 .Cast<ManagementBaseObject>().ToList()
32 .Where(d => (d.GetPropertyValue("HardwareID") as string[])?.Any(s => UsbIdRegex.Match(s).Success) ?? false);
33
💬 ToList is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 windows\QMK Toolbox\MainWindow.cs (line 465)
462 client.DefaultRequestHeaders.UserAgent.ParseAdd("QMK Toolbox");
463
464 var response = await client.GetAsync(url);
465 using (var fs = new FileStream(destFile, FileMode.CreateNew))
466 {
467 await response.Content.CopyToAsync(fs);
468 logTextBox.LogInfo($"File saved to: {destFile}");
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 windows\QMK Toolbox\MainWindow.cs (line 465)
462 client.DefaultRequestHeaders.UserAgent.ParseAdd("QMK Toolbox");
463
464 var response = await client.GetAsync(url);
465 using (var fs = new FileStream(destFile, FileMode.CreateNew))
466 {
467 await response.Content.CopyToAsync(fs);
468 logTextBox.LogInfo($"File saved to: {destFile}");
💬 FileStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 12 hits
📄 windows\QMK Toolbox\Hid\HidConsoleWindow.cs (line 49)
46 #endregion
47
48 #region HID Console
49 private readonly HidListener hidListener = new();
50
51 private HidConsoleDevice lastReportedDevice;
52
💬 Disposable field hidListener in type HidConsoleWindow is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 windows\QMK Toolbox\Hid\HidListener.cs (line 84)
81 consoleReportReceived?.Invoke(device, data);
82 }
83
84 private ManagementEventWatcher deviceConnectedWatcher;
85 private ManagementEventWatcher deviceDisconnectedWatcher;
86
87 private static ManagementEventWatcher CreateManagementEventWatcher(string eventType)
💬 Disposable field deviceConnectedWatcher in type HidListener is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

blazor-starter-kit

50 total diagnostics across 7 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 24 hits
📄 src\Application\Features\Dashboards\Queries\GetData\GetDashboardDataQuery.cs (line 50)
47 RoleCount = await _roleService.GetCountAsync()
48 };
49
50 var selectedYear = DateTime.Now.Year;
51 double[] productsFigure = new double[13];
52 double[] brandsFigure = new double[13];
53 double[] documentsFigure = new double[13];
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Infrastructure\DatabaseSeeder.cs (line 69)
66 UserName = "mukesh",
67 EmailConfirmed = true,
68 PhoneNumberConfirmed = true,
69 CreatedOn = DateTime.Now,
70 IsActive = true
71 };
72 var superUserInDb = await _userManager.FindByEmailAsync(superUser.Email);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 2 hits
📄 src\Infrastructure\Services\UploadService.cs (line 77)
74
75 while (max != min + 1)
76 {
77 int pivot = (max + min) / 2;
78 if (File.Exists(string.Format(pattern, pivot)))
79 min = pivot;
80 else
💬 The operands in the divisive expression (max + min) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\Infrastructure\Services\UploadService.cs (line 77)
74
75 while (max != min + 1)
76 {
77 int pivot = (max + min) / 2;
78 if (File.Exists(string.Format(pattern, pivot)))
79 min = pivot;
80 else
💬 The operands in the divisive expression (max + min) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 6 hits
📄 src\Application\Extensions\ExpressionExtensions.cs (line 28)
25 ParameterExpression p = left.Parameters.First();
26 SubstExpressionVisitor visitor = new SubstExpressionVisitor
27 {
28 Subst = {[right.Parameters.First()] = p}
29 };
30
31 Expression body = Expression.OrElse(left.Body, visitor.Visit(right.Body));
💬 Type Expression is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Application\Extensions\ExpressionExtensions.cs (line 15)
12 ParameterExpression p = left.Parameters.First();
13 SubstExpressionVisitor visitor = new SubstExpressionVisitor
14 {
15 Subst = {[right.Parameters.First()] = p}
16 };
17
18 Expression body = Expression.AndAlso(left.Body, visitor.Visit(right.Body));
💬 Type Expression is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS018 Switch does not handle all enum options 4 hits
📄 src\Infrastructure\Contexts\BlazorHeroContext.cs (line 39)
36 {
37 foreach (var entry in ChangeTracker.Entries<IAuditableEntity>().ToList())
38 {
39 switch (entry.State)
40 {
41 case EntityState.Added:
42 entry.Entity.CreatedOn = _dateTimeService.NowUtc;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 src\Infrastructure\Contexts\AuditableContext.cs (line 60)
57 continue;
58 }
59
60 switch (entry.State)
61 {
62 case EntityState.Added:
63 auditEntry.AuditType = AuditType.Create;
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 10 hits
📄 src\Infrastructure\Contexts\BlazorHeroContext.cs (line 39)
36 {
37 foreach (var entry in ChangeTracker.Entries<IAuditableEntity>().ToList())
38 {
39 switch (entry.State)
40 {
41 case EntityState.Added:
42 entry.Entity.CreatedOn = _dateTimeService.NowUtc;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Infrastructure\Contexts\AuditableContext.cs (line 60)
57 continue;
58 }
59
60 switch (entry.State)
61 {
62 case EntityState.Added:
63 auditEntry.AuditType = AuditType.Create;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS058 String concatenated in a loop 2 hits
📄 src\Client.Infrastructure\Routes\ProductsEndpoints.cs (line 14)
11 {
12 foreach (var orderByPart in orderBy)
13 {
14 url += $"{orderByPart},";
15 }
16 url = url[..^1]; // loose training ,
17 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Client.Infrastructure\Routes\ProductsEndpoints.cs (line 14)
11 {
12 foreach (var orderByPart in orderBy)
13 {
14 url += $"{orderByPart},";
15 }
16 url = url[..^1]; // loose training ,
17 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS066 Disposable field is not disposed 2 hits
📄 src\Client.Infrastructure\Managers\Interceptors\HttpInterceptorManager.cs (line 17)
14 private readonly HttpClientInterceptor _interceptor;
15 private readonly IAuthenticationManager _authenticationManager;
16 private readonly NavigationManager _navigationManager;
17 private readonly ISnackbar _snackBar;
18 private readonly IStringLocalizer<HttpInterceptorManager> _localizer;
19
20 public HttpInterceptorManager(
💬 Disposable field _snackBar in type HttpInterceptorManager is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Client.Infrastructure\Managers\Interceptors\HttpInterceptorManager.cs (line 17)
14 private readonly HttpClientInterceptor _interceptor;
15 private readonly IAuthenticationManager _authenticationManager;
16 private readonly NavigationManager _navigationManager;
17 private readonly ISnackbar _snackBar;
18 private readonly IStringLocalizer<HttpInterceptorManager> _localizer;
19
20 public HttpInterceptorManager(
💬 Disposable field _snackBar in type HttpInterceptorManager is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

GuardClauses

44 total diagnostics across 3 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 38 hits
📄 test\GuardClauses.UnitTests\GuardAgainstDefault.cs (line 16)
13 Guard.Against.Default("", "string");
14 Guard.Against.Default(1, "int");
15 Guard.Against.Default(Guid.NewGuid(), "guid");
16 Guard.Against.Default(DateTime.Now, "datetime");
17 Guard.Against.Default(new Object(), "object");
18 }
19
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 test\GuardClauses.UnitTests\GuardAgainstOutOfRangeForDateTime.cs (line 16)
13 [InlineData(-1, 0)]
14 public void DoesNothingGivenInRangeValue(int rangeFromOffset, int rangeToOffset)
15 {
16 DateTime input = DateTime.Now;
17 DateTime rangeFrom = input.AddSeconds(rangeFromOffset);
18 DateTime rangeTo = input.AddSeconds(rangeToOffset);
19 Guard.Against.OutOfRange(input, "index", rangeFrom, rangeTo);
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 test\GuardClauses.UnitTests\GuardAgainstExpression.cs (line 10)
7
8public class GuardAgainstExpression
9{
10 public struct CustomStruct
11 {
12 public string FieldName { get; set; }
13 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CustomStruct. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 test\GuardClauses.UnitTests\GuardAgainstExpressionDeprecated.cs (line 13)
10/// </summary>
11public class GuardAgainstExpressionDeprecated
12{
13 public struct CustomStruct
14 {
15 public string FieldName { get; set; }
16 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct CustomStruct. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS049 Comparing strings without StringComparison 2 hits
📄 test\GuardClauses.UnitTests\NamespaceSeparate\ExtendingGuard.cs (line 18)
15 public static void Foo(this IGuardClause guardClause, string input, [CallerArgumentExpression("input")] string? parameterName = null)
16#endif
17 {
18 if (input?.ToLower() == "foo")
19 throw new ArgumentException("Should not have been foo!", parameterName);
20 }
21}
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 test\GuardClauses.UnitTests\NamespaceSeparate\ExtendingGuard.cs (line 18)
15 public static void Foo(this IGuardClause guardClause, string input, [CallerArgumentExpression("input")] string? parameterName = null)
16#endif
17 {
18 if (input?.ToLower() == "foo")
19 throw new ArgumentException("Should not have been foo!", parameterName);
20 }
21}
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)

DotNetGuide

44 total diagnostics across 6 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 10 hits
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\LinqExercise.cs (line 187)
Source context not available
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\LinqExercise.cs (line 191)
Source context not available
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 20 hits
📄 DotNetGuidePractice\HelloDotNetGuide\Õ©©Þºüþ«ùµ│ò\õ║îÕê嵃ѵë¥þ«ùµ│ò.cs (line 19)
Source context not available
💬 The operands in the divisive expression (right - left) / 2 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 DotNetGuidePractice\HelloDotNetGuide\Õ©©Þºüþ«ùµ│ò\Õƒ║µò░µÄÆÕ║Åþ«ùµ│ò.cs (line 16)
Source context not available
💬 The operands in the divisive expression max / exp are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\LinqExercise.cs (line 324)
Source context not available
💬 Type StudentInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\LinqExercise.cs (line 324)
Source context not available
💬 Type StudentInfo is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS009 Random instantiated in a loop 4 hits
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\GotoExercise.cs (line 17)
Source context not available
💬 Variable random of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\GotoExercise.cs (line 57)
Source context not available
💬 Variable random of type System.Random is instantiated in a loop. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS009-LoopedRandomInstantiation.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\CSharp12GrammarExercise.cs (line 84)
Source context not available
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Distance. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\CSharp12GrammarExercise.cs (line 99)
Source context not available
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Buffer. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS051 Locking on mutable reference 4 hits
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\CSharp13GrammarExercise.cs (line 32)
Source context not available
💬 A lock was obtained on _oldLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 DotNetGuidePractice\HelloDotNetGuide\CSharpÞ»¡µ│ò\CSharp13GrammarExercise.cs (line 38)
Source context not available
💬 A lock was obtained on _newLock but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)

Telegram.Bot

42 total diagnostics across 6 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 test\Telegram.Bot.Tests.Integ\Games\GamesFixture.cs (line 57)
54 static async Task<User> GetPlayerIdFromChatAdmins(TestsFixture testsFixture, long chatId)
55 {
56 ChatMember[] admins = await testsFixture.BotClient.GetChatAdministrators(chatId);
57 ChatMember player = admins[new Random(DateTime.Now.Millisecond).Next(admins.Length)];
58 return player.User;
59 }
60}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 test\Telegram.Bot.Tests.Integ\Games\GamesFixture.cs (line 57)
54 static async Task<User> GetPlayerIdFromChatAdmins(TestsFixture testsFixture, long chatId)
55 {
56 ChatMember[] admins = await testsFixture.BotClient.GetChatAdministrators(chatId);
57 ChatMember player = admins[new Random(DateTime.Now.Millisecond).Next(admins.Length)];
58 return player.User;
59 }
60}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS019 Switch is missing default label 12 hits
📄 src\Telegram.Bot\Extensions\FormatExtensions.cs (line 196)
193 sb.Insert(i, tag); i += tag.Length;
194 }
195 }
196 switch (sb[i])
197 {
198 case '&': sb.Insert(i + 1, "amp;"); i += 4; break;
199 case '<': sb.Insert(i, "&lt"); sb[i += 3] = ';'; break;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Telegram.Bot\Extensions\FormatExtensions.cs (line 77)
74 sb.Insert(i, md); i += md.Length;
75 }
76 }
77 switch (lastCh = sb[i])
78 {
79 case '_': case '*': case '~': case '#': case '+': case '-': case '=': case '.': case '!':
80 case '[': case ']': case '(': case ')': case '{': case '}': case '>': case '|': case '\\':
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 8 hits
📄 test\Telegram.Bot.Tests.Unit\Polling\ReceiveAsyncTests.cs (line 27)
24 await Task.Delay(10, cancellationTokenSource.Token);
25 if (update.Message.Text is "end")
26 {
27 cancellationTokenSource.Cancel();
28 }
29 }
30
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 test\Telegram.Bot.Tests.Unit\Polling\ReceiveAsyncTests.cs (line 65)
62 await Task.Delay(10, cancellationTokenSource.Token);
63 if (update.Message.Text is "end")
64 {
65 globalCancelToken.Cancel();
66 }
67 }
68
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS058 String concatenated in a loop 4 hits
📄 src\Telegram.Bot\Extensions\FormatExtensions.cs (line 64)
61 else if (nextEntity.Type is MessageEntityType.DateTime)
62 {
63 closing.md = string.IsNullOrEmpty(nextEntity.DateTimeFormat) ? "" : $"&format={nextEntity.DateTimeFormat}";
64 closing.md = $"](tg://time?unix={((DateTimeOffset)nextEntity.UnixTime!).ToUnixTimeSeconds()}{closing.md})";
65 }
66 }
67 else if (md[0] == '>')
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 src\Telegram.Bot\Extensions\FormatExtensions.cs (line 64)
61 else if (nextEntity.Type is MessageEntityType.DateTime)
62 {
63 closing.md = string.IsNullOrEmpty(nextEntity.DateTimeFormat) ? "" : $"&format={nextEntity.DateTimeFormat}";
64 closing.md = $"](tg://time?unix={((DateTimeOffset)nextEntity.UnixTime!).ToUnixTimeSeconds()}{closing.md})";
65 }
66 }
67 else if (md[0] == '>')
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
SS059 IAsyncDisposable not disposed asynchronously 10 hits
📄 src\Telegram.Bot\ITelegramBotClient.cs (line 97)
94 if (passportFile == null) throw new ArgumentNullException(nameof(passportFile));
95 if (fileCredentials == null) throw new ArgumentNullException(nameof(fileCredentials));
96 if (destination == null) throw new ArgumentNullException(nameof(destination));
97 using var encryptedContentStream = passportFile.FileSize > 0 ? new MemoryStream((int)passportFile.FileSize) : new MemoryStream();
98 var fileInfo = await botClient.ThrowIfNull().GetInfoAndDownloadFile(passportFile.FileId, encryptedContentStream, cancellationToken).ConfigureAwait(false);
99 encryptedContentStream.Position = 0;
100 await new Passport.Decrypter().DecryptFileAsync(encryptedContentStream, fileCredentials, destination, cancellationToken).ConfigureAwait(false);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Telegram.Bot\PassportDecrypter.cs (line 154)
151 aes.Padding = PaddingMode.None;
152
153 using var decrypter = aes.CreateDecryptor();
154 using CryptoStream aesStream = new CryptoStream(data, decrypter, CryptoStreamMode.Read);
155 using var sha256 = SHA256.Create();
156 using CryptoStream shaStream = new CryptoStream(aesStream, sha256, CryptoStreamMode.Read);
157 byte[] paddingBuffer = new byte[256];
💬 CryptoStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 6 hits
📄 test\Telegram.Bot.Tests.Integ\Framework\TestsFixture.cs (line 22)
19public class TestsFixture : IDisposable
20{
21 readonly IMessageSink _diagnosticMessageSink;
22 ConfigurationProvider _configurationProvider;
23
24 public TestConfiguration Configuration => _configurationProvider.Configuration;
25
💬 Disposable field _configurationProvider in type TestsFixture is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 test\Telegram.Bot.Tests.Integ\Admin Bot\SupergroupAdminBotTestsFixture.cs (line 14)
11 byte[] _oldChatPhoto;
12 ChatPermissions _existingDefaultPermissions;
13
14 public TestsFixture TestsFixture { get; }
15 public ChatFullInfo Chat => TestsFixture.SupergroupChat;
16 public List<Message> PinnedMessages { get; }
17 public ChatInviteLink ChatInviteLink { get; set; }
💬 Disposable field TestsFixture in type SupergroupAdminBotTestsFixture is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

opentrace

40 total diagnostics across 4 rules

SS001 Async method with void return type 2 hits
📄 UI\MainForm.cs (line 92)
89 }
90 }
91
92 private async void CheckUpdateAsync()
93 {
94 string currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
95 string latestVersion = await updateService.CheckForUpdateAsync(currentVersion);
💬 Method CheckUpdateAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 UI\MainForm.cs (line 92)
89 }
90 }
91
92 private async void CheckUpdateAsync()
93 {
94 string currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
95 string latestVersion = await updateService.CheckForUpdateAsync(currentVersion);
💬 Method CheckUpdateAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS033 Async overload is available 2 hits
📄 UI\MainForm.cs (line 98)
95 string latestVersion = await updateService.CheckForUpdateAsync(currentVersion);
96 if (latestVersion != null)
97 {
98 App.app.Invoke(() =>
99 {
100 App.app.MainForm.Title += " " + string.Format(Resources.UPDATE_AVAILABLE, latestVersion);
101 });
💬 Async overload available for Application.Invoke (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 UI\MainForm.cs (line 98)
95 string latestVersion = await updateService.CheckForUpdateAsync(currentVersion);
96 if (latestVersion != null)
97 {
98 App.app.Invoke(() =>
99 {
100 App.app.MainForm.Title += " " + string.Format(Resources.UPDATE_AVAILABLE, latestVersion);
101 });
💬 Async overload available for Application.Invoke (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 8 hits
📄 Services\DnsResolverService.cs (line 52)
49 IDnsClient dnsClient = new DnsHttpClient(httpClient);
50
51 // 同时查询 A 和 AAAA 记录
52 DnsMessage aResult = Task.Run(() => dnsClient.Query(DnsQueryFactory.CreateQuery(host, Ae.Dns.Protocol.Enums.DnsQueryType.A))).Result;
53 DnsMessage aaaaResult = Task.Run(() => dnsClient.Query(DnsQueryFactory.CreateQuery(host, Ae.Dns.Protocol.Enums.DnsQueryType.AAAA))).Result;
54
55 if (aResult.Answers.Count == 0 && aaaaResult.Answers.Count == 0)
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Services\DnsResolverService.cs (line 53)
50
51 // 同时查询 A 和 AAAA 记录
52 DnsMessage aResult = Task.Run(() => dnsClient.Query(DnsQueryFactory.CreateQuery(host, Ae.Dns.Protocol.Enums.DnsQueryType.A))).Result;
53 DnsMessage aaaaResult = Task.Run(() => dnsClient.Query(DnsQueryFactory.CreateQuery(host, Ae.Dns.Protocol.Enums.DnsQueryType.AAAA))).Result;
54
55 if (aResult.Answers.Count == 0 && aaaaResult.Answers.Count == 0)
56 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS066 Disposable field is not disposed 28 hits
📄 UI\Dialogs\PreferencesDialog.xeto.cs (line 22)
19 public partial class PreferencesDialog : Dialog
20 {
21 private ObservableCollection<TracerouteResult> tracerouteResultCollection = new ObservableCollection<TracerouteResult>();
22 private TextOutputForm textOutputForm = new TextOutputForm();
23 private static NextTraceWrapper CurrentInstance { get; set; }
24 UserSettings userSettings = new UserSettings();
25 public PreferencesDialog()
💬 Disposable field textOutputForm in type PreferencesDialog is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 UI\Forms\ExceptionalOutputForm.xeto.cs (line 11)
8{
9 public partial class ExceptionalOutputForm : Form
10 {
11 private TextArea OutputContainer;
12 public ExceptionalOutputForm()
13 {
14 XamlReader.Load(this);
💬 Disposable field OutputContainer in type ExceptionalOutputForm is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

SymSpell

36 total diagnostics across 5 rules

SS003 Integer divided by integer causing implicit rounding 14 hits
📄 SymSpell\SymSpell.cs (line 801)
798 public int Count { get; private set; }
799 public ChunkArray(int initialCapacity)
800 {
801 int chunks = (initialCapacity + ChunkSize - 1) / ChunkSize;
802 Values = new T[chunks][];
803 for (int i = 0; i < Values.Length; i++) Values[i] = new T[ChunkSize];
804 }
💬 The operands in the divisive expression (initialCapacity + ChunkSize - 1) / ChunkSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 SymSpell\SymSpell.cs (line 801)
798 public int Count { get; private set; }
799 public ChunkArray(int initialCapacity)
800 {
801 int chunks = (initialCapacity + ChunkSize - 1) / ChunkSize;
802 Values = new T[chunks][];
803 for (int i = 0; i < Values.Length; i++) Values[i] = new T[ChunkSize];
804 }
💬 The operands in the divisive expression (initialCapacity + ChunkSize - 1) / ChunkSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 6 hits
📄 SymSpell\SymSpell.cs (line 110)
107
108 public override int GetHashCode()
109 {
110 return term.GetHashCode();
111 }
112 public override string ToString()
113 {
💬 GetHashCode() refers to mutable field term (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 SymSpell\SymSpell.cs (line 110)
107
108 public override int GetHashCode()
109 {
110 return term.GetHashCode();
111 }
112 public override string ToString()
113 {
💬 GetHashCode() refers to mutable field term (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 8 hits
📄 SymSpell\SymSpell.cs (line 639)
636 public string suggestion;
637 public int next;
638 }
639 private struct Entry
640 {
641 public int count;
642 public int first;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Entry. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 SymSpell\SymSpell.cs (line 634)
631 /// of time can be achieved, as well as a reduction in final memory usage.</summary>
632 public class SuggestionStage
633 {
634 private struct Node
635 {
636 public string suggestion;
637 public int next;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Node. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS018 Switch does not handle all enum options 4 hits
📄 SymSpell\SymSpell.cs (line 578)
575 SuggestItem si = new SuggestItem(suggestion, distance, suggestionCount);
576 if (suggestions.Count > 0)
577 {
578 switch (verbosity)
579 {
580 case Verbosity.Closest:
581 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 SymSpell\SymSpell.cs (line 578)
575 SuggestItem si = new SuggestItem(suggestion, distance, suggestionCount);
576 if (suggestions.Count > 0)
577 {
578 switch (verbosity)
579 {
580 case Verbosity.Closest:
581 {
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 4 hits
📄 SymSpell\SymSpell.cs (line 578)
575 SuggestItem si = new SuggestItem(suggestion, distance, suggestionCount);
576 if (suggestions.Count > 0)
577 {
578 switch (verbosity)
579 {
580 case Verbosity.Closest:
581 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 SymSpell\SymSpell.cs (line 578)
575 SuggestItem si = new SuggestItem(suggestion, distance, suggestionCount);
576 if (suggestions.Count > 0)
577 {
578 switch (verbosity)
579 {
580 case Verbosity.Closest:
581 {
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)

dotnet-script

36 total diagnostics across 5 rules

SS008 GetHashCode() refers to mutable or static member 10 hits
📄 src\Dotnet.Script.DependencyModel.Nuget\NuGetMetadataReferenceResolver.cs (line 32)
29
30 public override int GetHashCode()
31 {
32 return _metadataReferenceResolver.GetHashCode();
33 }
34
35 public override bool ResolveMissingAssemblies => _metadataReferenceResolver.ResolveMissingAssemblies;
💬 GetHashCode() refers to mutable field _metadataReferenceResolver (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Dotnet.Script.DependencyModel.Nuget\NuGetSourceReferenceResolver.cs (line 34)
31
32 public override int GetHashCode()
33 {
34 return _sourceReferenceResolver.GetHashCode();
35 }
36
37 public override string NormalizePath(string path, string baseFilePath)
💬 GetHashCode() refers to mutable field _sourceReferenceResolver (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS033 Async overload is available 8 hits
📄 src\Dotnet.Script.Core\Interactive\InteractiveRunner.cs (line 46)
43 {
44 while (!_shouldExit)
45 {
46 Console.Out.Write("> ");
47 var input = ReadInput();
48
49 if (InteractiveCommandParser.TryProvideCommand(input, out var command))
💬 Async overload available for TextWriter.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Dotnet.Script.Core\Interactive\InteractiveRunner.cs (line 46)
43 {
44 while (!_shouldExit)
45 {
46 Console.Out.Write("> ");
47 var input = ReadInput();
48
49 if (InteractiveCommandParser.TryProvideCommand(input, out var command))
💬 Async overload available for TextWriter.Write (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 4 hits
📄 src\Dotnet.Script.Extras\RemoteFileResolver.cs (line 51)
48 if (uri == null) return _fileBasedResolver.ResolveReference(path, baseFilePath);
49
50 var client = new HttpClient();
51 var response = client.GetAsync(path).Result;
52
53 if (response.IsSuccessStatusCode)
54 _remoteFiles[path] = response.Content.ReadAsByteArrayAsync().Result;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Dotnet.Script.Extras\RemoteFileResolver.cs (line 54)
51 var response = client.GetAsync(path).Result;
52
53 if (response.IsSuccessStatusCode)
54 _remoteFiles[path] = response.Content.ReadAsByteArrayAsync().Result;
55
56 return path;
57 }
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS049 Comparing strings without StringComparison 2 hits
📄 src\Dotnet.Script.DependencyModel\ScriptPackage\ScriptFilesDependencyResolver.cs (line 78)
75
76 if (rootfiles.Length > 1)
77 {
78 return rootfiles.SingleOrDefault(rf => rf.ToLower() == "main.csx");
79 }
80
81 return null;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
📄 src\Dotnet.Script.DependencyModel\ScriptPackage\ScriptFilesDependencyResolver.cs (line 78)
75
76 if (rootfiles.Length > 1)
77 {
78 return rootfiles.SingleOrDefault(rf => rf.ToLower() == "main.csx");
79 }
80
81 return null;
💬 A string is being compared through allocating a new string. Use a case-insensitive comparison instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md)
SS059 IAsyncDisposable not disposed asynchronously 12 hits
📄 src\Dotnet.Script.Core\ScriptDownloader.cs (line 33)
30 return await content.ReadAsStringAsync();
31 case "application/gzip":
32 case "application/x-gzip":
33 using (var stream = await content.ReadAsStreamAsync())
34 using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
35 using (var reader = new StreamReader(gzip))
36 return await reader.ReadToEndAsync();
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\Dotnet.Script.Core\ScriptDownloader.cs (line 34)
31 case "application/gzip":
32 case "application/x-gzip":
33 using (var stream = await content.ReadAsStreamAsync())
34 using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
35 using (var reader = new StreamReader(gzip))
36 return await reader.ReadToEndAsync();
37 default:
💬 GZipStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)

RunCat365

36 total diagnostics across 3 rules

SS017 Struct without Equals/GetHashCode/ToString overridden 16 hits
📄 RunCat365\BalloonTipType.cs (line 19)
16
17namespace RunCat365
18{
19 internal readonly struct BalloonTipInfo(string title, string text, ToolTipIcon icon)
20 {
21 internal string Title { get; } = title;
22 internal string Text { get; } = text;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct BalloonTipInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 RunCat365\MemoryRepository.cs (line 20)
17
18namespace RunCat365
19{
20 struct MemoryInfo
21 {
22 internal uint MemoryLoad { get; set; }
23 internal long TotalMemory { get; set; }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct MemoryInfo. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS034 Accessing Task.Result without await 6 hits
📄 RunCat365\LaunchAtStartupManager.cs (line 32)
29
30 public bool GetEnabled()
31 {
32 startupTask ??= Task.Run(async () => await StartupTask.GetAsync("RunCatStartup")).Result;
33 if (startupTask is null) return false;
34 if (startupTask.State == StartupTaskState.Enabled) return true;
35 return false;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 RunCat365\LaunchAtStartupManager.cs (line 40)
37
38 public bool SetEnabled(bool enabled)
39 {
40 startupTask ??= Task.Run(async () => await StartupTask.GetAsync("RunCatStartup")).Result;
41 if (enabled)
42 {
43 if (startupTask.State == StartupTaskState.Enabled) startupTask.Disable();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS066 Disposable field is not disposed 14 hits
📄 RunCat365\EndlessGameForm.cs (line 26)
23 internal class EndlessGameForm : Form
24 {
25 private const int JUMP_THREDHOLD = 17;
26 private readonly FormsTimer timer;
27 private readonly Theme systemTheme;
28 private GameStatus status = GameStatus.NewGame;
29 private Cat cat = new Cat.Running(Cat.Running.Frame.Frame0);
💬 Disposable field timer in type EndlessGameForm is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 RunCat365\ContextMenuManager.cs (line 22)
19{
20 internal class ContextMenuManager : IDisposable
21 {
22 private readonly CustomToolStripMenuItem systemInfoMenu = new();
23 private readonly NotifyIcon notifyIcon = new();
24 private readonly List<Icon> icons = [];
25 private readonly Lock iconLock = new();
💬 Disposable field systemInfoMenu in type ContextMenuManager is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Steam-auto-crack

34 total diagnostics across 3 rules

SS003 Integer divided by integer causing implicit rounding 4 hits
📄 Steamless.API\PE64\Pe64File.cs (line 369)
366 /// <returns></returns>
367 public ulong GetAlignment(ulong val, ulong align)
368 {
369 return (((val + align - 1) / align) * align);
370 }
371
372 /// <summary>
💬 The operands in the divisive expression (val + align - 1) / align are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Steamless.API\PE32\Pe32File.cs (line 366)
363 /// <returns></returns>
364 public uint GetAlignment(uint val, uint align)
365 {
366 return (((val + align - 1) / align) * align);
367 }
368
369 /// <summary>
💬 The operands in the divisive expression (val + align - 1) / align are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 28 hits
📄 Steamless.API\PE64\NativeApi64.cs (line 37)
34 /// IMAGE_DOS_HEADER Structure
35 /// </summary>
36 [StructLayout(LayoutKind.Sequential)]
37 public struct ImageDosHeader64
38 {
39 public ushort e_magic;
40 public ushort e_cblp;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ImageDosHeader64. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Steamless.API\PE32\NativeApi32.cs (line 37)
34 /// IMAGE_DOS_HEADER Structure
35 /// </summary>
36 [StructLayout(LayoutKind.Sequential)]
37 public struct ImageDosHeader32
38 {
39 public ushort e_magic;
40 public ushort e_cblp;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ImageDosHeader32. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS066 Disposable field is not disposed 2 hits
📄 Steamless.API\Crypto\AesHelper.cs (line 48)
45 /// <summary>
46 /// Internal AES crypto provider.
47 /// </summary>
48 private Aes m_AesCryptoProvider = Aes.Create();
49
50 /// <summary>
51 /// Default Constructor
💬 Disposable field m_AesCryptoProvider in type AesHelper is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Steamless.API\Crypto\AesHelper.cs (line 48)
45 /// <summary>
46 /// Internal AES crypto provider.
47 /// </summary>
48 private Aes m_AesCryptoProvider = Aes.Create();
49
50 /// <summary>
51 /// Default Constructor
💬 Disposable field m_AesCryptoProvider in type AesHelper is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

NSubstitute

32 total diagnostics across 3 rules

SS004 Elementary methods of type in collection not overridden 8 hits
No source samples extracted
SS015 String placeholders in wrong order 4 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 20 hits
No source samples extracted

app

32 total diagnostics across 4 rules

SS003 Integer divided by integer causing implicit rounding 12 hits
📄 Stratum.Core\src\Generator\Totp.cs (line 25)
22
23 public static byte[] GetCounterBytes(long counter, int period)
24 {
25 var window = counter / period;
26 var bytes = new byte[sizeof(long)];
27 BinaryPrimitives.WriteInt64BigEndian(bytes, window);
28 return bytes;
💬 The operands in the divisive expression counter / period are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 Stratum.Core\src\Generator\MobileOtp.cs (line 26)
23
24 public string Compute(long counter)
25 {
26 var timestamp = counter / 10;
27
28 var builder = new StringBuilder();
29 builder.Append(timestamp);
💬 The operands in the divisive expression counter / 10 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS019 Switch is missing default label 10 hits
📄 Stratum.Core\src\Entity\Authenticator.cs (line 87)
84 _ => throw new ArgumentException("Unknown authenticator type")
85 };
86
87 switch (Type.GetGenerationMethod())
88 {
89 case GenerationMethod.Time:
90 _code = _generator.Compute(counter);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Stratum.Core\src\JvmStringDecoder.cs (line 43)
40
41 var width = GetUtf8CharacterWidth(b);
42
43 switch (width)
44 {
45 // 1 byte and 2 byte characters are the same as UTF-8
46 case 1:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS059 IAsyncDisposable not disposed asynchronously 6 hits
📄 Stratum.Core\src\Converter\WinAuthBackupConverter.cs (line 29)
26 return await base.ConvertAsync(data);
27 }
28
29 using var inputMemory = new MemoryStream(data);
30 using var zip = new ZipFile(inputMemory);
31 zip.Password = password;
32
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Stratum.Core\src\Converter\WinAuthBackupConverter.cs (line 40)
37 throw new ArgumentException("No file found in zip");
38 }
39
40 using var outputMemory = new MemoryStream();
41
42 try
43 {
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 4 hits
📄 Stratum.Core\src\Generator\YandexOtp.cs (line 19)
16 public const int SecretByteCount = 16;
17 private const int Period = 30;
18
19 private readonly HMAC _hmac;
20 private bool _isDisposed;
21
22 public YandexOtp(string secret, string pin)
💬 Disposable field _hmac in type YandexOtp is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Stratum.Core\src\Generator\HmacOtp.cs (line 13)
10{
11 public abstract class HmacOtp : IDisposable
12 {
13 private readonly HMAC _hmac;
14 private readonly int _digits;
15 private bool _isDisposed;
16
💬 Disposable field _hmac in type HmacOtp is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Scrutor

32 total diagnostics across 2 rules

SS004 Elementary methods of type in collection not overridden 8 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 24 hits
No source samples extracted

ApiEndpoints

30 total diagnostics across 6 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 sample\Sample.WeatherForecast\Endpoints\Get.cs (line 33)
30 {
31 return Enumerable.Range(1, 5).Select(index => new WeatherForecast
32 {
33 Date = DateTime.Now.AddDays(index),
34 TemperatureC = Random.Shared.Next(-20, 55),
35 Summary = Summaries[Random.Shared.Next(Summaries.Length)]
36 })
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 sample\Sample.WeatherForecast\Endpoints\Get.cs (line 33)
30 {
31 return Enumerable.Range(1, 5).Select(index => new WeatherForecast
32 {
33 Date = DateTime.Now.AddDays(index),
34 TemperatureC = Random.Shared.Next(-20, 55),
35 Summary = Summaries[Random.Shared.Next(Summaries.Length)]
36 })
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 tests\Ardalis.ApiEndpoints.CodeAnalyzers.Test\Helpers\DiagnosticVerifier.Helper.cs (line 53)
50 var projects = new HashSet<Project>();
51 foreach (var document in documents)
52 {
53 projects.Add(document.Project);
54 }
55
56 var diagnostics = new List<Diagnostic>();
💬 Type Project is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 tests\Ardalis.ApiEndpoints.CodeAnalyzers.Test\Helpers\DiagnosticVerifier.Helper.cs (line 53)
50 var projects = new HashSet<Project>();
51 foreach (var document in documents)
52 {
53 projects.Add(document.Project);
54 }
55
56 var diagnostics = new List<Diagnostic>();
💬 Type Project is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 tests\Ardalis.ApiEndpoints.CodeAnalyzers.Test\Helpers\DiagnosticResult.cs (line 10)
7/// <summary>
8/// Location where the diagnostic appears, as determined by path, line number, and column number.
9/// </summary>
10public struct DiagnosticResultLocation
11{
12 public DiagnosticResultLocation(string path, int line, int column)
13 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DiagnosticResultLocation. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 tests\Ardalis.ApiEndpoints.CodeAnalyzers.Test\Helpers\DiagnosticResult.cs (line 37)
34/// <summary>
35/// Struct that stores information about a Diagnostic appearing in a source
36/// </summary>
37public struct DiagnosticResult
38{
39 private DiagnosticResultLocation[] locations;
40
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DiagnosticResult. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS033 Async overload is available 2 hits
📄 sample\Sample.WeatherForecast\Program.cs (line 24)
21
22app.MapControllers();
23
24app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 sample\Sample.WeatherForecast\Program.cs (line 24)
21
22app.MapControllers();
23
24app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 18 hits
📄 tests\Ardalis.ApiEndpoints.CodeAnalyzers.Test\Helpers\CodeFixVerifier.Helper.cs (line 25)
22 /// <returns>A Document with the changes from the CodeAction</returns>
23 private static Document ApplyFix(Document document, CodeAction codeAction)
24 {
25 var operations = codeAction.GetOperationsAsync(CancellationToken.None).Result;
26 var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution;
27 return solution.GetDocument(document.Id);
28 }
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 tests\Ardalis.ApiEndpoints.CodeAnalyzers.Test\Helpers\DiagnosticVerifier.Helper.cs (line 59)
56 var diagnostics = new List<Diagnostic>();
57 foreach (var project in projects)
58 {
59 var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
60 var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
61 foreach (var diag in diags)
62 {
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS044 Attribute must specify [AttributeUsage] 2 hits
📄 sample\SampleEndpointApp\FromMultiSourceAttribute.cs (line 5)
2
3namespace SampleEndpointApp;
4
5public sealed class FromMultiSourceAttribute : Attribute, IBindingSourceMetadata
6{
7 public BindingSource BindingSource { get; } = CompositeBindingSource.Create(
8 new[] { BindingSource.Path, BindingSource.Query },
💬 FromMultiSourceAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 sample\SampleEndpointApp\FromMultiSourceAttribute.cs (line 5)
2
3namespace SampleEndpointApp;
4
5public sealed class FromMultiSourceAttribute : Attribute, IBindingSourceMetadata
6{
7 public BindingSource BindingSource { get; } = CompositeBindingSource.Create(
8 new[] { BindingSource.Path, BindingSource.Query },
💬 FromMultiSourceAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)

N_m3u8DL-RE

30 total diagnostics across 4 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 src\N_m3u8DL-RE.Common\Log\Logger.cs (line 70)
67
68 private static string GetCurrTime()
69 {
70 return DateTime.Now.ToString("HH:mm:ss.fff");
71 }
72
73 private static void HandleLog(string write, string subWrite = "")
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\N_m3u8DL-RE.Common\Log\Logger.cs (line 42)
39 Directory.CreateDirectory(logDir);
40 }
41
42 var now = DateTime.Now;
43 if (string.IsNullOrEmpty(LogFilePath))
44 {
45 LogFilePath = Path.Combine(logDir, now.ToString("yyyy-MM-dd_HH-mm-ss-fff") + ".log");
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS003 Integer divided by integer causing implicit rounding 4 hits
📄 src\N_m3u8DL-RE.Common\Util\BinaryContentCheckUtil.cs (line 78)
75 const int packetSize = 188;
76 if (buffer.Length < packetSize) return false;
77 int syncCount = 0;
78 for (int i = 0; i < Math.Min(buffer.Length / packetSize, 5); i++)
79 {
80 if (buffer[i * packetSize] == 0x47) syncCount++;
81 }
💬 The operands in the divisive expression buffer.Length / packetSize are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\N_m3u8DL-RE.Common\Entity\WebVttSub.cs (line 168)
165 if ((this.Cues.Count > 0 && sub.Cues.Count > 0 && sub.Cues.First().StartTime < this.Cues.Last().EndTime && sub.Cues.First().EndTime != this.Cues.Last().EndTime) || this.Cues.Count == 0)
166 {
167 // The MPEG2 transport stream clocks (PCR, PTS, DTS) all have units of 1/90000 second
168 var seconds = (sub.MpegtsTimestamp - baseTimestamp) / 90000;
169 var offset = TimeSpan.FromSeconds(seconds);
170 // 当前预添加的字幕的起始时间小于实际上已经走过的时间(如offset已经是100秒,而字幕起始却是2秒),才修复
171 if (sub.Cues.Count > 0 && sub.Cues.First().StartTime < offset)
💬 The operands in the divisive expression (sub.MpegtsTimestamp - baseTimestamp) / 90000 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 20 hits
📄 src\N_m3u8DL-RE.Common\Entity\SubCue.cs (line 21)
18
19 public override int GetHashCode()
20 {
21 return HashCode.Combine(StartTime, EndTime, Payload, Settings);
22 }
23}
💬 GetHashCode() refers to mutable property StartTime (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\N_m3u8DL-RE.Common\Entity\SubCue.cs (line 21)
18
19 public override int GetHashCode()
20 {
21 return HashCode.Combine(StartTime, EndTime, Payload, Settings);
22 }
23}
💬 GetHashCode() refers to mutable property EndTime (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS059 IAsyncDisposable not disposed asynchronously 2 hits
📄 src\N_m3u8DL-RE.Common\Util\HTTPUtil.cs (line 145)
142 }
143
144 // 否则是文本,完整读取
145 using var ms = new MemoryStream();
146 ms.Write(buffer, 0, bytesRead);
147 await responseStream.CopyToAsync(ms);
148
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\N_m3u8DL-RE.Common\Util\HTTPUtil.cs (line 145)
142 }
143
144 // 否则是文本,完整读取
145 using var ms = new MemoryStream();
146 ms.Write(buffer, 0, bytesRead);
147 await responseStream.CopyToAsync(ms);
148
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)

coravel

28 total diagnostics across 6 rules

SS001 Async method with void return type 2 hits
📄 Src\Coravel\Scheduling\HostedService\SchedulerHost.cs (line 50)
47 this._timer = new Timer(this.RunSchedulerPerSecondAsync, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
48 }
49
50 private async void RunSchedulerPerSecondAsync(object state)
51 {
52 if (this._schedulerEnabled)
53 {
💬 Method RunSchedulerPerSecondAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Src\Coravel\Scheduling\HostedService\SchedulerHost.cs (line 50)
47 this._timer = new Timer(this.RunSchedulerPerSecondAsync, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
48 }
49
50 private async void RunSchedulerPerSecondAsync(object state)
51 {
52 if (this._schedulerEnabled)
53 {
💬 Method RunSchedulerPerSecondAsync is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 Src\Coravel.Cli\Commands\InstallCoravelCommand.cs (line 6)
3
4namespace Coravel.Cli.Commands
5{
6 public struct InstallCoravelCommand
7 {
8 public void Execute()
9 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct InstallCoravelCommand. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 Src\Coravel\Events\Dispatcher.cs (line 83)
80 /// <summary>
81 /// Represents an event subscription.
82 /// </summary>
83 public struct EventSubscription<TEvent> : IEventSubscription<TEvent> where TEvent : IEvent
84 {
85 private List<Type> _listeners;
86
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EventSubscription. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS033 Async overload is available 4 hits
📄 Src\UnitTests\CoravelUnitTests\Queuing\CancellableInvocableForQueueTests.cs (line 28)
25 var (_, token2) = queue.QueueCancellableInvocable<TestCancellableInvocable>();
26 var (_, token3) = queue.QueueCancellableInvocable<TestCancellableInvocable>();
27
28 token1.Cancel();
29 token3.Cancel();
30
31 TestCancellableInvocable.TokensCancelled = 0;
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Src\UnitTests\CoravelUnitTests\Queuing\CancellableInvocableForQueueTests.cs (line 29)
26 var (_, token3) = queue.QueueCancellableInvocable<TestCancellableInvocable>();
27
28 token1.Cancel();
29 token3.Cancel();
30
31 TestCancellableInvocable.TokensCancelled = 0;
32 await queue.ConsumeQueueAsync();
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS051 Locking on mutable reference 4 hits
📄 Src\Coravel\Scheduling\Schedule\Scheduler.cs (line 112)
109 bool isFirstTick = false;
110 if(this._isFirstTick)
111 {
112 lock(this._isFirstTickLockObj)
113 {
114 // Set to `this._isFirstTick` not `true` because there might be multiple threads coming into
115 // this critical section - but only one should count as "the first run".
💬 A lock was obtained on _isFirstTickLockObj but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
📄 Src\Coravel\Scheduling\HostedService\SchedulerHost.cs (line 59)
56 // miss a tick - which we want to make sure the scheduler doesn't miss and catches up.
57 var now = DateTime.UtcNow;
58 DateTime[] ticks = null;
59 lock (_tickLockObj)
60 {
61 // This class isn't thread-safe.
62 ticks = this._ensureContinuousSecondTicks.GetTicksBetweenPreviousAndNext(now).ToArray();
💬 A lock was obtained on _tickLockObj but the field is mutable. This can lead to deadlocks when a new value is assigned. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS051-LockingOnMutableReference.md)
SS059 IAsyncDisposable not disposed asynchronously 6 hits
📄 Src\Coravel\Scheduling\Schedule\Scheduler.cs (line 163)
160
161 private async Task InvokeEventWithLoggerScope(ScheduledEvent scheduledEvent)
162 {
163 using var scope = this._scopeFactory.CreateAsyncScope();
164 ILogger<IScheduler> logger = null;
165
166 if(this._shouldLogProgress)
💬 AsyncServiceScope can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Src\Coravel.Mailer\Mail\Renderers\RazorRenderer.cs (line 49)
46 var actionContext = GetActionContext();
47 var view = FindView(actionContext, viewName);
48
49 using (var output = new StringWriter())
50 {
51 var viewContext = new ViewContext(
52 actionContext,
💬 StringWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
SS066 Disposable field is not disposed 8 hits
📄 Src\Coravel\Scheduling\HostedService\SchedulerHost.cs (line 19)
16 private readonly ILogger<SchedulerHost> _logger;
17 private readonly IHostApplicationLifetime _lifetime;
18 private readonly IConfiguration _config;
19 private Timer _timer;
20 private bool _schedulerEnabled = true;
21 private object _tickLockObj = new object();
22 private EnsureContinuousSecondTicks _ensureContinuousSecondTicks;
💬 Disposable field _timer in type SchedulerHost is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 Src\Coravel\Queuing\HostedService\QueuingHost.cs (line 13)
10{
11 internal class QueuingHost : IHostedService, IDisposable
12 {
13 private CancellationTokenSource _shutdown = new CancellationTokenSource();
14 private SemaphoreSlim _signal = new SemaphoreSlim(0);
15 private Timer _timer;
16 private Queue _queue;
💬 Disposable field _shutdown in type QueuingHost is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

Entitas

28 total diagnostics across 3 rules

SS008 GetHashCode() refers to mutable or static member 14 hits
📄 src\Entitas\Matcher\MatcherEquals.cs (line 46)
43
44 public override int GetHashCode()
45 {
46 if (!_isHashCached)
47 {
48 var hash = GetType().GetHashCode();
49 hash = ApplyHash(hash, _allOfIndexes, 3, 53);
💬 GetHashCode() refers to mutable field _isHashCached (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Entitas\Matcher\MatcherEquals.cs (line 49)
46 if (!_isHashCached)
47 {
48 var hash = GetType().GetHashCode();
49 hash = ApplyHash(hash, _allOfIndexes, 3, 53);
50 hash = ApplyHash(hash, _anyOfIndexes, 307, 367);
51 hash = ApplyHash(hash, _noneOfIndexes, 647, 683);
52 _hash = hash;
💬 GetHashCode() refers to mutable field _allOfIndexes (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 12 hits
📄 src\Entitas\Collector\TriggerOnEvent.cs (line 3)
1namespace Entitas
2{
3 public struct TriggerOnEvent<TEntity> where TEntity : Entity
4 {
5 public readonly IMatcher<TEntity> Matcher;
6 public readonly GroupEvent GroupEvent;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct TriggerOnEvent. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 gen\Entitas.Generators\Component\EventDeclaration.cs (line 5)
2
3namespace Entitas.Generators
4{
5 public struct EventDeclaration
6 {
7 public readonly int EventTarget;
8 public readonly int EventType;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EventDeclaration. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 2 hits
📄 src\Entitas\Collector\Collector.cs (line 64)
61 {
62 var group = _groups[i];
63 var groupEvent = _groupEvents[i];
64 switch (groupEvent)
65 {
66 case GroupEvent.Added:
67 group.OnEntityAdded -= _onEntityDelegate;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Entitas\Collector\Collector.cs (line 64)
61 {
62 var group = _groups[i];
63 var groupEvent = _groupEvents[i];
64 switch (groupEvent)
65 {
66 case GroupEvent.Added:
67 group.OnEntityAdded -= _onEntityDelegate;
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)

ScreenToGif

26 total diagnostics across 3 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 12 hits
📄 Other\Translator\Util\LogWriter.cs (line 34)
31
32 #region Creates the file
33
34 var date = Path.Combine(folder, DateTime.Now.ToString("yy_MM_dd") + ".txt");
35 var dateTime = Path.Combine(folder, DateTime.Now.ToString("yy_MM_dd hh_mm_ss_fff") + ".txt");
36
37 FileStream fs = null;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 Other\Translator\Util\LogWriter.cs (line 35)
32 #region Creates the file
33
34 var date = Path.Combine(folder, DateTime.Now.ToString("yy_MM_dd") + ".txt");
35 var dateTime = Path.Combine(folder, DateTime.Now.ToString("yy_MM_dd hh_mm_ss_fff") + ".txt");
36
37 FileStream fs = null;
38 var inUse = false;
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 6 hits
📄 ScreenToGif.Model\Enums\Native\DisplayDevices.cs (line 6)
3namespace ScreenToGif.Domain.Enums.Native;
4
5[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
6public struct DisplayDevices
7{
8 public DisplayDevices(bool? filler) : this()
9 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct DisplayDevices. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 ScreenToGif.Model\Models\Native\NativeRect.cs (line 7)
4namespace ScreenToGif.Domain.Models.Native;
5
6[StructLayout(LayoutKind.Sequential)]
7public struct NativeRect
8{
9 public int Left; // x position of upper-left corner
10 public int Top; // y position of upper-left corner
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NativeRect. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS059 IAsyncDisposable not disposed asynchronously 8 hits
📄 Other\Translator\TranslatorWindow.xaml.cs (line 706)
703
704 var response = (HttpWebResponse)await request.GetResponseAsync();
705
706 using (var resultStream = response.GetResponseStream())
707 {
708 if (resultStream == null)
709 throw new WebException("Empty response from server when getting language codes");
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 Other\Translator\TranslatorWindow.xaml.cs (line 733)
730
731 var response = (HttpWebResponse)await request.GetResponseAsync();
732
733 using (var resultStream = response.GetResponseStream())
734 {
735 if (resultStream == null)
736 throw new WebException("Empty response from server when getting language codes path");
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)

AspNetCoreDiagnosticScenarios

26 total diagnostics across 4 rules

SS001 Async method with void return type 2 hits
📄 Scenarios\Controllers\AsyncVoidController.cs (line 13)
10 public class AsyncVoidController : Controller
11 {
12 [HttpGet("/async-void-1")]
13 public async void Get()
14 {
15 await Task.Delay(1000);
16
💬 Method Get is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 Scenarios\Controllers\AsyncVoidController.cs (line 13)
10 public class AsyncVoidController : Controller
11 {
12 [HttpGet("/async-void-1")]
13 public async void Get()
14 {
15 await Task.Delay(1000);
16
💬 Method Get is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS033 Async overload is available 8 hits
📄 Scenarios\Controllers\FireAndForgetController.cs (line 26)
23 // This closure is capturing the context from the Controller action parameter. This is bad because this work item could run
24 // outside of the request scope and the PokemonDbContext is scoped to the request. As a result, this will crash the process with
25 // and ObjectDisposedException
26 context.Pokemon.Add(new Pokemon());
27 await context.SaveChangesAsync();
28 });
29
💬 Async overload available for DbSet.Add (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 Scenarios\Controllers\FireAndForgetController.cs (line 46)
43
44 // This closure is capturing the context from the Controller action parameter. This is bad because this work item could run
45 // outside of the request scope and the PokemonDbContext is scoped to the request. As a result, this will throw an unhandled ObjectDisposedException.
46 context.Pokemon.Add(new Pokemon());
47 await context.SaveChangesAsync();
48 });
49
💬 Async overload available for DbSet.Add (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 12 hits
📄 Scenarios\Services\LegacyService.cs (line 15)
12 {
13 public string DoOperationBlocking()
14 {
15 return Task.Run(() => DoAsyncOperation()).Result;
16 }
17
18 public string DoOperationBlocking2()
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 Scenarios\Services\LegacyService.cs (line 25)
22
23 public string DoOperationBlocking3()
24 {
25 return Task.Run(() => DoAsyncOperation().Result).Result;
26 }
27
28 public string DoOperationBlocking4()
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS037 HttpClient instantiated directly 4 hits
📄 Scenarios\Controllers\HttpClientController.cs (line 15)
12 [Route("/httpclient-1")]
13 public async Task<string> OutgoingWorse()
14 {
15 var client = new HttpClient();
16 return await client.GetStringAsync(_url);
17 }
18
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 Scenarios\Controllers\HttpClientController.cs (line 22)
19 [Route("/httpclient-2")]
20 public async Task<string> OutgoingBad()
21 {
22 using (var client = new HttpClient())
23 {
24 return await client.GetStringAsync(_url);
25 }
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)

maui-samples

24 total diagnostics across 2 rules

SS001 Async method with void return type 12 hits
📄 10.0\Animations\Animations\Pages\Controls\EasingCard.cs (line 42)
39 });
40 }
41
42 private async void OnDblTap(object obj)
43 {
44 _cancelTapToken.Cancel();
45 Debug.WriteLine("You DOUBLE tapped");
💬 Method OnDblTap is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
📄 10.0\Animations\Animations\Pages\Controls\EasingCard.cs (line 53)
50 //await Shell.Current.GoToAsync($"{nameof(EasingEditorPage)}", navigationParameter);
51 }
52
53 private async void OnTap(object obj)
54 {
55 await DebouncedTap().ConfigureAwait(false);
56 }
💬 Method OnTap is marked as async but has a void return type (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md)
SS033 Async overload is available 12 hits
📄 10.0\Animations\Animations\Pages\Controls\EasingCard.cs (line 44)
41
42 private async void OnDblTap(object obj)
43 {
44 _cancelTapToken.Cancel();
45 Debug.WriteLine("You DOUBLE tapped");
46 var navigationParameter = new Dictionary<string, object>
47 {
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 10.0\Animations\Animations\Pages\Controls\EasingCard.cs (line 64)
61 {
62 try
63 {
64 Interlocked.Exchange(ref _cancelTapToken, new CancellationTokenSource()).Cancel();
65
66 //NOTE THE 500 HERE - WHICH IS THE TIME TO WAIT
67 await Task.Delay(TimeSpan.FromMilliseconds(300), _cancelTapToken.Token)
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)

SimplCommerce

24 total diagnostics across 3 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 18 hits
📄 test\SimplCommerce.Module.Pricing.Tests\Controllers\CartRuleApiControllerTests.cs (line 56)
53 Id = 1,
54 Name = "Test Cart Rule",
55 IsActive = true,
56 StartOn = DateTime.Now,
57 EndOn = DateTime.Now.AddDays(7),
58 IsCouponRequired = true,
59 RuleToApply = "Coupon",
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 test\SimplCommerce.Module.Pricing.Tests\Controllers\CartRuleApiControllerTests.cs (line 57)
54 Name = "Test Cart Rule",
55 IsActive = true,
56 StartOn = DateTime.Now,
57 EndOn = DateTime.Now.AddDays(7),
58 IsCouponRequired = true,
59 RuleToApply = "Coupon",
60 DiscountAmount = 10,
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS033 Async overload is available 2 hits
📄 src\SimplCommerce.WebHost\Program.cs (line 28)
25ConfigureService();
26var app = builder.Build();
27Configure();
28app.Run();
29
30void ConfigureService()
31{
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\SimplCommerce.WebHost\Program.cs (line 28)
25ConfigureService();
26var app = builder.Build();
27Configure();
28app.Run();
29
30void ConfigureService()
31{
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS059 IAsyncDisposable not disposed asynchronously 4 hits
📄 src\SimplCommerce.Infrastructure\Extensions\HttpClientExtensions.cs (line 14)
11
12 public static async Task<T> ReadAsJsonAsync<T>(this HttpContent httpContent)
13 {
14 using (var stream = await httpContent.ReadAsStreamAsync())
15 {
16 var jsonReader = new JsonTextReader(new StreamReader(stream));
17
💬 Stream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 src\SimplCommerce.Infrastructure\Web\RazorViewToStringRenderer.cs (line 42)
39 Model = model
40 };
41
42 using (var output = new StringWriter())
43 {
44 var viewContext = new ViewContext(
45 actionContext,
💬 StringWriter can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)

SteamAchievementManager

24 total diagnostics across 1 rules

SS017 Struct without Equals/GetHashCode/ToString overridden 24 hits
📄 SAM.API\Interfaces\ISteamApps001.cs (line 29)
26namespace SAM.API.Interfaces
27{
28 [StructLayout(LayoutKind.Sequential, Pack = 1)]
29 public struct ISteamApps001
30 {
31 public IntPtr GetAppData;
32 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct ISteamApps001. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 SAM.API\NativeClass.cs (line 29)
26namespace SAM.API
27{
28 [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
29 internal struct NativeClass
30 {
31 public IntPtr VirtualTable;
32 }
💬 Implement Equals(), GetHashCode() and ToString() methods on struct NativeClass. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)

querybuilder

22 total diagnostics across 5 rules

SS003 Integer divided by integer causing implicit rounding 4 hits
📄 QueryBuilder\Compilers\SqlServerCompiler.cs (line 181)
178 var colNames = string.Join(", ", adHoc.Columns.Select(Wrap));
179
180 var valueRow = string.Join(", ", Enumerable.Repeat(parameterPlaceholder, adHoc.Columns.Count));
181 var valueRows = string.Join(", ", Enumerable.Repeat($"({valueRow})", adHoc.Values.Count / adHoc.Columns.Count));
182 var sql = $"SELECT {colNames} FROM (VALUES {valueRows}) AS tbl ({colNames})";
183
184 ctx.RawSql = sql;
💬 The operands in the divisive expression adHoc.Values.Count / adHoc.Columns.Count are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 QueryBuilder\Compilers\Compiler.cs (line 243)
240 row += $" FROM {fromTable}";
241 }
242
243 var rows = string.Join(" UNION ALL ", Enumerable.Repeat(row, adHoc.Values.Count / adHoc.Columns.Count));
244
245 ctx.RawSql = rows;
246 ctx.Bindings = adHoc.Values;
💬 The operands in the divisive expression adHoc.Values.Count / adHoc.Columns.Count are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS019 Switch is missing default label 4 hits
📄 QueryBuilder\Compilers\PostgresCompiler.cs (line 35)
32 {
33 method = x.CaseSensitive ? "LIKE" : "ILIKE";
34
35 switch (x.Operator)
36 {
37 case "starts":
38 value = $"{value}%";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 QueryBuilder\Compilers\Compiler.Conditions.cs (line 120)
117
118 method = "LIKE";
119
120 switch (x.Operator)
121 {
122 case "starts":
123 value = $"{value}%";
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS033 Async overload is available 4 hits
📄 SqlKata.Execution\QueryFactory.cs (line 569)
566
567 while (result.HasNext)
568 {
569 result = result.Next(transaction);
570 if (!func(result.List, result.Page))
571 {
572 return;
💬 Async overload available for PaginationResult.Next (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 SqlKata.Execution\QueryFactory.cs (line 605)
602
603 while (result.HasNext)
604 {
605 result = result.Next(transaction);
606 action(result.List, result.Page);
607 }
608 }
💬 Async overload available for PaginationResult.Next (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS044 Attribute must specify [AttributeUsage] 6 hits
📄 QueryBuilder\ColumnAttribute.cs (line 8)
5 /// <summary>
6 /// This class is used as metadata on a property to generate different name in the output query.
7 /// </summary>
8 public class ColumnAttribute : Attribute
9 {
10 public string Name { get; private set; }
11 public ColumnAttribute(string name)
💬 ColumnAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
📄 QueryBuilder\ColumnAttribute.cs (line 25)
22 /// <summary>
23 /// This class is used as metadata on a property to determine if it is a primary key
24 /// </summary>
25 public class KeyAttribute : ColumnAttribute
26 {
27 public KeyAttribute([System.Runtime.CompilerServices.CallerMemberName] string name = "")
28 : base(name)
💬 KeyAttribute should specify how the attribute can be used (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md)
SS058 String concatenated in a loop 4 hits
📄 QueryBuilder\Compilers\OracleCompiler.cs (line 169)
166 string intoFormat = " INTO {0}{1} VALUES ({2})";
167 var nextInsert = string.Format(intoFormat, table, columns, values);
168
169 ctx.RawSql += nextInsert;
170 }
171
172 ctx.RawSql += " SELECT 1 FROM DUAL";
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)
📄 QueryBuilder\Compilers\Compiler.cs (line 464)
461 foreach (var insert in inserts.Skip(1))
462 {
463 string values = string.Join(", ", Parameterize(ctx, insert.Values));
464 ctx.RawSql += $", ({values})";
465 }
466 return ctx;
467 }
💬 A string was concatenated in a loop which introduces intermediate allocations. Consider using a StringBuilder or pre-allocated string instead. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS058-StringConcatenatedInLoop.md)

keepass2android

22 total diagnostics across 4 rules

SS004 Elementary methods of type in collection not overridden 2 hits
📄 src\Kp2aAutofillParser.Tests\AutofillTest.cs (line 124)
121 if (expectedHints == null)
122 expectedHints = new string[0];
123 string[] actualHints;
124 parser.FieldsMappedToHints.TryGetValue(field, out actualHints);
125 if (actualHints == null)
126 actualHints = new string[0];
127 if (actualHints.Any() || expectedHints.Any())
💬 Type TestInputField is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Kp2aAutofillParser.Tests\AutofillTest.cs (line 124)
121 if (expectedHints == null)
122 expectedHints = new string[0];
123 string[] actualHints;
124 parser.FieldsMappedToHints.TryGetValue(field, out actualHints);
125 if (actualHints == null)
126 actualHints = new string[0];
127 if (actualHints.Any() || expectedHints.Any())
💬 Type TestInputField is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS008 GetHashCode() refers to mutable or static member 12 hits
📄 src\Kp2aAutofillParser\AutofillParser.cs (line 722)
719 {
720 unchecked
721 {
722 var result = TextValue != null ? TextValue.GetHashCode() : 0;
723 result = 31 * result + (DateValue != null ? DateValue.GetHashCode() : 0);
724 result = 31 * result + (ToggleValue != null ? ToggleValue.GetHashCode() : 0);
725 return result;
💬 GetHashCode() refers to mutable property TextValue (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 src\Kp2aAutofillParser\AutofillParser.cs (line 722)
719 {
720 unchecked
721 {
722 var result = TextValue != null ? TextValue.GetHashCode() : 0;
723 result = 31 * result + (DateValue != null ? DateValue.GetHashCode() : 0);
724 result = 31 * result + (ToggleValue != null ? ToggleValue.GetHashCode() : 0);
725 return result;
💬 GetHashCode() refers to mutable property TextValue (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS019 Switch is missing default label 6 hits
📄 src\Kp2aAutofillParser\AutofillParser.cs (line 116)
113
114 public static bool isW3cTypePrefix(string hint)
115 {
116 switch (hint.ToLower())
117 {
118 case W3cHints.PREFIX_WORK:
119 case W3cHints.PREFIX_FAX:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 src\Kp2aAutofillParser\AutofillParser.cs (line 105)
102
103 public static bool isW3cAddressType(string hint)
104 {
105 switch (hint.ToLower())
106 {
107 case W3cHints.SHIPPING:
108 case W3cHints.BILLING:
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS041 Unnecessary enumerable materialization 2 hits
📄 src\Kp2aAutofillParser\AutofillParser.cs (line 870)
867 if (viewHints.Where(h => h != null).Select(AutofillHintsHelper.ToCanonicalHint).Intersect(_autofillHintsForLogin).Any())
868 {
869
870 AddFieldToHintMap(viewNode, viewHints.Where(h => h != null).Select(AutofillHintsHelper.ToCanonicalHint).ToHashSet().ToArray());
871 }
872
873 }
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)
📄 src\Kp2aAutofillParser\AutofillParser.cs (line 870)
867 if (viewHints.Where(h => h != null).Select(AutofillHintsHelper.ToCanonicalHint).Intersect(_autofillHintsForLogin).Any())
868 {
869
870 AddFieldToHintMap(viewNode, viewHints.Where(h => h != null).Select(AutofillHintsHelper.ToCanonicalHint).ToHashSet().ToArray());
871 }
872
873 }
💬 ToHashSet is unnecessarily materializing the IEnumerable and can be omitted (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md)

eShop

20 total diagnostics across 5 rules

SS004 Elementary methods of type in collection not overridden 2 hits
No source samples extracted
SS008 GetHashCode() refers to mutable or static member 8 hits
No source samples extracted
SS019 Switch is missing default label 2 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 2 hits
No source samples extracted
SS066 Disposable field is not disposed 6 hits
No source samples extracted

EquinoxProject

20 total diagnostics across 5 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 2 hits
📄 src\Equinox.Domain\Commands\Validations\CustomerValidation.cs (line 38)
35
36 protected static bool HaveMinimumAge(DateTime birthDate)
37 {
38 return birthDate <= DateTime.Now.AddYears(-18);
39 }
40 }
41}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\Equinox.Domain\Commands\Validations\CustomerValidation.cs (line 38)
35
36 protected static bool HaveMinimumAge(DateTime birthDate)
37 {
38 return birthDate <= DateTime.Now.AddYears(-18);
39 }
40 }
41}
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 src\Equinox.Services.Api\Configurations\SwaggerConfig.cs (line 37)
34 s.AddSecurityRequirement(new OpenApiSecurityRequirement
35 {
36 {
37 new OpenApiSecurityScheme
38 {
39 Reference = new OpenApiReference
40 {
💬 Type OpenApiSecurityScheme is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\Equinox.Services.Api\Configurations\SwaggerConfig.cs (line 37)
34 s.AddSecurityRequirement(new OpenApiSecurityRequirement
35 {
36 {
37 new OpenApiSecurityScheme
38 {
39 Reference = new OpenApiReference
40 {
💬 Type OpenApiSecurityScheme is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS033 Async overload is available 4 hits
📄 src\Equinox.Services.Api\Program.cs (line 31)
28app.MapIdentityApi<IdentityUser>();
29
30app.UseSwaggerSetup();
31app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\Equinox.UI.Web\Program.cs (line 39)
36// Applying migrations and seeding some data
37app.UseDbSeed();
38
39app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
SS034 Accessing Task.Result without await 6 hits
📄 src\Equinox.Infra.CrossCutting.Identity\API\JwtBuilder.cs (line 38)
35 {
36 if (string.IsNullOrEmpty(email)) throw new ArgumentException(nameof(email));
37
38 _user = _userManager.FindByEmailAsync(email).Result;
39 _userClaims = new List<Claim>();
40 _jwtClaims = new List<Claim>();
41 _identityClaims = new ClaimsIdentity();
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 src\Equinox.Infra.CrossCutting.Identity\API\JwtBuilder.cs (line 61)
58
59 public JwtBuilder<TIdentityUser, TKey> WithUserClaims()
60 {
61 _userClaims = _userManager.GetClaimsAsync(_user).Result;
62 _identityClaims.AddClaims(_userClaims);
63
64 return this;
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS066 Disposable field is not disposed 6 hits
📄 src\Equinox.Application\Services\CustomerAppService.cs (line 20)
17 IMediatorHandler mediator,
18 IEventStoreRepository eventStoreRepository) : ICustomerAppService
19 {
20 private readonly ICustomerRepository _customerRepository = customerRepository;
21 private readonly IEventStoreRepository _eventStoreRepository = eventStoreRepository;
22 private readonly IMediatorHandler _mediator = mediator;
23
💬 Disposable field _customerRepository in type CustomerAppService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)
📄 src\Equinox.Application\Services\CustomerAppService.cs (line 21)
18 IEventStoreRepository eventStoreRepository) : ICustomerAppService
19 {
20 private readonly ICustomerRepository _customerRepository = customerRepository;
21 private readonly IEventStoreRepository _eventStoreRepository = eventStoreRepository;
22 private readonly IMediatorHandler _mediator = mediator;
23
24 public async Task<IEnumerable<CustomerViewModel>> GetAll()
💬 Disposable field _eventStoreRepository in type CustomerAppService is not disposed (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md)

repkg

20 total diagnostics across 5 rules

SS003 Integer divided by integer causing implicit rounding 10 hits
📄 RePKG.Application\Texture\Helpers\DXT.cs (line 79)
76 {
77 // Use 5-Alpha Codebook
78 for (var i = 1; i < 5; i++)
79 codes[1 + i] = (byte)(((5 - i) * alpha0 + i * alpha1) / 5);
80 codes[6] = 0;
81 codes[7] = 255;
82 }
💬 The operands in the divisive expression ((5 - i) * alpha0 + i * alpha1) / 5 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 RePKG.Application\Texture\Helpers\DXT.cs (line 88)
85 // Use 7-Alpha Codebook
86 for (var i = 1; i < 7; i++)
87 {
88 codes[i + 1] = (byte)(((7 - i) * alpha0 + i * alpha1) / 7);
89 }
90 }
91
💬 The operands in the divisive expression ((7 - i) * alpha0 + i * alpha1) / 7 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS008 GetHashCode() refers to mutable or static member 2 hits
📄 RePKG.Application\Texture\Helpers\RG88.cs (line 164)
161 public override string ToString() => $"RG({R}, {G})";
162
163 [MethodImpl(MethodImplOptions.AggressiveInlining)]
164 public override int GetHashCode() => Rg.GetHashCode();
165
166 [MethodImpl(MethodImplOptions.AggressiveInlining)]
167 private void Pack(ref Vector4 vector)
💬 GetHashCode() refers to mutable property Rg (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
📄 RePKG.Application\Texture\Helpers\RG88.cs (line 164)
161 public override string ToString() => $"RG({R}, {G})";
162
163 [MethodImpl(MethodImplOptions.AggressiveInlining)]
164 public override int GetHashCode() => Rg.GetHashCode();
165
166 [MethodImpl(MethodImplOptions.AggressiveInlining)]
167 private void Pack(ref Vector4 vector)
💬 GetHashCode() refers to mutable property Rg (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md)
SS018 Switch does not handle all enum options 2 hits
📄 RePKG.Application\Texture\TexMipmapDecompressor.cs (line 23)
20 if (mipmap.Format.IsImage())
21 return;
22
23 switch (mipmap.Format)
24 {
25 case MipmapFormat.CompressedDXT5:
26 mipmap.Bytes = DXT.DecompressImage(mipmap.Width, mipmap.Height, mipmap.Bytes, DXTFlags.DXT5);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
📄 RePKG.Application\Texture\TexMipmapDecompressor.cs (line 23)
20 if (mipmap.Format.IsImage())
21 return;
22
23 switch (mipmap.Format)
24 {
25 case MipmapFormat.CompressedDXT5:
26 mipmap.Bytes = DXT.DecompressImage(mipmap.Width, mipmap.Height, mipmap.Bytes, DXTFlags.DXT5);
💬 Missing enum member in switched cases. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md)
SS019 Switch is missing default label 2 hits
📄 RePKG.Application\Texture\TexMipmapDecompressor.cs (line 23)
20 if (mipmap.Format.IsImage())
21 return;
22
23 switch (mipmap.Format)
24 {
25 case MipmapFormat.CompressedDXT5:
26 mipmap.Bytes = DXT.DecompressImage(mipmap.Width, mipmap.Height, mipmap.Bytes, DXTFlags.DXT5);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 RePKG.Application\Texture\TexMipmapDecompressor.cs (line 23)
20 if (mipmap.Format.IsImage())
21 return;
22
23 switch (mipmap.Format)
24 {
25 case MipmapFormat.CompressedDXT5:
26 mipmap.Bytes = DXT.DecompressImage(mipmap.Width, mipmap.Height, mipmap.Bytes, DXTFlags.DXT5);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS021 Test method without test attribute 4 hits
📄 RePKG.Tests\TexDecompressingTests.cs (line 89)
86 FileShare.Read), Encoding.UTF8);
87 }
88
89 public static void SaveValidatedBytes(byte[] bytes, string name)
90 {
91 using (var stream = File.Open($"{TestHelper.BasePath}\\{ValidatedDirectoryName}\\{name}.bytes",
92 FileMode.Create,
💬 Method SaveValidatedBytes might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)
📄 RePKG.Tests\TexDecompressingTests.cs (line 101)
98 }
99 }
100
101 public static void ValidateBytes(byte[] bytes, string name)
102 {
103 var validatedBytes = File.ReadAllBytes($"{TestHelper.BasePath}\\{ValidatedDirectoryName}\\{name}.bytes");
104
💬 Method ValidateBytes might be missing a test attribute (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md)

basic-computer-games

18 total diagnostics across 3 rules

SS003 Integer divided by integer causing implicit rounding 2 hits
📄 00_Common\dotnet\Games.Common\Randomness\RandomNumberGenerator.cs (line 14)
11 public RandomNumberGenerator()
12 {
13 // The BASIC RNG is seeded based on time with a 1 second resolution
14 _random = new Random((int)(DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond));
15 }
16
17 public float NextFloat() => _previous = (float)_random.NextDouble();
💬 The operands in the divisive expression DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 00_Common\dotnet\Games.Common\Randomness\RandomNumberGenerator.cs (line 14)
11 public RandomNumberGenerator()
12 {
13 // The BASIC RNG is seeded based on time with a 1 second resolution
14 _random = new Random((int)(DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond));
15 }
16
17 public float NextFloat() => _previous = (float)_random.NextDouble();
💬 The operands in the divisive expression DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 14 hits
📄 00_Common\dotnet\Games.Common\Numbers\Number.cs (line 6)
3/// <summary>
4/// A single-precision floating-point number with string formatting equivalent to the BASIC interpreter.
5/// </summary>
6public struct Number
7{
8 private readonly float _value;
9
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Number. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 00_Common\dotnet\Games.Common\IO\Tokenizer.cs (line 57)
54 (ITokenizerState, Token.Builder) Consume(char character, Token.Builder tokenBuilder);
55 }
56
57 private struct LookForStartOfTokenState : ITokenizerState
58 {
59 public (ITokenizerState, Token.Builder) Consume(char character, Token.Builder tokenBuilder) =>
60 character switch
💬 Implement Equals(), GetHashCode() and ToString() methods on struct LookForStartOfTokenState. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS019 Switch is missing default label 2 hits
📄 00_Common\dotnet\Games.Common\IO\Token.cs (line 17)
14 var match = _numberPattern.Match(String);
15
16 IsNumber = float.TryParse(match.Value, out var number);
17 Number = (IsNumber, number) switch
18 {
19 (false, _) => float.NaN,
20 (true, float.PositiveInfinity) => float.MaxValue,
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 00_Common\dotnet\Games.Common\IO\Token.cs (line 17)
14 var match = _numberPattern.Match(String);
15
16 IsNumber = float.TryParse(match.Value, out var number);
17 Number = (IsNumber, number) switch
18 {
19 (false, _) => float.NaN,
20 (true, float.PositiveInfinity) => float.MaxValue,
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)

PKHeX

16 total diagnostics across 1 rules

SS003 Integer divided by integer causing implicit rounding 16 hits
📄 PKHeX.Drawing\ImageUtil.cs (line 35)
32 public Span<byte> GetBitmapData(out BitmapData bmpData, PixelFormat format = PixelFormat.Format32bppArgb)
33 {
34 bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, format);
35 var bpp = Image.GetPixelFormatSize(format) / 8;
36 return GetSpan(bmpData.Scan0, bmp.Width * bmp.Height * bpp);
37 }
38
💬 The operands in the divisive expression Image.GetPixelFormatSize(format) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 PKHeX.Drawing\ImageUtil.cs (line 72)
69 public byte[] GetBitmapData()
70 {
71 var format = bmp.PixelFormat;
72 var bpp = Image.GetPixelFormatSize(format) / 8;
73 var result = new byte[bmp.Width * bmp.Height * bpp];
74 bmp.GetBitmapData(result, format);
75 return result;
💬 The operands in the divisive expression Image.GetPixelFormatSize(format) / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)

MediatR

16 total diagnostics across 4 rules

SS034 Accessing Task.Result without await 4 hits
No source samples extracted
SS044 Attribute must specify [AttributeUsage] 2 hits
No source samples extracted
SS051 Locking on mutable reference 8 hits
No source samples extracted
SS066 Disposable field is not disposed 2 hits
No source samples extracted

carter

12 total diagnostics across 2 rules

SS033 Async overload is available 8 hits
No source samples extracted
SS059 IAsyncDisposable not disposed asynchronously 4 hits
No source samples extracted

Flurl

12 total diagnostics across 2 rules

SS017 Struct without Equals/GetHashCode/ToString overridden 6 hits
No source samples extracted
SS058 String concatenated in a loop 6 hits
No source samples extracted

mongo-csharp-driver

12 total diagnostics across 1 rules

SS017 Struct without Equals/GetHashCode/ToString overridden 12 hits
📄 tests\SmokeTests\MongoDB.Driver.SmokeTests.Sdk\LogEntry.cs (line 20)
17
18namespace MongoDB.Driver.SmokeTests.Sdk
19{
20 internal struct LogEntry
21 {
22 public LogEntry(LogLevel logLevel, string category, string message)
23 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct LogEntry. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 tests\SmokeTests\MongoDB.Driver.SmokeTests.Sdk\LogEntry.cs (line 20)
17
18namespace MongoDB.Driver.SmokeTests.Sdk
19{
20 internal struct LogEntry
21 {
22 public LogEntry(LogLevel logLevel, string category, string message)
23 {
💬 Implement Equals(), GetHashCode() and ToString() methods on struct LogEntry. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)

sample-dotnet-core-cqrs-api

10 total diagnostics across 4 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 src\SampleProject.Domain\SeedWork\DomainEventBase.cs (line 9)
6 {
7 public DomainEventBase()
8 {
9 this.OccurredOn = DateTime.Now;
10 }
11
12 public DateTime OccurredOn { get; }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 src\SampleProject.Infrastructure\Domain\ForeignExchanges\ForeignExchange.cs (line 28)
25
26 List<ConversionRate> rates = GetConversionRatesFromExternalApi();
27
28 this._cacheStore.Add(new ConversionRatesCache(rates), new ConversionRatesCacheKey(), DateTime.Now.Date.AddDays(1));
29
30 return rates;
31 }
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 src\SampleProject.Application\Configuration\Emails\EmailMessage.cs (line 3)
1namespace SampleProject.Application.Configuration.Emails
2{
3 public struct EmailMessage
4 {
5 public string From { get; }
6
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EmailMessage. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\SampleProject.Application\Configuration\Emails\EmailMessage.cs (line 3)
1namespace SampleProject.Application.Configuration.Emails
2{
3 public struct EmailMessage
4 {
5 public string From { get; }
6
💬 Implement Equals(), GetHashCode() and ToString() methods on struct EmailMessage. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
SS023 Exception thrown from property getter 2 hits
📄 src\SampleProject.API\Configuration\ExecutionContextAccessor.cs (line 26)
23 return Guid.Parse(
24 _httpContextAccessor.HttpContext.Request.Headers[CorrelationMiddleware.CorrelationHeaderKey]);
25 }
26 throw new ApplicationException("Http context and correlation id is not available");
27 }
28 }
29
💬 An exception is thrown from the getter of property CorrelationId (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
📄 src\SampleProject.API\Configuration\ExecutionContextAccessor.cs (line 26)
23 return Guid.Parse(
24 _httpContextAccessor.HttpContext.Request.Headers[CorrelationMiddleware.CorrelationHeaderKey]);
25 }
26 throw new ApplicationException("Http context and correlation id is not available");
27 }
28 }
29
💬 An exception is thrown from the getter of property CorrelationId (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md)
SS033 Async overload is available 2 hits
📄 src\SampleProject.Infrastructure\Processing\DomainEventsDispatcher.cs (line 74)
71 domainEventNotification.DomainEvent.OccurredOn,
72 type,
73 data);
74 this._ordersContext.OutboxMessages.Add(outboxMessage);
75 }
76 }
77 }
💬 Async overload available for DbSet.Add (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\SampleProject.Infrastructure\Processing\DomainEventsDispatcher.cs (line 74)
71 domainEventNotification.DomainEvent.OccurredOn,
72 type,
73 data);
74 this._ordersContext.OutboxMessages.Add(outboxMessage);
75 }
76 }
77 }
💬 Async overload available for DbSet.Add (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)

Stateless

10 total diagnostics across 1 rules

SS034 Accessing Task.Result without await 10 hits
No source samples extracted

samples

8 total diagnostics across 2 rules

SS002 Use DateTime.UtcNow instead of DateTime.Now 4 hits
📄 core\extensions\AppWithPlugin\JsonPlugin\JsonPlugin.cs (line 32)
29 JsonLocation = jsonAssembly.Location,
30 Machine = Environment.MachineName,
31 User = Environment.UserName,
32 Date = DateTime.Now
33 };
34
35 Console.WriteLine(JsonConvert.SerializeObject(info, Formatting.Indented));
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
📄 core\extensions\AppWithPlugin\OldJsonPlugin\JsonPlugin.cs (line 30)
27 JsonVersion = jsonAssembly.FullName,
28 JsonLocation = jsonAssembly.Location,
29 Machine = Environment.MachineName,
30 Date = DateTime.Now
31 };
32
33 Console.WriteLine(JsonConvert.SerializeObject(info, Formatting.Indented));
💬 Use DateTime.UtcNow to get a locale-independent value (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS002-DateTimeNow.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 4 hits
📄 core\extensions\AppWithPlugin\JsonPlugin\JsonPlugin.cs (line 14)
11
12 public string Description => "Outputs JSON value.";
13
14 private struct Info
15 {
16 public string JsonVersion;
17 public string JsonLocation;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Info. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 core\extensions\AppWithPlugin\OldJsonPlugin\JsonPlugin.cs (line 14)
11
12 public string Description => "Outputs JSON value.";
13
14 private struct Info
15 {
16 public string JsonVersion;
17 public string JsonLocation;
💬 Implement Equals(), GetHashCode() and ToString() methods on struct Info. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)

Discord.Net

8 total diagnostics across 2 rules

SS034 Accessing Task.Result without await 2 hits
📄 samples\InteractionFramework\InteractionHandler.cs (line 82)
79 // If Slash Command execution fails it is most likely that the original interaction acknowledgement will persist. It is a good idea to delete the original
80 // response, or at least let the user know that something went wrong during the command execution.
81 if (interaction.Type is InteractionType.ApplicationCommand)
82 await interaction.GetOriginalResponseAsync().ContinueWith(async (msg) => await msg.Result.DeleteAsync());
83 }
84 }
85
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
📄 samples\InteractionFramework\InteractionHandler.cs (line 82)
79 // If Slash Command execution fails it is most likely that the original interaction acknowledgement will persist. It is a good idea to delete the original
80 // response, or at least let the user know that something went wrong during the command execution.
81 if (interaction.Type is InteractionType.ApplicationCommand)
82 await interaction.GetOriginalResponseAsync().ContinueWith(async (msg) => await msg.Result.DeleteAsync());
83 }
84 }
85
💬 Use await to get the result of a Task. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md)
SS059 IAsyncDisposable not disposed asynchronously 6 hits
📄 experiment\Discord.Net.BuildOverrides\BuildOverrides.cs (line 268)
265 if (!result.IsSuccessStatusCode)
266 throw new HttpRequestException("Failed to get dependency");
267
268 using (var ms = new MemoryStream())
269 {
270 var innerStream = await result.Content.ReadAsStreamAsync();
271 await innerStream.CopyToAsync(ms);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)
📄 experiment\Discord.Net.BuildOverrides\BuildOverrides.cs (line 268)
265 if (!result.IsSuccessStatusCode)
266 throw new HttpRequestException("Failed to get dependency");
267
268 using (var ms = new MemoryStream())
269 {
270 var innerStream = await result.Content.ReadAsStreamAsync();
271 await innerStream.CopyToAsync(ms);
💬 MemoryStream can be disposed of asynchronously (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS059-DisposeAsyncDisposable.md)

SteamKit

8 total diagnostics across 1 rules

SS004 Elementary methods of type in collection not overridden 8 hits
📄 Resources\ProtobufDumper\ProtobufDumper\ProtobufDumper.cs (line 228)
225 foreach ( var dep in node.Proto.dependency )
226 {
227 var depend = protobufMap[ dep ];
228 set.Add( depend.Proto );
229 RecursiveAddPublicDependencies( set, depend, depth + 1 );
230 }
231 }
💬 Type FileDescriptorProto is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 Resources\ProtobufDumper\ProtobufDumper\ProtobufDumper.cs (line 237)
234 foreach ( var idx in node.Proto.public_dependency )
235 {
236 var depend = protobufMap[ node.Proto.dependency[ idx ] ];
237 set.Add( depend.Proto );
238 RecursiveAddPublicDependencies( set, depend, depth + 1 );
239 }
240 }
💬 Type FileDescriptorProto is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)

AspNetCoreRateLimit

8 total diagnostics across 3 rules

SS003 Integer divided by integer causing implicit rounding 4 hits
📄 src\AspNetCoreRateLimit\Net\IPAddressRange.cs (line 121)
118 internal static byte[] GetBitMask(int sizeOfBuff, int bitLen)
119 {
120 var maskBytes = new byte[sizeOfBuff];
121 var bytesLen = bitLen / 8;
122 var bitsLen = bitLen % 8;
123 for (var i = 0; i < bytesLen; i++)
124 {
💬 The operands in the divisive expression bitLen / 8 are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
📄 src\AspNetCoreRateLimit.Redis\RedisProcessingStrategy.cs (line 35)
32 public async Task<RateLimitCounter> IncrementAsync(string counterId, TimeSpan interval, Func<double> RateIncrementer = null)
33 {
34 var now = DateTime.UtcNow;
35 var numberOfIntervals = now.Ticks / interval.Ticks;
36 var intervalStart = new DateTime(numberOfIntervals * interval.Ticks, DateTimeKind.Utc);
37
38 _logger.LogDebug("Calling Lua script. {counterId}, {timeout}, {delta}", counterId, interval.TotalSeconds, 1D);
💬 The operands in the divisive expression now.Ticks / interval.Ticks are both integers and result in an implicit rounding. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS003-DivideIntegerByInteger.md)
SS004 Elementary methods of type in collection not overridden 2 hits
📄 src\AspNetCoreRateLimit\Middleware\RateLimitMiddleware.cs (line 110)
107 }
108 }
109
110 rulesDict.Add(rule, rateLimitCounter);
111 }
112
113 // set X-Rate-Limit headers for the longest period
💬 Type RateLimitRule is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
📄 src\AspNetCoreRateLimit\Middleware\RateLimitMiddleware.cs (line 110)
107 }
108 }
109
110 rulesDict.Add(rule, rateLimitCounter);
111 }
112
113 // set X-Rate-Limit headers for the longest period
💬 Type RateLimitRule is used in a collection lookup but does not override Equals() and GetHashCode() (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md)
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
📄 src\AspNetCoreRateLimit\Models\RateLimitCounter.cs (line 8)
5 /// <summary>
6 /// Stores the initial access time and the numbers of calls made from that point
7 /// </summary>
8 public struct RateLimitCounter
9 {
10 public DateTime Timestamp { get; set; }
11
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RateLimitCounter. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)
📄 src\AspNetCoreRateLimit\Models\RateLimitCounter.cs (line 8)
5 /// <summary>
6 /// Stores the initial access time and the numbers of calls made from that point
7 /// </summary>
8 public struct RateLimitCounter
9 {
10 public DateTime Timestamp { get; set; }
11
💬 Implement Equals(), GetHashCode() and ToString() methods on struct RateLimitCounter. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md)

jellyfin-plugin-metatube

8 total diagnostics across 2 rules

SS019 Switch is missing default label 6 hits
📄 Jellyfin.Plugin.MetaTube\Providers\ExternalUrlProvider.cs (line 18)
15 {
16 if (item.TryGetProviderId(Plugin.ProviderId, out var pid))
17 {
18 switch (item)
19 {
20 case Movie:
21 yield return string.Format(new MovieExternalId().UrlFormatString, pid);
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 Jellyfin.Plugin.MetaTube\Helpers\ProviderId.cs (line 39)
36
37 private static bool? ToBool(string s)
38 {
39 switch (s)
40 {
41 case "1":
42 case "t":
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
SS037 HttpClient instantiated directly 2 hits
📄 Jellyfin.Plugin.MetaTube\ApiClient.cs (line 254)
251
252 static ApiClient()
253 {
254 HttpClient = new HttpClient(new SocketsHttpHandler
255 {
256 // Connect Timeout.
257 ConnectTimeout = TimeSpan.FromSeconds(30),
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)
📄 Jellyfin.Plugin.MetaTube\ApiClient.cs (line 254)
251
252 static ApiClient()
253 {
254 HttpClient = new HttpClient(new SocketsHttpHandler
255 {
256 // Connect Timeout.
257 ConnectTimeout = TimeSpan.FromSeconds(30),
💬 HttpClient was instantiated directly. Use IHttpClientFactory instead (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md)

GoogleTranslateIpCheck

6 total diagnostics across 1 rules

SS033 Async overload is available 6 hits
📄 src\GoogleTranslateIpCheck\GoogleTranslateIpCheck\Program.cs (line 18)
15{
16 try
17 {
18 var json = File.ReadAllText(configFile);
19 config = JsonSerializer.Deserialize(json, ConfigJsonContext.Default.Config);
20 }
21 catch
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\GoogleTranslateIpCheck\GoogleTranslateIpCheck\Program.cs (line 176)
173 Console.WriteLine($"{ip}");
174 _ips.Add(ip.ToString());
175 if (listIp.Count + _ips.Count >= config!.IP扫描限制数量)
176 cts.Cancel();
177 }
178 catch
179 {
💬 Async overload available for CancellationTokenSource.Cancel (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)

Jellyfin

6 total diagnostics across 3 rules

SS003 Integer divided by integer causing implicit rounding 2 hits
No source samples extracted
SS017 Struct without Equals/GetHashCode/ToString overridden 2 hits
No source samples extracted
SS019 Switch is missing default label 2 hits
No source samples extracted

BenchmarkDotNet

4 total diagnostics across 1 rules

SS044 Attribute must specify [AttributeUsage] 4 hits
No source samples extracted

practical-aspnetcore

2 total diagnostics across 1 rules

SS033 Async overload is available 2 hits
📄 projects\application-environment\Program.cs (line 14)
11
12 await context.Response.WriteAsync($"Version: {System.Reflection.Assembly.GetEntryAssembly().GetName().Version}<br/>");
13});
14app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 projects\application-environment\Program.cs (line 14)
11
12 await context.Response.WriteAsync($"Version: {System.Reflection.Assembly.GetEntryAssembly().GetName().Version}<br/>");
13});
14app.Run();
💬 Async overload available for WebApplication.Run (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)

OFGB

2 total diagnostics across 1 rules

SS019 Switch is missing default label 2 hits
📄 MainWindow.xaml.cs (line 123)
120
121 private static void ToggleOptions(string checkboxName, bool enable)
122 {
123 switch (checkboxName)
124 {
125 case "cb1":
126 Registry.SetValue("HKEY_CURRENT_USER\\" + cur_ver + "Explorer\\Advanced\\", "ShowSyncProviderNotifications", Convert.ToInt32(!enable));
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)
📄 MainWindow.xaml.cs (line 123)
120
121 private static void ToggleOptions(string checkboxName, bool enable)
122 {
123 switch (checkboxName)
124 {
125 case "cb1":
126 Registry.SetValue("HKEY_CURRENT_USER\\" + cur_ver + "Explorer\\Advanced\\", "ShowSyncProviderNotifications", Convert.ToInt32(!enable));
💬 Switch should have default label. (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md)

playwright-dotnet

2 total diagnostics across 1 rules

SS033 Async overload is available 2 hits
📄 src\tools\Playwright.Tooling\DriverDownloader.cs (line 75)
72 var regex = new Regex("<!-- GEN:(.*?) -->(.*?)<!-- GEN:stop -->", RegexOptions.Compiled);
73
74 var basePlaywrightDir = Environment.GetEnvironmentVariable("PW_SRC_DIR") ?? Path.Combine(Environment.CurrentDirectory, "..", "playwright");
75 var readme = File.ReadAllText(Path.Combine(basePlaywrightDir, "README.md"));
76 static string ReplaceBrowserVersion(string content, MatchCollection browserMatches)
77 {
78 foreach (Match match in browserMatches)
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)
📄 src\tools\Playwright.Tooling\DriverDownloader.cs (line 75)
72 var regex = new Regex("<!-- GEN:(.*?) -->(.*?)<!-- GEN:stop -->", RegexOptions.Compiled);
73
74 var basePlaywrightDir = Environment.GetEnvironmentVariable("PW_SRC_DIR") ?? Path.Combine(Environment.CurrentDirectory, "..", "playwright");
75 var readme = File.ReadAllText(Path.Combine(basePlaywrightDir, "README.md"));
76 static string ReplaceBrowserVersion(string content, MatchCollection browserMatches)
77 {
78 foreach (Match match in browserMatches)
💬 Async overload available for File.ReadAllText (https://github.com/Vannevelj/SharpSource/blob/master/docs/SS033-AsyncOverloadsAvailable.md)

Clean Repos (No Findings)

These repos produced zero SharpSource diagnostics:

✓ sqlite-net ✓ electrino ✓ docfx ✓ OptiKey ✓ WinMemoryCleaner ✓ PushSharp ✓ Open-XML-SDK ✓ shadowsocksr-csharp ✓ Opserver ✓ BetterJoy ✓ carnac ✓ Seatbelt ✓ Fody ✓ Monitorian ✓ naps2 ✓ wpftoolkit ✓ cake ✓ p2p ✓ WinAppDriver ✓ SyncClipboard ✓ Psychson ✓ clean-architecture-manga ✓ SubsCheck-Win-GUI ✓ MagicOnion ✓ RulesEngine ✓ PSReadLine ✓ SuperSocket ✓ Remotely ✓ clashN ✓ Lidarr ✓ protobuf-net ✓ SparkleShare ✓ Sheas-Cealer ✓ Umbraco-CMS ✓ Common.Utility ✓ msbuild ✓ Bloatynosy ✓ tModLoader ✓ Ladon ✓ SkiaSharp ✓ SophiApp ✓ perfview ✓ Text-Grab ✓ winforms ✓ BililiveRecorder ✓ Unity-Design-Pattern ✓ Covenant ✓ GalaxyBudsClient ✓ CliWrap ✓ Tai ✓ Rubeus ✓ mpv.net ✓ tixl ✓ WinDynamicDesktop ✓ NoteHighlight2016 ✓ Swashbuckle.WebApi ✓ TodoApp ✓ ComputeSharp ✓ MaterialSkin ✓ FFXIVQuickLauncher ✓ sdk ✓ SmartSystemMenu ✓ SoundSwitch ✓ Screenbox ✓ murder ✓ Cosmos ✓ extensions ✓ coverlet ✓ GARbro ✓ wincompose ✓ openrpa ✓ Graphics ✓ bloxstrap ✓ NBTExplorer ✓ osharp ✓ OpenDeepWiki ✓ FNA ✓ MyComputerManager ✓ DepotDownloader ✓ USBCopyer ✓ Pomelo.EntityFrameworkCore.MySql ✓ SharpLab ✓ copy-dialog-lunar-lander ✓ command-line-api ✓ elasticsearch-net ✓ SharpIDE ✓ neo ✓ YoutubeExplode ✓ AsyncEx ✓ TUnit ✓ MoreLINQ ✓ ravendb ✓ privatezilla ✓ SteamDesktopAuthenticator ✓ 163MusicLyrics ✓ oxyplot ✓ OneMore ✓ acat ✓ surging ✓ interactive ✓ run-aspnetcore-microservices ✓ FluentEmail ✓ OnTopReplica ✓ cognitive-services-speech-sdk ✓ Thrive ✓ AutoUpdater.NET ✓ Hawk ✓ TickerQ ✓ dafny ✓ win-acme ✓ RevokeMsgPatcher ✓ aspnetcore ✓ PowerShell ✓ semantic-kernel ✓ DevToys ✓ ShareX ✓ shadowsocks-windows ✓ WinUI-Gallery ✓ Verify ✓ Swashbuckle ✓ v2rayN ✓ PowerToys ✓ YARP ✓ maui ✓ YoutubeDownloader ✓ N_m3u8DL-CLI ✓ runtime ✓ Sonarr ✓ EverythingToolbar ✓ FileConverter ✓ ContextMenuManager ✓ roslyn ✓ UniGetUI ✓ QuickLook ✓ CMWTAT_Digital_Edition ✓ ml-agents ✓ PEASS-ng ✓ ILSpy ✓ Humanizer ✓ Hangfire ✓ MailKit ✓ language-ext ✓ ImageSharp ✓ Foundatio ✓ Brighter ✓ Bogus ✓ Avalonia ✓ FluentValidation ✓ EFCore.BulkExtensions ✓ CleanArchitecture ✓ Mapster ✓ Shouldly ✓ Refit ✓ ReactiveUI ✓ StackExchange.Redis ✓ spectre.console ✓ Silk.NET ✓ Prism ✓ MiniProfiler ✓ Mediator ✓ Marten ✓ NSwag ✓ NodaTime ✓ Newtonsoft.Json ✓ MonoGame ✓ downkyicore ✓ FlaxEngine ✓ ViVe ✓ Harmony ✓ ToastFish ✓ ScottPlot ✓ GameFramework ✓ ZyperWinOptimize ✓ HandyControl ✓ PixiEditor ✓ FlyOOBE ✓ sharpkeys ✓ Winhance ✓ openhardwaremonitor ✓ runner ✓ gsudo ✓ azure-sdk-for-net ✓ Everywhere ✓ workflow-core ✓ 1Remote ✓ graphql-dotnet ✓ Prowlarr ✓ dlss-swapper ✓ moq ✓ nvidiaProfileInspector ✓ websocket-sharp ✓ npoi ✓ mRemoteNG ✓ EarTrumpet ✓ Dependencies ✓ Kavita ✓ CefSharp ✓ DiscordChatExporter ✓ mono ✓ AspNetCore.Docs ✓ ArchiSteamFarm ✓ Radarr ✓ LKY_OfficeTools ✓ aspnetboilerplate ✓ PDFPatcher ✓ nopCommerce ✓ StabilityMatrix ✓ ailab ✓ blockchain ✓ stride ✓ Electron.NET ✓ wpf ✓ NETworkManager ✓ MahApps.Metro ✓ uno ✓ Notepads ✓ gitextensions ✓ Unity3DTraining ✓ DriverStoreExplorer

Skipped Repos

These repos could not be built (missing workloads, solution not found, etc.):

— html-agility-pack — Files — WaveFunctionCollapse — SteamTools — awesome-dotnet-core — osu — MaterialDesignInXamlToolkit — efcore — duplicati — abp — QuestPDF — Playnite — csharplang — ImageGlass — garnet — choco — Terminal.Gui — awesome-software-architecture — MudBlazor — ET — machinelearning — wpfui — jynew — BiliBiliToolPro — C-Sharp — EntityComponentSystemSamples — OrchardCore — MarkovJunior — DnsServer — elsa-core — clean-code-dotnet — UIEffect — reactive — AssetRipper — unity-mcp — dotnet-starter-kit — Borderless-Gaming — Mirror — MixedRealityToolkit-Unity — open-project-1 — ParrelSync — STranslate — KurrentDB — ProxySU — graphql-platform — MisakaTranslator — example-voting-app — ParticleEffectForUGUI — usbipd-win — Swashbuckle.AspNetCore — Malware-Patch — Libation — Parabolic — LittleBigMouse — QFramework — LiveCharts2 — markdig — NaughtyAttributes — FPSSample — openiddict-core — Unigram — MicaForEveryone — ZLinq — greenshot — Emby — CefFlashBrowser — one-day-one-language — MathUtilities — fluentui-blazor — sourcegit — qttabbar — azure-powershell — jint — Steamless — xunit — Digital-Logic-Sim — NatTypeTester — BootstrapBlazor — grpc-dotnet — ApplicationInspector — AspNetCore.Diagnostics.HealthChecks — Starward — NuGetForUnity — SSH.NET — UnityLibrary — testcontainers-dotnet — asm-dude — Harden-Windows-Security — AICommand — csharp-sdk — RetroBar — mapperly — MvvmCross — bflat — Magick.NET — scriban — sbox-public — crest — VRTK — XCharts — nuke — xNode — ysoserial.net — kiota — opentelemetry-dotnet — EventSourcing.NetCore — npgsql — dotnet — play-games-plugin-for-unity — Geographical-Adventures — Deform — FusionCache — redis-windows — space-station-14 — Skinner — AutoFixture — Blazorise — X-PostProcessing-Library — Templates — FancyScrollView — FOCA — Steamworks.NET — Pinta — mixbox — arfoundation-samples — LLPlayer — MiniExcel — referencesource — CppSharp — daggerfall-unity — UnrealCLR — Architecture — linq2db — EverythingPowerToys — evolutionary-architecture-by-example — UniVRM — aspnet-api-versioning — YooAsset — UnityGaussianSplatting — nbfc — GitVersion — NavMeshComponents — CommunityServer — tolua — UtinyRipper — BotSharp — obfuscar — behaviac — ZXing.Net — EasyNetQ — ReportGenerator — SharpSCADA — Pixeval — UnitsNet — AttackSurfaceAnalyzer — FairyGUI-unity — AsyncRAT-C-Sharp — Ben.Demystifier — Caliburn.Micro — ProceduralToolkit — graphy — StyleCopAnalyzers — macios