### Complete RawClient workflow Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/rawclient/intro A full example demonstrating client configuration, event handler setup, connection, subscription, publishing, and cleanup. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Configure the client var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.hivemq.com") .WithPort(1883) .WithClientId("raw-client-example") .Build(); var client = new RawClient(options); // Setup message handler BEFORE connecting client.OnMessageReceived += (sender, args) => { Console.WriteLine($"[{args.PublishMessage.Topic}]: {args.PublishMessage.PayloadAsString}"); }; // Track connection state changes client.AfterConnect += (sender, args) => Console.WriteLine("Connected to broker"); client.AfterDisconnect += (sender, args) => Console.WriteLine("Disconnected from broker"); try { // Connect var connectResult = await client.ConnectAsync().ConfigureAwait(false); if (connectResult.ReasonCode != ConnAckReasonCode.Success) { Console.WriteLine($"Connection failed: {connectResult.ReasonCode}"); return; } // Subscribe to topics await client.SubscribeAsync("test/topic1", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); await client.SubscribeAsync("test/topic2", QualityOfService.ExactlyOnceDelivery).ConfigureAwait(false); // Publish messages for (var i = 0; i < 10; i++) { await client.PublishAsync("test/topic1", $"Message {i}").ConfigureAwait(false); await Task.Delay(100); } // Wait for messages await Task.Delay(1000); // Disconnect await client.DisconnectAsync().ConfigureAwait(false); } finally { client.Dispose(); } ``` -------------------------------- ### Quick Start with RawClient Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/rawclient/intro Demonstrates the basic lifecycle of a RawClient including message handler setup, connection, subscription, publishing, and disconnection. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Create a RawClient var client = new RawClient(); // Setup a global message handler BEFORE connecting client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message received on {args.PublishMessage.Topic}: {args.PublishMessage.PayloadAsString}"); }; // Connect to the broker var connectResult = await client.ConnectAsync().ConfigureAwait(false); // Subscribe to a topic (RawClient does NOT track this subscription) await client.SubscribeAsync("my/topic", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); // Publish a message await client.PublishAsync("my/topic", "Hello from RawClient!").ConfigureAwait(false); // Disconnect when done await client.DisconnectAsync().ConfigureAwait(false); client.Dispose(); ``` -------------------------------- ### Complete Connection Example Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/connect_options_builder Demonstrates building connection options and applying them to a client connection. ```csharp var connectOptions = new ConnectOptionsBuilder() .WithSessionExpiryInterval(3600) // 1 hour session expiry .WithKeepAlive(60) // 60 second keep alive .WithCleanStart(true) // Start with a clean session .Build(); await client.ConnectAsync(connectOptions); ``` -------------------------------- ### Minimal MQTT Example Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/quickstart A simplified example for testing against a local broker using default settings. ```csharp using HiveMQtt.Client; // Connect to localhost:1883 with defaults var client = new HiveMQClient(); await client.ConnectAsync(); // Publish a message await client.PublishAsync("test/topic", "Hello World!"); // Clean up await client.DisconnectAsync(); client.Dispose(); ``` -------------------------------- ### Comprehensive SubscribeOptionsBuilder Example Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/subscribing Demonstrates all available configuration parameters including NoLocal, RetainAsPublished, and RetainHandling. ```csharp using HiveMQtt.MQTT5.Types; var options = new SubscribeOptionsBuilder() .WithSubscription( "topic1", // Topic QualityOfService.ExactlyOnceDelivery, // Quality of Service Level true, // NoLocal true, // RetainAsPublished RetainHandling.SendAtSubscribe) // RetainHandling .WithUserProperty("property1", "value1") .WithUserProperties( new Dictionary { { "property1", "value1" }, { "property2", "value2" } }) .Build(); ``` -------------------------------- ### Quick Start with HiveMQClient Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/hivemqclient Demonstrates initializing the client, setting up a message handler, connecting to a broker, subscribing to a topic, and publishing a message. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Create a client var client = new HiveMQClient(); // Setup message handler BEFORE subscribing client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message received on {args.PublishMessage.Topic}: {args.PublishMessage.PayloadAsString}"); }; // Connect to the broker var connectResult = await client.ConnectAsync().ConfigureAwait(false); // Subscribe to a topic (tracked in client.Subscriptions) await client.SubscribeAsync("my/topic", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); // Publish a message await client.PublishAsync("my/topic", "Hello from HiveMQClient!").ConfigureAwait(false); // Disconnect when done await client.DisconnectAsync().ConfigureAwait(false); client.Dispose(); ``` -------------------------------- ### Start Host and Send Rebirth Command Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/sparkplug/host-application Starts the host application and publishes a rebirth command to a specific node. ```csharp await host.StartAsync(); await host.PublishRebirthCommandAsync("myGroup", "myNode"); ``` -------------------------------- ### Complete MQTT Workflow Example Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/quickstart Demonstrates the full lifecycle of configuring, connecting, subscribing, and publishing. Ensure message handlers are defined before subscribing to avoid missing retained messages. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // 1. Configure client options var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.hivemq.com") .WithPort(1883) .Build(); var client = new HiveMQClient(options); // 2. Set up message handler BEFORE subscribing client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Message Received: {args.PublishMessage.PayloadAsString}"); }; // 3. Connect to the broker var connectResult = await client.ConnectAsync().ConfigureAwait(false); // 4. Subscribe to topics var subscribeOptions = new SubscribeOptionsBuilder() .WithSubscription("topic1", QualityOfService.AtLeastOnceDelivery) .WithSubscription("topic2", QualityOfService.ExactlyOnceDelivery) .Build(); var subscribeResult = await client.SubscribeAsync(subscribeOptions).ConfigureAwait(false); // 5. Publish a message var publishResult = await client.PublishAsync("topic1/example", "Hello, MQTT!").ConfigureAwait(false); // 6. Disconnect when done await client.DisconnectAsync().ConfigureAwait(false); client.Dispose(); ``` -------------------------------- ### WithCleanStart(bool cleanStart) Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/connect_options_builder Configures whether the connection starts a new session or continues an existing one. ```APIDOC ## WithCleanStart(bool cleanStart) ### Description Specifies whether the Connection starts a new Session or is a continuation of an existing Session. ### Parameters - **cleanStart** (bool) - Required - True to start a new session, false to continue an existing one. ``` -------------------------------- ### Install HiveMQtt Package Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet Use the .NET CLI to add the HiveMQtt package to your project. ```bash dotnet add package HiveMQtt ``` -------------------------------- ### Complete HiveMQClient Implementation Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/hivemqclient A full example demonstrating client configuration, event handling, connection, subscription management, and message publishing. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Configure the client var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.hivemq.com") .WithPort(1883) .WithClientId("hivemqclient-example") .WithAutomaticReconnect(true) .Build(); var client = new HiveMQClient(options); // Setup global message handler client.OnMessageReceived += (sender, args) => { Console.WriteLine($"[{args.PublishMessage.Topic}]: {args.PublishMessage.PayloadAsString}"); }; // Track connection state changes client.AfterConnect += (sender, args) => Console.WriteLine("Connected to broker"); client.AfterDisconnect += (sender, args) => Console.WriteLine("Disconnected from broker"); try { // Connect var connectResult = await client.ConnectAsync().ConfigureAwait(false); if (connectResult.ReasonCode != ConnAckReasonCode.Success) { Console.WriteLine($"Connection failed: {connectResult.ReasonCode}"); return; } // Subscribe with per-subscription callbacks var subscribeOptions = new SubscribeOptionsBuilder() .WithSubscription( new TopicFilter("sensors/temperature", QualityOfService.AtLeastOnceDelivery), (sender, args) => Console.WriteLine($"Temperature: {args.PublishMessage.PayloadAsString}")) .WithSubscription( new TopicFilter("sensors/humidity", QualityOfService.AtLeastOnceDelivery), (sender, args) => Console.WriteLine($"Humidity: {args.PublishMessage.PayloadAsString}")) .Build(); await client.SubscribeAsync(subscribeOptions).ConfigureAwait(false); // View tracked subscriptions Console.WriteLine($"Active subscriptions: {client.Subscriptions.Count}"); // Publish messages for (var i = 0; i < 10; i++) { await client.PublishAsync("sensors/temperature", $"{20 + i}°C").ConfigureAwait(false); await Task.Delay(100); } // Wait for messages await Task.Delay(1000); // Unsubscribe by topic await client.UnsubscribeAsync("sensors/temperature").ConfigureAwait(false); // Disconnect await client.DisconnectAsync().ConfigureAwait(false); } finally { client.Dispose(); } ``` -------------------------------- ### Trace Level Log Output Example Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/configure-logging Example of the verbose output generated when the minlevel is set to Trace, showing packet and event handling activity. ```text 2024-03-14 15:40:18.2252|TRACE|HiveMQtt.Client.HiveMQClient|Trace Level Logging Legend: 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(W)- == ConnectionWriter 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(PW)- == ConnectionPublishWriter 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(R)- == ConnectionReader 2024-03-14 15:40:18.2312|TRACE|HiveMQtt.Client.HiveMQClient| -(RPH)- == ReceivedPacketsHandler 2024-03-14 15:40:18.2320|INFO|HiveMQtt.Client.HiveMQClient|Connecting to broker at 127.0.0.1:1883 2024-03-14 15:40:18.2343|TRACE|HiveMQtt.Client.HiveMQClient|BeforeConnectEventLauncher 2024-03-14 15:40:18.2460|TRACE|HiveMQtt.Client.HiveMQClient|Socket connected to 127.0.0.1:1883 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|Queuing packet for send: HiveMQtt.MQTT5.Packets.ConnectPacket 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(RPH)- Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(R)- ConnectionReader Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|5: ConnectionMonitor Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(RPH)- 0 received packets currently waiting to be processed. 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- ConnectionWriter Starting...Connecting 2024-03-14 15:40:18.2464|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- ConnectionWriter: 1 packets waiting to be sent. 2024-03-14 15:40:18.2476|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- --> Sending ConnectPacket id=0 2024-03-14 15:40:18.2529|TRACE|HiveMQtt.Client.HiveMQClient|OnConnectSentEventLauncher 2024-03-14 15:40:18.2529|TRACE|HiveMQtt.Client.HiveMQClient|-(W)- ConnectionWriter: 0 packets waiting to be sent. 2024-03-14 15:40:18.2732|TRACE|HiveMQtt.Client.HiveMQClient|ReadAsync: Read Buffer Length 11 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.MQTT5.PacketDecoder|PacketDecoder: Decoded Packet: consumed=11, packet=HiveMQtt.MQTT5.Packets.ConnAckPacket id=0 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.Client.HiveMQClient|-(R)- <-- Received ConnAckPacket. Adding to receivedQueue. 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.Client.HiveMQClient|-(RPH)- <-- Received ConnAck id=0 2024-03-14 15:40:18.2765|TRACE|HiveMQtt.Client.HiveMQClient|OnConnAckReceivedEventLauncher 2024-03-14 15:40:18.2775|TRACE|HiveMQtt.Client.HiveMQClient|AfterConnectEventLauncher ``` -------------------------------- ### Install HiveMQ MQTT Client via NuGet Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/intro Use the .NET CLI to add the HiveMQtt package to your project. ```bash dotnet add package HiveMQtt ``` -------------------------------- ### Install HiveMQtt.Sparkplug NuGet package Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/sparkplug/intro Use the .NET CLI to add the Sparkplug extension package to your project. ```bash dotnet add package HiveMQtt.Sparkplug ``` -------------------------------- ### Example: FireFirstMatchingHandler Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/hivemqclient Demonstrates the behavior of FireFirstMatchingHandler where only the first matching subscription handler is executed. ```csharp var options = new HiveMQClientOptionsBuilder() .WithOverlappingSubscriptionBehavior(OverlappingSubscriptionBehavior.FireFirstMatchingHandler) .Build(); var client = new HiveMQClient(options); // Subscribe to overlapping patterns var opts1 = new SubscribeOptions(); opts1.TopicFilters.Add(new TopicFilter("sensors/#", QualityOfService.AtLeastOnceDelivery)); opts1.Handlers["sensors/#"] = (s, e) => Console.WriteLine("Wildcard handler"); await client.SubscribeAsync(opts1); // First subscription var opts2 = new SubscribeOptions(); opts2.TopicFilters.Add(new TopicFilter("sensors/+/temperature", QualityOfService.AtLeastOnceDelivery)); opts2.Handlers["sensors/+/temperature"] = (s, e) => Console.WriteLine("Specific handler"); await client.SubscribeAsync(opts2); // Second subscription // Global handler always fires regardless of setting client.OnMessageReceived += (s, e) => Console.WriteLine("Global handler"); // Publish to sensors/livingroom/temperature // Output: // Global handler // Wildcard handler // (Specific handler does NOT fire - only first match fires) ``` -------------------------------- ### Host Application Implementation Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/sparkplug/quickstart Configure and start a Sparkplug host application to listen for birth messages and publish rebirth commands. ```csharp var clientOptions = new HiveMQClientOptionsBuilder() .WithBroker("localhost") .WithPort(1883) .WithClientId("my-host") .Build(); var sparkplugOptions = new SparkplugHostApplicationOptions { SparkplugTopicFilter = "spBv1.0/#", UseStateMessages = false }; var host = new SparkplugHostApplication(clientOptions, sparkplugOptions); host.NodeBirthReceived += (_, e) => Console.WriteLine($"Node birth: {e.Topic.GroupId}/{e.Topic.EdgeNodeId}"); host.DeviceBirthReceived += (_, e) => Console.WriteLine($"Device birth: {e.Topic.DeviceId}"); await host.StartAsync(); await host.PublishRebirthCommandAsync("myGroup", "myNode"); ``` -------------------------------- ### Run HiveMQ Community Edition with Docker Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/intro Start a local MQTT broker instance using the HiveMQ Community Edition Docker image. ```bash docker run --name hivemq-ce -d -p 1883:1883 hivemq/hivemq-ce ``` -------------------------------- ### Configure Clean Start Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/client_options_builder Sets whether the broker should discard previous session state upon connection. ```csharp WithCleanStart(true) ``` -------------------------------- ### Set Clean Start Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/connect_options_builder Determines whether the connection initiates a new session or resumes an existing one. ```csharp .WithCleanStart(true) // Start with a clean session ``` -------------------------------- ### Define Per-Subscription Callbacks Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/subscribing Shows the method signature for adding a callback to a subscription and provides examples using both lambda expressions and named methods. ```csharp public SubscribeOptionsBuilder WithSubscription(TopicFilter topicFilter, EventHandler? handler = null) ``` ```csharp var builder = new SubscribeOptionsBuilder(); var options = builder.WithSubscription( new TopicFilter("test/topic", QualityOfService.AtLeastOnceDelivery), (sender, e) => { Console.WriteLine($"Message received on topic {e.PublishMessage.Topic}: {e.PublishMessage.PayloadAsString}"); }) .Build(); ``` ```csharp private static void MessageHandler(object? sender, OnMessageReceivedEventArgs eventArgs) { Console.WriteLine($"Message Received: {eventArgs.PublishMessage.PayloadAsString}"); } var builder = new SubscribeOptionsBuilder(); var options = builder.WithSubscription( new TopicFilter("test/topic", QualityOfService.AtLeastOnceDelivery), MessageHandler) .Build(); ``` -------------------------------- ### Edge Node Implementation Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/sparkplug/quickstart Configure and start a Sparkplug edge node to handle commands and publish data metrics. ```csharp var clientOptions = new HiveMQClientOptionsBuilder() .WithBroker("localhost") .WithPort(1883) .WithClientId("my-edge-node") .Build(); var sparkplugOptions = new SparkplugEdgeNodeOptions { GroupId = "myGroup", EdgeNodeId = "myNode" }; var edgeNode = new SparkplugEdgeNode(clientOptions, sparkplugOptions); edgeNode.NodeCommandReceived += (_, e) => Console.WriteLine($"NCMD: {e.Payload.Metrics.Count} metrics"); await edgeNode.StartAsync(); var metrics = new[] { SparkplugMetricBuilder.Create("temperature").WithFloatValue(22.5).Build() }; await edgeNode.PublishNodeDataAsync(metrics); ``` -------------------------------- ### Configure and Initialize SparkplugHostApplication Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/sparkplug/host-application Sets up the MQTT client options and Sparkplug host application options required to initialize the host. ```csharp var clientOptions = new HiveMQClientOptionsBuilder() .WithBroker("localhost") .WithPort(1883) .WithClientId("my-host") .Build(); var sparkplugOptions = new SparkplugHostApplicationOptions { SparkplugTopicFilter = "spBv1.0/#", UseStateMessages = false }; var host = new SparkplugHostApplication(clientOptions, sparkplugOptions); ``` -------------------------------- ### Subscriptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/unsubscribe_options Property to get or set the list of subscriptions for the unsubscribe operation. ```APIDOC ## Property ### Subscriptions Gets or sets the list of subscriptions for this unsubscribe operation. ### Example ```csharp options.Subscriptions.Add(new Subscription("home/sensors/temperature", QualityOfService.AtLeastOnce)); ``` ``` -------------------------------- ### Subscribe to Overlapping Topics Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/subscribing Example of subscribing to multiple overlapping topic patterns. ```csharp await client.SubscribeAsync("sensors/#"); // Matches: sensors/temperature/livingroom await client.SubscribeAsync("sensors/+/temperature"); // Matches: sensors/livingroom/temperature ``` -------------------------------- ### Configure ConnectOptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/connect_options Demonstrates initializing ConnectOptions and overriding default connection settings before establishing a connection. ```csharp ConnectOptions connectOptions = new ConnectOptions(); connectOptions.SessionExpiryInterval = 3600; // 1 hour session expiry connectOptions.KeepAlive = 60; // 60 second keep alive connectOptions.CleanStart = true; // Start with a clean session await client.ConnectAsync(connectOptions); ``` -------------------------------- ### UserProperties Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/unsubscribe_options Property to get or set custom user properties for the unsubscribe request. ```APIDOC ## Property ### UserProperties Gets or sets the user properties for the unsubscribe operation. ### Example ```csharp options.UserProperties["reason"] = "No longer needed"; ``` ``` -------------------------------- ### Initialize Configuration in Startup Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/client-certificates Sets up the configuration object within the application startup class. ```csharp using Microsoft.Extensions.Configuration; using System.IO; // Assuming you are in the Startup.cs or a similar setup file public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } // Other configurations... } ``` -------------------------------- ### Async OnMessageReceived Handler Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/message-ordering Example of an async void handler where ordering is only guaranteed until the first await statement. ```csharp client.OnMessageReceived += async (sender, args) => { await SaveToDatabaseAsync(args); // ordering does NOT extend past the first await }; ``` -------------------------------- ### Configure Proxy with RawClient Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/configure-proxy Demonstrates manual proxy configuration using WebProxy for both HiveMQClient and RawClient. ```csharp using System.Net; using HiveMQtt.Client; var proxy = new WebProxy("http://proxy.example.com:8080"); var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.example.com") .WithProxy(proxy) .Build(); // Works with both HiveMQClient and RawClient var rawClient = new RawClient(options); await rawClient.ConnectAsync(); ``` -------------------------------- ### Connect and Publish with HiveMQtt Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet Demonstrates initializing a client with builder options, handling incoming messages via events, and performing basic connect, subscribe, and publish operations. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; // Connect to HiveMQ Cloud (or any MQTT broker) var options = new HiveMQClientOptionsBuilder() .WithBroker("your-cluster.hivemq.cloud") .WithPort(8883) .WithUseTls(true) .WithUserName("your-username") .WithPassword("your-password") .Build(); var client = new HiveMQClient(options); // Handle incoming messages client.OnMessageReceived += (sender, args) => { Console.WriteLine($"Received: {args.PublishMessage.PayloadAsString}"); }; await client.ConnectAsync(); await client.SubscribeAsync("sensors/temperature"); await client.PublishAsync("sensors/temperature", "23.5°C"); ``` -------------------------------- ### Execute HiveMQtt Benchmarks Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/benchmarks Run the benchmark suite using the .NET CLI from the project root. ```bash cd Benchmarks/ClientBenchmarkApp dotnet run ClientBenchmarkApp.csproj -c Release ``` -------------------------------- ### Configure Client Certificate from File Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/client_options_builder Adds a client certificate for authentication by specifying the file path. ```csharp WithClientCertificate("path/to/certificate.pfx", "password") ``` -------------------------------- ### Configure WebSocket Proxy Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/configure-proxy Use WithWebSocketProxy for WebSocket connections. This example shows a basic configuration without authentication. ```csharp using System.Net; using HiveMQtt.Client; // Basic proxy without authentication var options = new HiveMQClientOptionsBuilder() .WithWebSocketServer("wss://broker.example.com:8884/mqtt") .WithWebSocketProxy(new WebProxy("http://proxy.example.com:8080")) .Build(); var client = new HiveMQClient(options); await client.ConnectAsync(); ``` -------------------------------- ### Add Subscription with Options Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/subscribe_options_builder Configure a subscription with specific QoS, local delivery, and retention settings, optionally including a message handler. ```csharp SubscribeOptionsBuilder WithSubscription( string topic, QualityOfService qos, bool? noLocal = null, bool? retainAsPublished = null, RetainHandling? retainHandling = RetainHandling.SendAtSubscribe, EventHandler? messageReceivedHandler = null ); ``` ```csharp builder.WithSubscription( "home/sensors/temperature", QualityOfService.AtLeastOnce, noLocal: true, retainAsPublished: false, retainHandling: RetainHandling.DoNotSendOnSubscribe, messageReceivedHandler: (sender, args) => { Console.WriteLine($"Received message: {args.Message.PayloadAsString}"); }); ``` -------------------------------- ### Connect with Default Options Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/hivemqclient Establishes a connection to localhost on port 1883 using default client settings. ```csharp using HiveMQtt.Client; var client = new HiveMQClient(); var connectResult = await client.ConnectAsync().ConfigureAwait(false); ``` -------------------------------- ### Constructing and Publishing an MQTT5 Message Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/publishing Demonstrates how to instantiate an MQTT5PublishMessage, configure properties like Retain and UserProperties, and send it using PublishAsync. ```csharp var message = new MQTT5PublishMessage { Topic = "topic1/example", Payload = Encoding.UTF8.GetBytes("Hello, World!"), QoS = QualityOfService.AtLeastOnceDelivery, }; message.Retain = true; message.UserProperties.Add("Client-Geo", "-33.8688, 151.2093"); var result = await client.PublishAsync(message); ``` -------------------------------- ### Connect with default settings Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/connecting Establishes a connection to a local broker on localhost port 1883 without additional configuration. ```csharp using HiveMQtt.Client; // Connect var client = new HiveMQClient(); var connectResult = await client.ConnectAsync().ConfigureAwait(false); ``` -------------------------------- ### Configure Proxy via Environment Variables Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/configure-proxy Shows how to retrieve proxy settings from environment variables to avoid hardcoding credentials. ```csharp using System.Net; using HiveMQtt.Client; var proxyUrl = Environment.GetEnvironmentVariable("HTTP_PROXY"); var builder = new HiveMQClientOptionsBuilder() .WithBroker("broker.example.com") .WithPort(1883); if (!string.IsNullOrEmpty(proxyUrl)) { var proxy = new WebProxy(proxyUrl); // Optional: Add credentials from environment var proxyUser = Environment.GetEnvironmentVariable("PROXY_USER"); var proxyPass = Environment.GetEnvironmentVariable("PROXY_PASS"); if (!string.IsNullOrEmpty(proxyUser)) { proxy.Credentials = new NetworkCredential(proxyUser, proxyPass); } builder.WithProxy(proxy); } var options = builder.Build(); var client = new HiveMQClient(options); ``` -------------------------------- ### Initialize MQTT5PublishMessage Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/publish_message Constructors for creating a new publish message instance. ```csharp MQTT5PublishMessage(); ``` ```csharp var message = new MQTT5PublishMessage(); ``` ```csharp MQTT5PublishMessage(string topic, QualityOfService? qos); ``` ```csharp var message = new MQTT5PublishMessage("home/sensors/temperature", QualityOfService.AtLeastOnce); ``` -------------------------------- ### Connect with Basic Credentials Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/connect-with-auth Establishes a TLS-secured connection to an MQTT broker using hardcoded credentials. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.ReasonCodes; var options = new HiveMQClientOptionsBuilder() .WithBroker("your-broker.hivemq.cloud") .WithPort(8883) .WithUseTls(true) .WithUserName("my-username") .WithPassword("my-password") .Build(); var client = new HiveMQClient(options); var connectResult = await client.ConnectAsync().ConfigureAwait(false); if (connectResult.ReasonCode == ConnAckReasonCode.Success) { Console.WriteLine("Connected successfully!"); } ``` -------------------------------- ### Migrate from Plain String to SecureString Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/security Demonstrates the transition from obsolete plain string methods to SecureString to avoid compiler warnings. ```csharp // ⚠️ This generates a compiler warning var options = new HiveMQClientOptionsBuilder() .WithPassword("plain-text-password") // CS0618: Obsolete warning .Build(); // ✅ Use SecureString instead var options = new HiveMQClientOptionsBuilder() .WithPassword(securePassword) .Build(); ``` -------------------------------- ### Build() Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/last_will_and_testament_builder Constructs the LastWillAndTestament instance and validates the configuration. ```APIDOC ## Build() ### Description Constructs the LastWillAndTestament instance and validates the configuration. ### Example var lwt = builder.WithTopic("client/disconnect").WithPayload("Disconnected unexpectedly").WithQualityOfServiceLevel(QualityOfService.ExactlyOnce).WithRetain(true).Build(); ``` -------------------------------- ### Connect with Specific Options Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/hivemqclient Configures client connection parameters such as broker address, port, TLS, and client ID using the builder pattern. ```csharp var options = new HiveMQClientOptionsBuilder() .WithBroker("broker.hivemq.com") .WithPort(8883) .WithUseTls(true) .WithClientId("my-client-id") .Build(); var client = new HiveMQClient(options); var connectResult = await client.ConnectAsync().ConfigureAwait(false); ``` -------------------------------- ### Basic Publishing and Subscribing Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/namespaces Standard pattern for connecting, subscribing to a topic, and publishing a message. ```csharp using HiveMQtt.Client; using HiveMQtt.MQTT5.Types; var client = new HiveMQClient(); await client.ConnectAsync(); await client.SubscribeAsync("topic", QualityOfService.AtLeastOnceDelivery); await client.PublishAsync("topic", "Hello!"); ``` -------------------------------- ### Instantiate X509Certificate2 with Password Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/client-certificates Manually create an X509Certificate2 object with a password before passing it to the builder. ```csharp using HiveMQtt.Client; using System.Security.Cryptography.X509Certificates; var clientCertificate = new X509Certificate2( "path/to/certificate-with-password.pem", "certificate-password"); var options = new HiveMQClientOptionsBuilder() .WithClientCertificate(clientCertificate) .Build(); var client = new HiveMQClient(options); ``` -------------------------------- ### Build() Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/connect_options_builder Constructs and returns the final ConnectOptions instance based on the configured settings. ```APIDOC ## Build() ### Description Creates and returns a new ConnectOptions object with all the configured settings. ### Returns - **ConnectOptions** - The configured options object. ``` -------------------------------- ### WithSubscription(string, QualityOfService, bool?, bool?, RetainHandling?, EventHandler?) Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/subscribe_options_builder Adds a subscription with detailed options including topic, QoS, and specific MQTT subscription flags. ```APIDOC ## WithSubscription(string topic, QualityOfService qos, bool? noLocal, bool? retainAsPublished, RetainHandling? retainHandling, EventHandler? messageReceivedHandler) ### Description Adds a subscription with detailed options. ### Parameters - **topic** (string) - Required - The topic name. - **qos** (QualityOfService) - Required - The QoS level. - **noLocal** (bool?) - Optional - Indicates whether this client receives messages it publishes. - **retainAsPublished** (bool?) - Optional - Determines if the retain flag remains as published. - **retainHandling** (RetainHandling?) - Optional - Defines how retained messages are handled. - **messageReceivedHandler** (EventHandler?) - Optional - A handler for messages received on this subscription. ``` -------------------------------- ### Configure DisconnectOptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/disconnect_options Demonstrates initializing DisconnectOptions and setting various properties before passing them to the DisconnectAsync method. ```csharp DisconnectOptions disconnectOptions = new DisconnectOptions(); disconnectOptions.ReasonCode = DisconnectReasonCode.NormalDisconnection; disconnectOptions.SessionExpiry = 3600; disconnectOptions.ReasonString = "Device power save mode"; disconnectOptions.UserProperties = new Dictionary { { "device-id", "xrw02k-224a" }, { "TZ", "CEST" } }; await client.DisconnectAsync(disconnectOptions); ``` -------------------------------- ### Simple Topic Subscription Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/hivemqclient Demonstrates subscribing to topics with default or specific Quality of Service (QoS) levels and additional MQTT 5.0 subscription options. ```csharp // Subscribe with default options (QoS 0) await client.SubscribeAsync("my/topic").ConfigureAwait(false); // Subscribe with specific QoS await client.SubscribeAsync("my/topic", QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false); // Subscribe with additional options await client.SubscribeAsync( "my/topic", QualityOfService.ExactlyOnceDelivery, noLocal: true, retainAsPublished: true, retainHandling: RetainHandling.SendAtSubscribe ).ConfigureAwait(false); ``` -------------------------------- ### Configure Credentials via appsettings.json Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/connect-with-auth Reads MQTT configuration settings from a standard .NET configuration section. ```csharp // In appsettings.json: // { // "Mqtt": { // "Broker": "your-broker.hivemq.cloud", // "Username": "your-username", // "Password": "your-password" // } // } var mqttConfig = configuration.GetSection("Mqtt"); var options = new HiveMQClientOptionsBuilder() .WithBroker(mqttConfig["Broker"]) .WithPort(8883) .WithUseTls(true) .WithUserName(mqttConfig["Username"]) .WithPassword(mqttConfig["Password"]) .Build(); ``` -------------------------------- ### Initialize SubscribeOptionsBuilder Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/subscribe_options_builder Instantiate the builder to begin configuring subscription options. ```csharp SubscribeOptionsBuilder(); ``` ```csharp var builder = new SubscribeOptionsBuilder(); ``` -------------------------------- ### Enable Detailed Logging Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/help Configure NLog to output TRACE level logs for troubleshooting purposes. ```text // Add NLog.config to your project with TRACE level ``` -------------------------------- ### Build ConnectOptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/connect_options_builder Constructs a new ConnectOptions instance using the configured builder settings. ```csharp ConnectOptions options = new ConnectOptionsBuilder() .WithSessionExpiryInterval(3600) .WithKeepAlive(60) .WithCleanStart(true) .Build(); ``` -------------------------------- ### Acknowledge by Event Args Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/manual-ack Recommended approach for mixed QoS subscriptions; it safely handles QoS 0 (no-op) and QoS 1/2 messages. ```csharp client.OnMessageReceived += async (sender, args) => { // Process the message (e.g. persist, forward)... await ProcessMessageAsync(args.PublishMessage); // Safe for any QoS: no-op for QoS 0, sends PubAck/PubRec for QoS 1/2 await client.AckAsync(args); }; ``` -------------------------------- ### Initialize LastWillAndTestament with binary payload Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/last_will_and_testament Creates a new instance using a byte array for the payload. ```csharp LastWillAndTestament(string topic, byte[] payload, QualityOfService qos = QualityOfService.AtMostOnceDelivery, bool retain = false); ``` ```csharp var lwt = new LastWillAndTestament("disconnect/topic", Encoding.UTF8.GetBytes("Client disconnected"), QualityOfService.ExactlyOnce, true); ``` -------------------------------- ### Build LastWillAndTestament instance Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/last_will_and_testament_builder Constructs the LastWillAndTestament instance and validates the configuration. ```csharp LastWillAndTestament Build(); ``` ```csharp var lwt = builder .WithTopic("client/disconnect") .WithPayload("Disconnected unexpectedly") .WithQualityOfServiceLevel(QualityOfService.ExactlyOnce) .WithRetain(true) .Build(); ``` -------------------------------- ### Configure Proxy via appsettings.json Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/configure-proxy Provides the JSON configuration structure and the C# code to load proxy settings from an appsettings.json file. ```json { "MqttSettings": { "Broker": "broker.example.com", "Port": 1883, "Proxy": { "Enabled": true, "Url": "http://proxy.example.com:8080", "Username": "", "Password": "" } } } ``` ```csharp using System.Net; using HiveMQtt.Client; using Microsoft.Extensions.Configuration; var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var mqttSettings = config.GetSection("MqttSettings"); var builder = new HiveMQClientOptionsBuilder() .WithBroker(mqttSettings["Broker"]) .WithPort(int.Parse(mqttSettings["Port"])); var proxySection = mqttSettings.GetSection("Proxy"); if (proxySection.GetValue("Enabled")) { var proxy = new WebProxy(proxySection["Url"]); var username = proxySection["Username"]; if (!string.IsNullOrEmpty(username)) { proxy.Credentials = new NetworkCredential( username, proxySection["Password"]); } builder.WithProxy(proxy); } var options = builder.Build(); ``` -------------------------------- ### MQTT5PublishMessage Constructors Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/publish_message Initializes a new instance of the MQTT5PublishMessage class. ```APIDOC ## MQTT5PublishMessage() ### Description Initializes a new instance of the MQTT5PublishMessage class. ## MQTT5PublishMessage(string topic, QualityOfService? qos) ### Description Initializes a new instance of the MQTT5PublishMessage class with the specified topic and Quality of Service level. ### Parameters - **topic** (string) - Required - The topic name. - **qos** (QualityOfService?) - Required - The QoS level. ``` -------------------------------- ### Build() Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/subscribe_options_builder Constructs the SubscribeOptions instance and validates the configuration. ```APIDOC ## Build() ### Description Constructs the `SubscribeOptions` instance and validates the configuration. ``` -------------------------------- ### Initialize UnsubscribeOptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/unsubscribe_options Create a new instance of the UnsubscribeOptions class. ```csharp UnsubscribeOptions(); ``` ```csharp var options = new UnsubscribeOptions(); ``` -------------------------------- ### Initialize SubscribeOptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/subscribe_options Create a new instance of the SubscribeOptions class. ```csharp SubscribeOptions(); ``` ```csharp var options = new SubscribeOptions(); ``` -------------------------------- ### Build() Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/client_options_builder Builds the HiveMQClientOptions instance based on the configured options. ```APIDOC ### Build() Builds the HiveMQClientOptions instance based on the configured options. **Example:** `HiveMQClientOptions options = new HiveMQClientOptionsBuilder().WithBroker("mqtt.example.com").WithPort(1883).Build();` ``` -------------------------------- ### Define Certificate Configuration Model Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/client-certificates Creates a C# class to map the certificate settings from the configuration file. ```csharp public class CertificateSettings { public string CertificatePath { get; set; } public string CertificatePassword { get; set; } } ``` -------------------------------- ### Build HiveMQClientOptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/client_options_builder Finalizes the configuration and builds the HiveMQClientOptions instance. ```csharp HiveMQClientOptions options = new HiveMQClientOptionsBuilder().WithBroker("mqtt.example.com").WithPort(1883).Build(); ``` -------------------------------- ### Build SubscribeOptions Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/subscribe_options_builder Finalize the configuration and generate the SubscribeOptions instance. ```csharp SubscribeOptions Build(); ``` ```csharp var options = builder .WithSubscription("home/sensors/temperature", QualityOfService.AtLeastOnce) .WithUserProperty("key", "value") .Build(); options.Validate(); ``` -------------------------------- ### Build() Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/unsubscribe_options_builder Constructs the UnsubscribeOptions instance based on the provided settings. ```APIDOC ## Build() ### Description Validates the builder configuration and creates an instance of `UnsubscribeOptions`. ### Example ```csharp var options = builder .WithSubscription(new Subscription("home/sensors/temperature", QualityOfService.AtLeastOnce)) .WithUserProperty("reason", "No longer needed") .Build(); ``` ``` -------------------------------- ### Configure Credentials via Environment Variables Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/connect-with-auth Retrieves broker and authentication details from system environment variables to avoid hardcoding sensitive data. ```csharp var options = new HiveMQClientOptionsBuilder() .WithBroker(Environment.GetEnvironmentVariable("MQTT_BROKER")) .WithPort(8883) .WithUseTls(true) .WithUserName(Environment.GetEnvironmentVariable("MQTT_USERNAME")) .WithPassword(Environment.GetEnvironmentVariable("MQTT_PASSWORD")) .Build(); ``` -------------------------------- ### LastWillAndTestamentBuilder() Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/last_will_and_testament_builder Initializes a new instance of the LastWillAndTestamentBuilder class. ```APIDOC ## LastWillAndTestamentBuilder() ### Description Initializes a new instance of the LastWillAndTestamentBuilder class. ### Signature `LastWillAndTestamentBuilder()` ``` -------------------------------- ### Configure Multiple Client Certificates Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/client_options_builder Adds a list of X.509 certificates for client authentication. ```csharp WithClientCertificates(new List { new X509Certificate2("path/to/certificate1.pfx", "password"), new X509Certificate2("path/to/certificate2.pfx", "password") }) ``` -------------------------------- ### Subscribe to a topic with QoS Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/subscribing Specify a QualityOfService level when subscribing to a topic. ```csharp using HiveMQtt.MQTT5.Types; // For QualityOfService enum string topic = "my/topic"; QualityOfService qos = QualityOfService.AtLeastOnceDelivery; await client.SubscribeAsync(topic, qos).ConfigureAwait(false); ``` -------------------------------- ### Performance Optimization for QoS 0 Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/rawclient/intro Leverage the fast path for QoS 0 messages by omitting topic aliases and retain flags to minimize validation overhead. ```csharp // This takes the fast path - minimal overhead var message = new MQTT5PublishMessage { Topic = "sensor/data", Payload = sensorData, QoS = QualityOfService.AtMostOnceDelivery, }; var result = await client.PublishAsync(message).ConfigureAwait(false); ``` -------------------------------- ### LastWillAndTestament(string topic, byte[] payload, QualityOfService qos, bool retain) Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/last_will_and_testament Initializes a new instance of the LastWillAndTestament class with a binary payload. ```APIDOC ## Constructor: LastWillAndTestament(string topic, byte[] payload, QualityOfService qos = QualityOfService.AtMostOnceDelivery, bool retain = false) ### Description Initializes a new instance of the LastWillAndTestament class with a binary payload. ### Parameters - **topic** (string) - Required - The topic of the message. - **payload** (byte[]) - Required - The payload in binary format. - **qos** (QualityOfService) - Optional - The QoS level (default: AtMostOnceDelivery). - **retain** (bool) - Optional - Whether the message should be retained by the broker. ### Example ```csharp var lwt = new LastWillAndTestament("disconnect/topic", Encoding.UTF8.GetBytes("Client disconnected"), QualityOfService.ExactlyOnce, true); ``` ``` -------------------------------- ### Initialize LastWillAndTestament with string payload Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/last_will_and_testament Creates a new instance using a UTF-8 encoded string payload. ```csharp LastWillAndTestament(string topic, string payload, QualityOfService qos = QualityOfService.AtMostOnceDelivery, bool retain = false); ``` ```csharp var lwt = new LastWillAndTestament("disconnect/topic", "Client disconnected", QualityOfService.AtLeastOnce, true); ``` -------------------------------- ### Initialize LastWillAndTestamentBuilder Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/last_will_and_testament_builder Instantiate the builder to begin configuring a Last Will and Testament message. ```csharp LastWillAndTestamentBuilder(); ``` ```csharp var builder = new LastWillAndTestamentBuilder(); ``` -------------------------------- ### Configure Certificate Settings in appsettings.json Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/how-to/client-certificates Defines the structure for certificate paths and passwords within a JSON configuration file. ```json { // Other configuration settings "CertificateSettings": { "CertificatePath": "path/to/certificate-with-password.pem", "CertificatePassword": "YourSecurePassword" } } ``` -------------------------------- ### Initialize UnsubscribeOptionsBuilder Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/unsubscribe_options_builder Constructor for creating a new instance of the builder. ```csharp UnsubscribeOptionsBuilder(); ``` ```csharp var builder = new UnsubscribeOptionsBuilder(); ``` -------------------------------- ### Configure Client Certificate Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/reference/client_options_builder Adds an X.509 certificate for client authentication. ```csharp WithClientCertificate(new X509Certificate2("path/to/certificate.pfx", "password")) ``` -------------------------------- ### Build and Execute Subscription Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/subscribing Finalize the options object and pass it to the client's SubscribeAsync method. ```csharp var options = builder.Build(); ``` ```csharp await client.SubscribeAsync(options); ``` -------------------------------- ### Configure Multiple Certificates Source: https://hivemq.github.io/hivemq-mqtt-client-dotnet/docs/hivemqtt/security Chain multiple certificates by calling WithClientCertificate multiple times. ```csharp var options = new HiveMQClientOptionsBuilder() .WithBroker("your-broker.hivemq.cloud") .WithPort(8883) .WithUseTls(true) .WithClientCertificate("path/to/client-cert.pem") .WithClientCertificate("path/to/intermediate-ca.pem") .Build(); ```