Skip to content

Commit fd220fa

Browse files
authored
Refactoring, Examples and Warning cleanup (#95)
1 parent 83b4560 commit fd220fa

File tree

16 files changed

+108
-40
lines changed

16 files changed

+108
-40
lines changed

.editorconfig

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,15 @@ csharp_style_unused_value_expression_statement_preference = discard_variable:sug
186186
dotnet_diagnostic.IDE0058.severity = suggestion
187187
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
188188
dotnet_diagnostic.IDE0059.severity = suggestion
189+
dotnet_diagnostic.IDE0002.severity = none
190+
dotnet_diagnostic.IDE0010.severity = none
191+
dotnet_diagnostic.IDE0021.severity = none
192+
dotnet_diagnostic.IDE0028.severity = none
193+
dotnet_diagnostic.IDE0049.severity = none
194+
dotnet_diagnostic.IDE0053.severity = none
195+
dotnet_diagnostic.IDE0090.severity = none
196+
dotnet_diagnostic.IDE0290.severity = none
197+
dotnet_diagnostic.SA1508.severity = none
189198

190199
##########################################
191200
# Formatting Rules

.vscode/settings.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
],
55
"cSpell.words": [
66
"CONNACK",
7+
"hivemq",
8+
"hivemqtt",
79
"PUBACK",
810
"PUBCOMP",
911
"PUBREC",

Examples/HiveMQtt-CLI/HiveMQtt-CLI/HiveMQtt-CLI.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net7.0</TargetFramework>
5+
<TargetFramework>net6.0</TargetFramework>
66
<RootNamespace>HiveMQtt_CLI</RootNamespace>
77
<ImplicitUsings>enable</ImplicitUsings>
88
<Nullable>enable</Nullable>

Examples/Reconnect/.vscode/launch.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"request": "launch",
1111
"preLaunchTask": "build",
1212
// If you have changed target frameworks, make sure to update the program path.
13-
"program": "${workspaceFolder}/bin/Debug/net7.0/Reconnect.dll",
13+
"program": "${workspaceFolder}/bin/Debug/net6.0/Reconnect.dll",
1414
"args": [],
1515
"cwd": "${workspaceFolder}",
1616
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console

Examples/Reconnect/NLog.config

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?xml version="1.0" encoding="utf-8" ?>
2+
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
4+
5+
<!-- optional, add some variables
6+
https://github.com/nlog/NLog/wiki/Configuration-file#variables
7+
-->
8+
<variable name="myvar" value="myvalue"/>
9+
10+
<!--
11+
See https://github.com/nlog/nlog/wiki/Configuration-file
12+
for information on customizing logging rules and outputs.
13+
-->
14+
<targets>
15+
16+
<!--
17+
add your targets here
18+
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
19+
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
20+
-->
21+
22+
<!--
23+
Write events to a file with the date in the filename.
24+
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
25+
layout="${longdate} ${uppercase:${level}} ${message}" />
26+
-->
27+
<target name="logfile" xsi:type="File" fileName="Reconnect.log" />
28+
<target name="logconsole" xsi:type="Console" />
29+
</targets>
30+
31+
<rules>
32+
<!-- add your logging rules here -->
33+
34+
<!--
35+
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
36+
<logger name="*" minlevel="Debug" writeTo="f" />
37+
-->
38+
<logger name="HiveMQtt.*" minlevel="Trace" writeTo="logconsole" />
39+
</rules>
40+
</nlog>

Examples/Reconnect/Program.cs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
using HiveMQtt.Client;
2+
using HiveMQtt.Client.Exceptions;
23
using HiveMQtt.Client.Options;
34
using System.Text.Json;
5+
using System.Diagnostics;
46

57
var topic = "hivemqtt/waiting/game";
68

7-
var options = new HiveMQClientOptions();
8-
options.Host = "127.0.0.1";
9-
options.Port = 1883;
9+
var options = new HiveMQClientOptions
10+
{
11+
Host = "127.0.0.1",
12+
Port = 1883,
13+
};
1014

1115
var client = new HiveMQClient(options);
1216

@@ -74,12 +78,12 @@
7478
break;
7579
}
7680
}
77-
catch (Exception ex)
81+
catch (HiveMQttClientException ex)
7882
{
79-
Console.WriteLine($"--> Failed to connect: {ex.Message}");
83+
Console.WriteLine($"--> Failed to reconnect: {ex.Message}");
8084

8185
// Double the delay with each failed retry to a maximum
82-
delay = Math.Min(delay * 2, 10000);
86+
delay = Math.Min(delay * 2, 15000);
8387
Console.WriteLine($"--> Will delay for {delay / 1000} seconds until next try.");
8488
}
8589
}
@@ -123,7 +127,6 @@
123127
})
124128
).ConfigureAwait(false);
125129

