Skip to content

Commit dbb1d31

Browse files
Merge pull request #663 from TransactionProcessing/task/codacy_warning_package
Resolve Codacy warning backlog
2 parents 74dfacc + 5f976b9 commit dbb1d31

21 files changed

Lines changed: 112 additions & 111 deletions

File tree

‎SqlServerAgentJobDeploymentTool/MainForm.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -791,7 +791,7 @@ private string BuildConnectionString()
791791
DataSource = server,
792792
InitialCatalog = database,
793793
Encrypt = _useSslCheckBox.Checked,
794-
TrustServerCertificate = _useSslCheckBox.Checked
794+
TrustServerCertificate = false
795795
};
796796

797797
if (IsSqlAuthenticationSelected())

‎StreamManagement/Form1.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,14 @@ private async void Form1_Load(object sender, EventArgs e)
2323
private static async Task<List<StreamConfiguration>> LoadStreamConfig(CancellationToken cancellationToken)
2424
{
2525
// Read the identity server config json string
26-
String streamConfigurationJsonData = null;
26+
String streamConfigurationJsonData;
2727
using (StreamReader sr = new StreamReader("streamconfiguration.json"))
2828
{
2929
streamConfigurationJsonData = await sr.ReadToEndAsync(cancellationToken);
3030
}
3131

32-
StreamConfigurationList streamConfiguration = JsonSerializer.Deserialize<StreamConfigurationList>(streamConfigurationJsonData);
32+
StreamConfigurationList streamConfiguration = JsonSerializer.Deserialize<StreamConfigurationList>(streamConfigurationJsonData)
33+
?? throw new InvalidOperationException("Stream configuration file did not contain valid JSON.");
3334

3435
return streamConfiguration.StreamConfiguration;
3536
}

‎StreamManagementTool/Program.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,14 @@ await client.SetStreamMetadataAsync(
4848
private static async Task<List<StreamConfiguration>> LoadStreamConfig(CancellationToken cancellationToken)
4949
{
5050
// Read the identity server config json string
51-
String streamConfigurationJsonData = null;
51+
String streamConfigurationJsonData;
5252
using (StreamReader sr = new StreamReader("streammanagementconfiguration.json"))
5353
{
5454
streamConfigurationJsonData = await sr.ReadToEndAsync(cancellationToken);
5555
}
5656

57-
StreamConfigurationList streamConfiguration = JsonSerializer.Deserialize<StreamConfigurationList>(streamConfigurationJsonData);
58-
57+
StreamConfigurationList streamConfiguration = JsonSerializer.Deserialize<StreamConfigurationList>(streamConfigurationJsonData)
58+
?? throw new InvalidOperationException("Stream configuration file did not contain valid JSON.");
5959
return streamConfiguration.StreamConfiguration;
6060
}
6161
}

