Skip to content

Commit e285646

Browse files
committed
* fix all violations of Roslyn analyzer rule and ReSharper inspection @ c#/crawler
1 parent c7bbc83 commit e285646

17 files changed

+32
-30
lines changed

c#/GlobalSuppressions.cs

+1
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@
8383
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1122:Use string.Empty for empty strings")]
8484
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1127:Generic type constraints should be on their own line")]
8585
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1128:Put constructor initializers on their own line")]
86+
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1133:Each attribute should be placed on its own line of code")]
8687
[assembly: SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1134:Attributes should not share line")]
8788
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1008:Opening parenthesis should be spaced correctly")]
8889
[assembly: SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1009:Closing parenthesis should be spaced correctly")]

c#/crawler/src/SonicPusher.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public SonicPusher(ILogger<SonicPusher> logger, IConfiguration config)
1414
_config.GetValue("Hostname", "localhost"),
1515
_config.GetValue("Port", 1491),
1616
_config.GetValue("Secret", "SecretPassword"));
17-
CollectionPrefix = _config.GetValue<string>("CollectionPrefix") ?? "tbm_";
17+
CollectionPrefix = _config.GetValue<string>("CollectionPrefix", "tbm_");
1818
}
1919

2020
public ISonicIngestConnection Ingest { get; }

c#/crawler/src/Tieba/ClientRequester.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ private async Task<HttpResponseMessage> PostJson(
100100
return acc;
101101
}) + "tiebaclient!!!";
102102
#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
103-
var signatureMd5 = BitConverter.ToString(MD5.HashData(Encoding.UTF8.GetBytes(signature))).Replace("-", "");
103+
var signatureMd5 = Convert.ToHexString(MD5.HashData(Encoding.UTF8.GetBytes(signature)));
104104
#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms
105105
postParamPairs.Add(KeyValuePair.Create("sign", signatureMd5));
106106

c#/crawler/src/Tieba/ClientRequesterTcs.cs

+2-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ public sealed class ClientRequesterTcs : WithLogTrace
77
private readonly ConcurrentQueue<TaskCompletionSource> _queue = new();
88
private readonly Timer _timer = new() {Enabled = true};
99
private readonly Stopwatch _stopwatch = new();
10-
private double _maxRps;
1110
private uint _requestCounter;
1211