126-
127130
while (true)
128131
{
129132
await Task.Delay(2000).ConfigureAwait(false);

Examples/Reconnect/Reconnect.csproj

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

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net7.0</TargetFramework>
5+
<TargetFramework>net6.0</TargetFramework>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
88
</PropertyGroup>
@@ -13,8 +13,16 @@
1313
</PropertyGroup>
1414

1515
<!-- Update the version to match -->
16+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
17+
<WarningLevel>4</WarningLevel>
18+
</PropertyGroup>
1619
<ItemGroup>
17-
<PackageReference Include="HiveMQtt" Version="0.4.1" />
20+
<PackageReference Include="HiveMQtt" Version="0.4.2" />
1821
</ItemGroup>
1922

23+
<ItemGroup>
24+
<None Update="NLog.config">
25+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
26+
</None>
27+
</ItemGroup>
2028
</Project>

Source/HiveMQtt/Client/HiveMQClient.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ public HiveMQClient(HiveMQClientOptions? options = null)
4242
{
4343
options ??= new HiveMQClientOptions();
4444
this.Options = options;
45+
this.cancellationSource = new CancellationTokenSource();
4546
}
4647

4748
/// <inheritdoc />

Source/HiveMQtt/Client/HiveMQClientEvents.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
namespace HiveMQtt.Client;
1717

1818
using System;
19-
using System.Diagnostics;
2019
using HiveMQtt.Client.Events;
2120
using HiveMQtt.Client.Options;
2221
using HiveMQtt.Client.Results;

Source/HiveMQtt/Client/HiveMQClientSocket.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,11 @@ namespace HiveMQtt.Client;
2929
/// <inheritdoc />
3030
public partial class HiveMQClient : IDisposable, IHiveMQClient
3131
{
32+
private readonly CancellationTokenSource cancellationSource;
3233
private Socket? socket;
3334
private Stream? stream;
3435
private PipeReader? reader;
3536
private PipeWriter? writer;
36-
private CancellationTokenSource cancellationSource;
3737
private CancellationToken outFlowCancellationToken;
3838
private CancellationToken infoFlowCancellationToken;
3939

@@ -131,7 +131,6 @@ internal async Task<bool> ConnectSocketAsync()
131131
this.writer = PipeWriter.Create(this.stream);
132132

133133
// Setup the cancellation tokens
134-
this.cancellationSource = new CancellationTokenSource();
135134
this.outFlowCancellationToken = this.cancellationSource.Token;
136135
this.infoFlowCancellationToken = this.cancellationSource.Token;
137136

Source/HiveMQtt/Client/HiveMQClientTrafficProcessor.cs

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ private Task<bool> TrafficInflowProcessorAsync(CancellationToken cancellationTok
207207
if (readResult.IsCompleted)
208208
{
209209
// This is an unexpected exit and may be due to a network failure.
210-
Logger.Trace("TrafficInflowProcessor IsCompleted: end of the streamx");
210+
Logger.Trace("TrafficInflowProcessor IsCompleted: end of the stream");
211211

212212
if (this.connectState == ConnectState.Connected)
213213
{
@@ -220,6 +220,7 @@ private Task<bool> TrafficInflowProcessorAsync(CancellationToken cancellationTok
220220
this.cancellationSource.Cancel();
221221
return false;
222222
}
223+
223224
return true;
224225
}
225226

@@ -308,7 +309,7 @@ private Task<bool> TrafficInflowProcessorAsync(CancellationToken cancellationTok
308309
/// <summary>
309310
/// Handle an incoming Publish packet.
310311
/// </summary>
311-
/// <param name="publishPacket"></param>
312+
/// <param name="publishPacket">The received publish packet.</param>
312313
internal void HandleIncomingPublishPacket(PublishPacket publishPacket)
313314
{
314315
Logger.Trace("<-- Publish");
@@ -339,8 +340,8 @@ internal void HandleIncomingPublishPacket(PublishPacket publishPacket)
339340
/// <summary>
340341
/// Handle an incoming ConnAck packet.
341342
/// </summary>
342-
/// <param name="pubAckPacket"></param>
343-
/// <exception cref="HiveMQttClientException"></exception>
343+
/// <param name="pubAckPacket">The received PubAck packet.</param>
344+
/// <exception cref="HiveMQttClientException">Raised if the packet identifier is unknown.</exception>
344345
internal void HandleIncomingPubAckPacket(PubAckPacket pubAckPacket)
345346
{
346347
Logger.Trace("<-- PubAck");
@@ -362,7 +363,7 @@ internal void HandleIncomingPubAckPacket(PubAckPacket pubAckPacket)
362363
/// <summary>
363364
/// Handle an incoming PubRec packet.
364365
/// </summary>
365-
/// <param name="pubRecPacket"></param>
366+
/// <param name="pubRecPacket">The received PubRec packet.</param>
366367
internal void HandleIncomingPubRecPacket(PubRecPacket pubRecPacket)
367368
{
368369
Logger.Trace("<-- PubRec");
@@ -394,7 +395,7 @@ internal void HandleIncomingPubRecPacket(PubRecPacket pubRecPacket)
394395
/// <summary>
395396
/// Handle an incoming PubRel packet.
396397
/// </summary>
397-
/// <param name="pubRelPacket"></param>
398+
/// <param name="pubRelPacket">The received PubRel packet.</param>
398399
internal void HandleIncomingPubRelPacket(PubRelPacket pubRelPacket)
399400
{
400401
Logger.Trace("<-- PubRel");
@@ -417,8 +418,8 @@ internal void HandleIncomingPubRelPacket(PubRelPacket pubRelPacket)
417418
/// <summary>
418419
/// Handle an incoming PubComp packet.
419420
/// </summary>
420-
/// <param name="pubCompPacket"></param>
421-
/// <exception cref="HiveMQttClientException"></exception>
421+
/// <param name="pubCompPacket">The received PubComp packet.</param>
422+
/// <exception cref="HiveMQttClientException">Raised if the packet identifier is unknown.</exception>
422423
internal void HandleIncomingPubCompPacket(PubCompPacket pubCompPacket)
423424
{
424425
Logger.Trace("<-- PubComp");
@@ -433,10 +434,10 @@ internal void HandleIncomingPubCompPacket(PubCompPacket pubCompPacket)
433434
/// <summary>
434435
/// Write a buffer to the stream.
435436
/// </summary>
436-
/// <param name="source"></param>
437-
/// <param name="cancellationToken"></param>
438-
/// <returns></returns>
439-
/// <exception cref="HiveMQttClientException"></exception>
437+
/// <param name="source">The buffer to write.</param>
438+
/// <param name="cancellationToken">The cancellation token.</param>
439+
/// <returns>A FlushResult wrapped in a ValueTask.</returns>
440+
/// <exception cref="HiveMQttClientException">Raised if the writer is null.</exception>
440441
internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default)
441442
{
442443
if (this.writer is null)
@@ -450,9 +451,9 @@ internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, Cancella
450451
/// <summary>
451452
/// Read a buffer from the stream.
452453
/// </summary>
453-
/// <param name="cancellationToken"></param>
454-
/// <returns></returns>
455-
/// <exception cref="HiveMQttClientException"></exception>
454+
/// <param name="cancellationToken">The cancellation token.</param>
455+
/// <returns>A ReadResult wrapped in a ValueTask.</returns>
456+
/// <exception cref="HiveMQttClientException">Raised if the reader is null.</exception>
456457
internal ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default)
457458
{
458459
if (this.reader is null)

Source/HiveMQtt/Client/HiveMQClientUtil.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ namespace HiveMQtt.Client;
1818
/// <inheritdoc />
1919
public partial class HiveMQClient : IDisposable, IHiveMQClient
2020
{
21-
private bool disposed = false;
22-
private int lastPacketId = 0;
21+
private bool disposed;
22+
private int lastPacketId;
2323

2424
/// <summary>
2525
/// https://learn.microsoft.com/en-us/dotnet/api/system.idisposable?view=net-6.0.

Source/HiveMQtt/Client/Results/UnsubscribeResult.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ namespace HiveMQtt.Client.Results;
1919

2020
public class UnsubscribeResult
2121
{
22-
// FIXME: List of subscriptions with their unsubscribe reason codes
2322
public UnsubscribeResult()
2423
{
2524
this.Subscriptions = new List<Subscription>();

Source/HiveMQtt/HiveMQtt.sln

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HiveMQtt", "HiveMQtt.csproj
77
EndProject
88
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HiveMQtt-CLI", "..\..\Examples\HiveMQtt-CLI\HiveMQtt-CLI\HiveMQtt-CLI.csproj", "{B7404198-178C-43C5-9136-4BF25D23EC7E}"
99
EndProject
10+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Reconnect", "..\..\Examples\Reconnect\Reconnect.csproj", "{FE0AD218-169C-4DE6-ADBE-0B55695620B4}"
11+
EndProject
1012
Global
1113
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1214
Debug|Any CPU = Debug|Any CPU
@@ -21,6 +23,10 @@ Global
2123
{B7404198-178C-43C5-9136-4BF25D23EC7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
2224
{B7404198-178C-43C5-9136-4BF25D23EC7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
2325
{B7404198-178C-43C5-9136-4BF25D23EC7E}.Release|Any CPU.Build.0 = Release|Any CPU
26+
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27+
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Debug|Any CPU.Build.0 = Debug|Any CPU
28+
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Release|Any CPU.ActiveCfg = Release|Any CPU
29+
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Release|Any CPU.Build.0 = Release|Any CPU
2430
EndGlobalSection
2531
GlobalSection(SolutionProperties) = preSolution
2632
HideSolutionNode = FALSE
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using System.Runtime.CompilerServices;
22

3-
[assembly:InternalsVisibleTo("HiveMQtt.Test")]
3+
[assembly: InternalsVisibleTo("HiveMQtt.Test")]
44

55
[assembly: CLSCompliant(true)]

Tests/HiveMQtt.Test/HiveMQClient/HiveMQClientConnectTest.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
namespace HiveMQtt.Test.HiveMQClient;
22

3+
using System.Globalization;
34
using System.Threading.Tasks;
45
using HiveMQtt.Client;
56
using HiveMQtt.Client.Events;
@@ -161,7 +162,7 @@ public async Task Test_AfterDisconnectEvent_Async()
161162
// Assert that all Events were called
162163
Assert.True(client.LocalStore.ContainsKey("AfterDisconnectHandlerCalled"));
163164
Assert.True(client.LocalStore.ContainsKey("AfterDisconnectHandlerCalledCount"));
164-
Assert.Equal(client.LocalStore["AfterDisconnectHandlerCalledCount"], "1");
165+
Assert.Equal("1", client.LocalStore["AfterDisconnectHandlerCalledCount"]);
165166

166167
// Remove event handlers
167168
client.AfterDisconnect -= AfterDisconnectHandler;
@@ -232,11 +233,11 @@ private static void AfterDisconnectHandler(object? sender, AfterDisconnectEventA
232233
{
233234
var client = (HiveMQClient)sender;
234235

235-
if (client.LocalStore.ContainsKey("AfterDisconnectHandlerCalled"))
236+
if (client.LocalStore.TryGetValue("AfterDisconnectHandlerCalled", out var value))
236237
{
237-
var count = Convert.ToInt16(client.LocalStore["AfterDisconnectHandlerCalledCount"]);
238+
var count = Convert.ToInt16(value, CultureInfo.InvariantCulture);
238239
count++;
239-
client.LocalStore.Add("AfterDisconnectHandlerCalledCount", count.ToString());
240+
client.LocalStore.Add("AfterDisconnectHandlerCalledCount", count.ToString(CultureInfo.InvariantCulture));
240241
}
241242
else
242243
{
@@ -253,11 +254,11 @@ private static void OnDisconnectSentHandler(object? sender, OnDisconnectSentEven
253254
{
254255
var client = (HiveMQClient)sender;
255256

256-
if (client.LocalStore.ContainsKey("OnDisconnectSentHandlerCalled"))
257+
if (client.LocalStore.TryGetValue("OnDisconnectSentHandlerCalled", out var value))
257258
{
258-
var count = Convert.ToInt16(client.LocalStore["OnDisconnectSentHandlerCalledCount"]);
259+
var count = Convert.ToInt16(value, CultureInfo.InvariantCulture);
259260
count++;
260-
client.LocalStore.Add("OnDisconnectSentHandlerCalledCount", count.ToString());
261+
client.LocalStore.Add("OnDisconnectSentHandlerCalledCount", count.ToString(CultureInfo.InvariantCulture));
261262
}
262263
else
263264
{

0 commit comments

Comments
 (0)