‎TransactionProcessing.MerchantFileProcessor/Clients/SharedAccessTokenProvider.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public async Task<Result<CachedToken>> GetAccessToken(CancellationToken cancella
2121
{
2222
if (IsTokenValid(this.currentToken))
2323
{
24-
return Result.Success(this.currentToken);
24+
return Result.Success(this.currentToken!);
2525
}
2626

2727
await this.refreshLock.WaitAsync(cancellationToken);
@@ -30,7 +30,7 @@ public async Task<Result<CachedToken>> GetAccessToken(CancellationToken cancella
3030
{
3131
if (IsTokenValid(this.currentToken))
3232
{
33-
return Result.Success(this.currentToken);
33+
return Result.Success(this.currentToken!);
3434
}
3535

3636
var tokenResult = await this.RequestToken(cancellationToken);

‎TransactionProcessing.MerchantPos/Models/Entities.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public class Merchant
77
{
88
[Key]
99
public Guid MerchantId { get; set; }
10-
public String MerchantName { get; set; }
10+
public String MerchantName { get; set; } = String.Empty;
1111
public Decimal Balance { get; set; }
1212
public DateTime LastEndOfDayDateTime { get; set; }
1313
public DateTime LastLogonDateTime { get; set; }

‎TransactionProcessing.MerchantPos/Persistence/EfRepository.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public interface IEfRepository
1414
Task UpdateTotals(Guid merchantId, Guid operatorId, Guid contractId, Decimal amount);
1515
Task<List<OperatorTotal>> GetTotals(Guid merchantId);
1616
Task ClearTotals(Guid merchantId);
17-
Task<Merchant> GetMerchant(Guid merchantId);
17+
Task<Merchant?> GetMerchant(Guid merchantId);
1818

1919
Task IncrementTransactionNumber(Guid merchantId, String merchantName);
2020
}

‎TransactionProcessing.MerchantPos/Runtime/ApiClient.cs‎

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -119,9 +119,10 @@ public async Task<Result<List<Product>>> GetProductList(MerchantConfig cfg,
119119
return ResultHelpers.CreateFailure(result);
120120
}
121121

122-
Logger.LogInformation($"{result.Data.Count} for merchant requested successfully");
122+
List<ContractResponseX> contracts = result.Data ?? [];
123+
Logger.LogInformation($"{contracts.Count} for merchant requested successfully");
123124

124-
foreach (ContractResponseX contractResponse in result.Data) {
125+
foreach (ContractResponseX contractResponse in contracts) {
125126
foreach (ContractProductX contractResponseProduct in contractResponse.Products) {
126127
products.Add(new Product {
127128
ContractId = contractResponse.ContractId,
@@ -268,6 +269,7 @@ private async Task<Result<List<SaleTransactionRequestMessage>>> BuildBillPayment
268269
Result<(String accountNumber, String accountName, String mobileNumber)> extraDetails = product.ProductSubType switch {
269270
ProductSubType.BillPaymentPostPay => await this.CreateBillPaymentBill(value, CancellationToken.None),
270271
ProductSubType.BillPaymentPrePay => await this.CreateBillPaymentMeter(CancellationToken.None),
272+
_ => throw new InvalidOperationException($"Unsupported product subtype {product.ProductSubType}"),
271273
};
272274

273275
if (extraDetails.IsFailed) {
@@ -397,7 +399,7 @@ private String BuildRequestUrl(String route) {
397399

398400
return requestUri;
399401
}
400-
private async Task<Result<(String accountNumber, String accountName, String? mobileNumber)>> CreateBillPaymentBill(Decimal billAmount, CancellationToken cancellationToken)
402+
private async Task<Result<(String accountNumber, String accountName, String mobileNumber)>> CreateBillPaymentBill(Decimal billAmount, CancellationToken cancellationToken)
401403
{
402404
Int32 accountNumber = RandomNumberGenerator.GetInt32(1, 100000);
403405
String baseAddress = this.SettingsStore.Current.ApiConfiguration.TestHost;
@@ -439,7 +441,7 @@ private String BuildRequestUrl(String route) {
439441
return ResultHelpers.CreateFailure(result);
440442
}
441443

442-
return Result.Success<(String, String, String?)>((body.meter_number.ToString(), body.customer_name, null));
444+
return Result.Success((body.meter_number.ToString(), body.customer_name, "07777777705"));
443445
}
444446

445447
}
@@ -453,7 +455,7 @@ public class ContractResponseX
453455
public int ContractReportingId { get; set; }
454456

455457
[JsonProperty("description")]
456-
public string Description { get; set; }
458+
public string Description { get; set; } = string.Empty;
457459

458460
[JsonProperty("estate_id")]
459461
public Guid EstateId { get; set; }
@@ -465,19 +467,19 @@ public class ContractResponseX
465467
public Guid OperatorId { get; set; }
466468

467469
[JsonProperty("operator_name")]
468-
public string OperatorName { get; set; }
470+
public string OperatorName { get; set; } = string.Empty;
469471

470472
[JsonProperty("products")]
471-
public List<ContractProductX> Products { get; set; }
473+
public List<ContractProductX> Products { get; set; } = [];
472474
}
473475

474476
public class ContractProductX
475477
{
476478
[JsonProperty("display_text")]
477-
public string DisplayText { get; set; }
479+
public string DisplayText { get; set; } = string.Empty;
478480

479481
[JsonProperty("name")]
480-
public string Name { get; set; }
482+
public string Name { get; set; } = string.Empty;
481483

482484
[JsonProperty("product_id")]
483485
public Guid ProductId { get; set; }
@@ -486,7 +488,7 @@ public class ContractProductX
486488
public int ProductReportingId { get; set; }
487489

488490
[JsonProperty("transaction_fees")]
489-
public List<ContractProductTransactionFeeX> TransactionFees { get; set; }
491+
public List<ContractProductTransactionFeeX> TransactionFees { get; set; } = [];
490492

491493
[JsonProperty("value")]
492494
public Decimal? Value { get; set; }
@@ -504,7 +506,7 @@ public class ContractProductTransactionFeeX
504506
public FeeType FeeType { get; set; }
505507

506508
[JsonProperty("description")]
507-
public string Description { get; set; }
509+
public string Description { get; set; } = string.Empty;
508510

509511
[JsonProperty("transaction_fee_id")]
510512
public Guid TransactionFeeId { get; set; }
@@ -536,17 +538,17 @@ public class MerchantResponse
536538
public Guid MerchantId { get; set; }
537539

538540
[JsonProperty("merchant_name")]
539-
public string MerchantName { get; set; }
541+
public string MerchantName { get; set; } = string.Empty;
540542

541543
[JsonProperty("opening_hours")]
542-
public Dictionary<DayOfWeek, OpeningHoursResponse> OpeningHours { get; set; }
544+
public Dictionary<DayOfWeek, OpeningHoursResponse> OpeningHours { get; set; } = [];
543545
}
544546

545547
public class OpeningHoursResponse
546548
{
547549
[JsonProperty("opening")]
548-
public string Opening { get; set; }
550+
public string Opening { get; set; } = string.Empty;
549551

550552
[JsonProperty("closing")]
551-
public string Closing { get; set; }
553+
public string Closing { get; set; } = string.Empty;
552554
}

‎TransactionProcessing.MerchantPos/Runtime/MerchantConfig.cs‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@ public class MerchantConfig
55
public bool Enabled { get; set; } = false; // new flag
66
public Guid EstateId { get; set; }
77
public Guid MerchantId { get; set; }
8-
public string MerchantName { get; set; }
9-
public string Username { get; set; }
10-
public string Password { get; set; }
11-
public string DeviceIdentifier { get; set; }
12-
public string ApplicationVersion { get; set; }
8+
public string MerchantName { get; set; } = string.Empty;
9+
public string Username { get; set; } = string.Empty;
10+
public string Password { get; set; } = string.Empty;
11+
public string DeviceIdentifier { get; set; } = string.Empty;
12+
public string ApplicationVersion { get; set; } = string.Empty;
1313
public int SaleIntervalSeconds { get; set; } = 30;
1414

1515
public double FailureInjectionProbability { get; set; } = 0.02;
@@ -19,7 +19,7 @@ public class MerchantConfig
1919

2020
public TimeOnly ClosingTime { get; set; } = new(23, 50);
2121
public TimeOnly OpeningTime { get; set; } = new(8, 0);
22-
public List<Product> Products { get; set; }
22+
public List<Product> Products { get; set; } = [];
2323
public Boolean RequiresEndOfDay { get; set; } = true;
24-
public MerchantResponse Merchant { get; set; }
25-
}
24+
public MerchantResponse Merchant { get; set; } = null!;
25+
}

‎TransactionProcessing.MerchantPos/Runtime/MerchantRuntime.cs‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ public MerchantRuntime(IApiClient apiClient,
2525
this.Metrics = metrics;
2626
}
2727

28-
private TokenResponse CurrentServiceToken;
29-
private TokenResponse CurrentUserToken;
30-
private (String clientId, String clientSecret) ServiceClientCredentials;
31-
private (String clientId, String clientSecret) PosClientCredentials;
28+
private TokenResponse? CurrentServiceToken;
29+
private TokenResponse? CurrentUserToken;
30+
private (String clientId, String clientSecret) ServiceClientCredentials = default!;
31+
private (String clientId, String clientSecret) PosClientCredentials = default!;
3232
public async Task RunAsync((String clientId, String clientSecret) serviceClient, (String clientId, String clientSecret) posClient , MerchantConfig config, CancellationToken cancellationToken)
3333
{
3434
Logger.LogInformation($"MerchantRuntime started for {config.MerchantName}");
@@ -131,23 +131,28 @@ private async Task StartupSequence(MerchantConfig cfg,
131131
return;
132132
}
133133

134+
TokenResponse userToken = this.CurrentUserToken
135+
?? throw new InvalidOperationException($"User token was not initialized for merchant {cfg.MerchantName}.");
136+
TokenResponse serviceToken = this.CurrentServiceToken
137+
?? throw new InvalidOperationException($"Service token was not initialized for merchant {cfg.MerchantName}.");
138+
134139
// 2. Load products
135-
Result<List<Product>> productsResult = await ApiClient.GetProductList(cfg, this.CurrentUserToken, cancellationToken);
140+
Result<List<Product>> productsResult = await ApiClient.GetProductList(cfg, userToken, cancellationToken);
136141
if (productsResult.IsFailed) {
137142
Logger.LogWarning($"Failed to get product list for merchant {cfg.MerchantName} during startup sequence.");
138143
return;
139144
}
140145
cfg.Products = productsResult.Data;
141146

142147
// 3. Balance
143-
Result<decimal> balanceResult = await ApiClient.GetBalance(cfg, this.CurrentServiceToken, cancellationToken);
148+
Result<decimal> balanceResult = await ApiClient.GetBalance(cfg, serviceToken, cancellationToken);
144149
if (balanceResult.IsFailed) {
145150
Logger.LogWarning($"Failed to get balance for merchant {cfg.MerchantName} during startup sequence.");
146151
return;
147152
}
148153
await Repository.UpdateBalance(cfg.MerchantId,cfg.MerchantName, balanceResult.Data);
149154
// 4. get the merchant record
150-
var merchant = await ApiClient.GetMerchant(cfg, this.CurrentUserToken, cancellationToken);
155+
var merchant = await ApiClient.GetMerchant(cfg, userToken, cancellationToken);
151156
cfg.Merchant = merchant.Data;
152157
}
153158

@@ -156,21 +161,29 @@ private async Task RunMainLoop(MerchantConfig cfg,
156161
TimeSpan saleInterval = TimeSpan.FromSeconds(cfg.SaleIntervalSeconds);
157162

158163
while (!token.IsCancellationRequested) {
159-
Merchant merchant = await this.Repository.GetMerchant(cfg.MerchantId);
164+
Merchant merchant = await this.Repository.GetMerchant(cfg.MerchantId)
165+
?? throw new InvalidOperationException($"Merchant {cfg.MerchantId} was not found.");
160166
// Wait until the merchant's configured opening time
161167
DateTime currentTime = DateTime.Now;
162168

163169
// Get the current days opening and closing time
164170
TimeSpan openingTime;
165171
TimeSpan closingTime;
166-
Boolean found = cfg.Merchant.OpeningHours.TryGetValue(DateTime.Now.DayOfWeek, out var openingHours);
172+
MerchantResponse merchantConfig = cfg.Merchant
173+
?? throw new InvalidOperationException($"Merchant details were not loaded for {cfg.MerchantName}.");
174+
175+
Boolean found = merchantConfig.OpeningHours.TryGetValue(DateTime.Now.DayOfWeek, out var openingHours);
167176
if (found == false) {
168177
// fallback to the configured default opening and closing time if no specific hours for the day of week
169178
openingTime = cfg.OpeningTime.ToTimeSpan();
170179
closingTime = cfg.ClosingTime.ToTimeSpan();
171180
}
172181
else {
173182
// We have opening and closing times for the current day of week, so use those
183+
if (openingHours is null)
184+
{
185+
throw new InvalidOperationException($"Opening hours were not configured for {cfg.MerchantName} on {DateTime.Now.DayOfWeek}.");
186+
}
174187
openingTime = TimeSpan.ParseExact(openingHours.Opening, "hhmm", null);
175188
closingTime = TimeSpan.ParseExact(openingHours.Closing, "hhmm", null);
176189
}
@@ -214,7 +227,9 @@ private async Task RunMainLoop(MerchantConfig cfg,
214227
}
215228
else
216229
{
217-
await ApiClient.SendLogon(cfg, this.CurrentUserToken, merchant.TransactionNumber, token);
230+
TokenResponse userToken = this.CurrentUserToken
231+
?? throw new InvalidOperationException($"User token was not initialized for merchant {cfg.MerchantName}.");
232+
await ApiClient.SendLogon(cfg, userToken, merchant.TransactionNumber, token);
218233
//_lastDailyLogonDate = now.Date;
219234
await this.Repository.UpdateLastLogon(cfg.MerchantId, cfg.MerchantName, now);
220235
Logger.LogInformation($"Performed daily logon for merchant {cfg.MerchantName} on {now:yyyy-MM-dd}");
@@ -235,9 +250,13 @@ private async Task DoSaleCycle(MerchantConfig cfg,Int32 transactionNumber, Cance
235250
Result tokenResult = await this.GetServiceToken(cancellationToken);
236251
if (tokenResult.IsFailed)
237252
return;
253+
TokenResponse serviceToken = this.CurrentServiceToken
254+
?? throw new InvalidOperationException($"Service token was not initialized for merchant {cfg.MerchantName}.");
238255
tokenResult = await this.GetUserToken(cfg, cancellationToken);
239256
if (tokenResult.IsFailed)
240257
return;
258+
TokenResponse userToken = this.CurrentUserToken
259+
?? throw new InvalidOperationException($"User token was not initialized for merchant {cfg.MerchantName}.");
241260

242261
decimal balance = await Repository.GetBalance(cfg.MerchantId);
243262

@@ -254,7 +273,7 @@ private async Task DoSaleCycle(MerchantConfig cfg,Int32 transactionNumber, Cance
254273
bool induceFail = NextDouble() < cfg.FailureInjectionProbability;
255274
decimal saleValue = induceFail ? balance + 10 : value;
256275

257-
Result<SaleResponse> result = await ApiClient.SendSale(cfg, this.CurrentUserToken, product, saleValue, transactionNumber, cancellationToken);
276+
Result<SaleResponse> result = await ApiClient.SendSale(cfg, userToken, product, saleValue, transactionNumber, cancellationToken);
258277

259278
if (result.IsFailed)
260279
{
@@ -278,7 +297,7 @@ private async Task DoSaleCycle(MerchantConfig cfg,Int32 transactionNumber, Cance
278297
this.Metrics.SetBalance(cfg.MerchantId, newBalance);
279298
if (newBalance < cfg.DepositThreshold)
280299
{
281-
await ApiClient.SendDeposit(cfg, this.CurrentServiceToken, cfg.DepositAmount,cancellationToken);
300+
await ApiClient.SendDeposit(cfg, serviceToken, cfg.DepositAmount,cancellationToken);
282301
await Repository.UpdateBalance(cfg.MerchantId, cfg.MerchantName, newBalance + cfg.DepositAmount);
283302
newBalance = await Repository.GetBalance(cfg.MerchantId);
284303
this.Metrics.SetBalance(cfg.MerchantId, newBalance);
@@ -296,9 +315,11 @@ private async Task DoReconciliation(MerchantConfig cfg, CancellationToken cancel
296315
Result tokenResult = await this.GetUserToken(cfg, cancellationToken);
297316
if (tokenResult.IsFailed)
298317
return;
318+
TokenResponse userToken = this.CurrentUserToken
319+
?? throw new InvalidOperationException($"User token was not initialized for merchant {cfg.MerchantName}.");
299320

300321
List<OperatorTotal> totals = await Repository.GetTotals(cfg.MerchantId);
301-
await ApiClient.SendReconciliation(cfg, this.CurrentUserToken, totals, cancellationToken);
322+
await ApiClient.SendReconciliation(cfg, userToken, totals, cancellationToken);
302323

303324
// Clear totals
304325
await this.Repository.UpdateLastEndOfDay(cfg.MerchantId, cfg.MerchantName, DateTime.Now);

‎TransactionProcessing.MerchantPos/Runtime/Product.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
namespace TransactionProcessing.MerchantPos.Runtime;
44

5-
public class Product
6-
{
7-
public string Name { get; set; }
5+
public class Product
6+
{
7+
public string Name { get; set; } = string.Empty;
88
public Guid OperatorId { get; set; }
99
public Guid ProductId { get; set; }
1010
public Guid ContractId { get; set; }
1111
public decimal Value { get; set; }
1212
public ProductType ProductType { get; set; }
1313
public ProductSubType ProductSubType { get; set; }
14-
}
14+
}

0 commit comments

Comments
 (0)