1312
public ClientRequesterTcs(ILogger<ClientRequesterTcs> logger, IConfiguration config)
@@ -28,10 +27,10 @@ public ClientRequesterTcs(ILogger<ClientRequesterTcs> logger, IConfiguration con
2827
private float AverageRps => _requestCounter / (float)_stopwatch.Elapsed.TotalSeconds;
2928
private double MaxRps
3029
{
31-
get => _maxRps;
30+
get;
3231
set
3332
{
34-
_maxRps = value;
33+
field = value;
3534
if ((uint)_timer.Interval != (uint)(1000 / value))
3635
{ // only update interval with a truncated integer to prevent frequently change it
3736
// which will cause the increment of real rps can't keep up with _maxRps with long queue length

c#/crawler/src/Tieba/Crawl/Crawler/CrawlerLocks.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,11 @@ public IReadOnlyDictionary<LockId, IReadOnlyDictionary<Page, FailureCount>> Retr
9595
{
9696
lock (_failed)
9797
{
98-
var failedClone = _failed.ToDictionary(pair => pair.Key, pair =>
98+
var failedClone = _failed.ToDictionary(pair => pair.Key,
99+
IReadOnlyDictionary<Page, FailureCount> (pair) =>
99100
{
100101
lock (pair.Value)
101-
return (IReadOnlyDictionary<Page, FailureCount>)new Dictionary<Page, FailureCount>(pair.Value);
102+
return new Dictionary<Page, FailureCount>(pair.Value);
102103
});
103104
_failed.Clear();
104105
return failedClone;

c#/crawler/src/Tieba/Crawl/Facade/CrawlFacade.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ public abstract class CrawlFacade<TPostEntity, TParsedPost, TResponse, TPostProt
1919
{
2020
private readonly HashSet<Page> _lockingPages = [];
2121
private readonly ConcurrentDictionary<Uid, User.Parsed> _users = new();
22-
private UserParser? _userParser;
2322
private ICrawlFacade<TPostEntity, TParsedPost>.ExceptionHandler _exceptionHandler = _ => { };
2423

2524
// ReSharper disable UnusedAutoPropertyAccessor.Global
@@ -31,7 +30,9 @@ public required ILogger<CrawlFacade<TPostEntity, TParsedPost, TResponse, TPostPr
3130
// ReSharper restore UnusedAutoPropertyAccessor.Global
3231
protected Fid Fid { get; } = fid;
3332
protected ConcurrentDictionary<PostId, TParsedPost> Posts { get; } = new();
34-
protected UserParser UserParser => _userParser ??= userParserFactory(_users);
33+
34+
[field: AllowNull, MaybeNull]
35+
protected UserParser UserParser => field ??= userParserFactory(_users);
3536

3637
public virtual void Dispose()
3738
{

c#/crawler/src/Tieba/Crawl/Saver/IRevisionProperties.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ public interface IRevisionProperties
66
[typeof(ThreadRevision), typeof(ReplyRevision), typeof(SubReplyRevision), typeof(UserRevision)]);
77

88
private static IReadOnlyDictionary<Type, IReadOnlyDictionary<string, PropertyInfo>> GetPropsKeyByType(IEnumerable<Type> types) =>
9-
types.ToDictionary(type => type, type =>
10-
(IReadOnlyDictionary<string, PropertyInfo>)type.GetProperties().ToDictionary(prop => prop.Name));
9+
types.ToDictionary(type => type,
10+
IReadOnlyDictionary<string, PropertyInfo> (type) =>
11+
type.GetProperties().ToDictionary(prop => prop.Name));
1112
}

c#/crawler/src/Tieba/Crawl/Saver/Post/ReplySaver.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ public partial class ReplySaver(
2626
}
2727
public partial class ReplySaver
2828
{
29-
private Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>? _addSplitRevisionsDelegatesKeyByEntityType;
29+
[field: AllowNull, MaybeNull]
3030
protected override Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>
3131
AddSplitRevisionsDelegatesKeyByEntityType =>
32-
_addSplitRevisionsDelegatesKeyByEntityType ??= new(() => new()
32+
field ??= new(() => new()
3333
{
3434
{typeof(ReplyRevision.SplitFloor), AddRevisionsWithDuplicateIndex<ReplyRevision.SplitFloor>},
3535
{typeof(ReplyRevision.SplitSubReplyCount), AddRevisionsWithDuplicateIndex<ReplyRevision.SplitSubReplyCount>},

c#/crawler/src/Tieba/Crawl/Saver/Post/SubReplySaver.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ public partial class SubReplySaver(
2222
}
2323
public partial class SubReplySaver
2424
{
25-
private Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>? _addSplitRevisionsDelegatesKeyByEntityType;
25+
[field: AllowNull, MaybeNull]
2626
protected override Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>
2727
AddSplitRevisionsDelegatesKeyByEntityType =>
28-
_addSplitRevisionsDelegatesKeyByEntityType ??= new(() => new()
28+
field ??= new(() => new()
2929
{
3030
{typeof(SubReplyRevision.SplitAgreeCount), AddRevisionsWithDuplicateIndex<SubReplyRevision.SplitAgreeCount>},
3131
{typeof(SubReplyRevision.SplitDisagreeCount), AddRevisionsWithDuplicateIndex<SubReplyRevision.SplitDisagreeCount>}

c#/crawler/src/Tieba/Crawl/Saver/Post/ThreadSaver.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ public partial class ThreadSaver(
2121
}
2222
public partial class ThreadSaver
2323
{
24-
private Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>? _addSplitRevisionsDelegatesKeyByEntityType;
24+
[field: AllowNull, MaybeNull]
2525
protected override Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>
2626
AddSplitRevisionsDelegatesKeyByEntityType =>
27-
_addSplitRevisionsDelegatesKeyByEntityType ??= new(() => new()
27+
field ??= new(() => new()
2828
{
2929
{typeof(ThreadRevision.SplitViewCount), AddRevisionsWithDuplicateIndex<ThreadRevision.SplitViewCount>}
3030
});

c#/crawler/src/Tieba/Crawl/Saver/Related/AuthorRevisionSaver.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ private Action Save<TEntity, TRevision, TValue>(
9191
// locking key only using AuthorRevision.Fid and Uid, ignoring TriggeredBy
9292
// this prevents inserting multiple entities with similar time and other fields with the same values
9393
// ReSharper disable NotAccessedPositionalProperty.Global
94-
public record UniqueAuthorRevision(Fid Fid, Uid Uid);
94+
private sealed record UniqueAuthorRevision(Fid Fid, Uid Uid);
9595

9696
// ReSharper restore NotAccessedPositionalProperty.Global
9797
private sealed class LatestAuthorRevisionProjection<TValue>

c#/crawler/src/Tieba/Crawl/Saver/UserSaver.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,10 @@ public void SaveParentThreadLatestReplierUid(CrawlerDbContext db, Tid tid) =>
6161
}
6262
public partial class UserSaver
6363
{
64-
private Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>? _addSplitRevisionsDelegatesKeyByEntityType;
64+
[field: AllowNull, MaybeNull]
6565
protected override Lazy<Dictionary<Type, AddSplitRevisionsDelegate>>
6666
AddSplitRevisionsDelegatesKeyByEntityType =>
67-
_addSplitRevisionsDelegatesKeyByEntityType ??= new(() => new()
67+
field ??= new(() => new()
6868
{
6969
{typeof(UserRevision.SplitDisplayName), AddRevisionsWithDuplicateIndex<UserRevision.SplitDisplayName>},
7070
{typeof(UserRevision.SplitPortraitUpdatedAt), AddRevisionsWithDuplicateIndex<UserRevision.SplitPortraitUpdatedAt>},

c#/imagePipeline/src/Consumer/MetadataConsumer.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ private static class ExifGpsTagValuesParser
242242
: null;
243243
}
244244

245-
private static double ConvertDmsToDd(IReadOnlyList<double> dms)
245+
private static double ConvertDmsToDd(List<double> dms)
246246
{ // https://stackoverflow.com/questions/3249700/convert-degrees-minutes-seconds-to-decimal-coordinates
247247
if (dms.Count != 3) throw new ArgumentException(
248248
"Unexpected length for DMS, expecting three doubles.", nameof(dms));

c#/imagePipeline/src/Consumer/QrCodeConsumer.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public QrCodeConsumer(IConfiguration config, FailedImageHandler failedImageHandl
99
{
1010
_failedImageHandler = failedImageHandler;
1111
var modelsPath = config.GetSection("QrCodeConsumer")
12-
.GetValue("ModelPath", "./OpenCvWechatModels") ?? "./OpenCvWechatModels";
12+
.GetValue("ModelPath", "./OpenCvWechatModels");
1313
_qrCode = WeChatQRCode.Create(
1414
$"{modelsPath}/detect.prototxt",
1515
$"{modelsPath}/detect.caffemodel",

c#/imagePipeline/src/ImageBatchConsumingWorker.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ protected override async Task DoWork(CancellationToken stoppingToken)
4343
}
4444

4545
private async Task Consume(
46-
IReadOnlyCollection<ImageWithBytes> imagesWithBytes,
46+
List<ImageWithBytes> imagesWithBytes,
4747
CancellationToken stoppingToken = default)
4848
{
4949
await using var dbFactory = dbContextDefaultFactory();

c#/imagePipeline/src/Ocr/PaddleOcrProvider.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@ public PaddleOcrProvider(IConfiguration config, string script,
1818
{
1919
_config = config.GetSection("OcrConsumer:PaddleOcr");
2020
_script = script;
21-
Settings.GlobalModelDirectory =
22-
_config.GetValue("ModelPath", "./PaddleOcrModels") ?? "./PaddleOcrModels";
21+
Settings.GlobalModelDirectory = _config.GetValue("ModelPath", "./PaddleOcrModels");
2322
_paddleOcrDetectorFactory = paddleOcrDetectorFactory;
2423
_paddleOcrRecognizerFactory = paddleOcrRecognizerFactory;
2524
}

c#/imagePipeline/src/Ocr/TesseractRecognizer.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,12 @@ namespace tbm.ImagePipeline.Ocr;
55
public sealed partial class TesseractRecognizer(IConfiguration config, string script) : IDisposable
66
{
77
private readonly IConfigurationSection _config = config.GetSection("OcrConsumer:Tesseract");
8-
private Lazy<OCRTesseract>? _tesseractInstanceHorizontal;
9-
private Lazy<OCRTesseract>? _tesseractInstanceVertical;
108

119
public delegate TesseractRecognizer New(string script);
1210

1311
[SuppressMessage("ReSharper", "StringLiteralTypo")]
14-
private Lazy<OCRTesseract> TesseractInstanceHorizontal => _tesseractInstanceHorizontal ??= new(script switch
12+
[field: AllowNull, MaybeNull]
13+
private Lazy<OCRTesseract> TesseractInstanceHorizontal => field ??= new(script switch
1514
{ // https://en.wikipedia.org/wiki/Template:ISO_15924_script_codes_and_related_Unicode_data
1615
"Hans" => CreateTesseract("best/chi_sim+best/eng"),
1716
"Hant" => CreateTesseract("best/chi_tra+best/eng"),
@@ -21,7 +20,8 @@ public sealed partial class TesseractRecognizer(IConfiguration config, string sc
2120
});
2221

2322
[SuppressMessage("ReSharper", "StringLiteralTypo")]
24-
private Lazy<OCRTesseract> TesseractInstanceVertical => _tesseractInstanceVertical ??= new(script switch
23+
[field: AllowNull, MaybeNull]
24+
private Lazy<OCRTesseract> TesseractInstanceVertical => field ??= new(script switch
2525
{
2626
"Hans" => CreateTesseract("best/chi_sim_vert", isVertical: true),
2727
"Hant" => CreateTesseract("best/chi_tra_vert", isVertical: true),
@@ -43,7 +43,7 @@ public void Dispose()
4343
// https://github.com/shimat/opencvsharp/issues/873#issuecomment-1458868153
4444
// https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
4545
private OCRTesseract CreateTesseract(string scripts, bool isVertical = false) =>
46-
OCRTesseract.Create(_config.GetValue("DataPath", "") ?? "",
46+
OCRTesseract.Create(_config.GetValue("DataPath", ""),
4747
scripts, charWhitelist: "", oem: 1, psmode: isVertical ? 5 : 7);
4848
}
4949
public sealed partial class TesseractRecognizer

0 commit comments

Comments
 (0)