Skip to content

Releases: alonf/IoTHubClientGenerator

V0.1.6

06 Jan 02:19
763d8d6

Choose a tag to compare

A pre-release version of the IoT Hub Client Generator library.
This is a C# code generation attribute library that makes it very easy to create an Azure IoT Client.

V0.1.6:

This release fixed some issues and added the ability to use variables' values in attribute properties:
Example for the new option:
private static string CSFromVar="fgserg3456tesrg";
[Device(ConnectionString="[CSFromVar]"] DeviceClient DeviceClient {get;set;}

An example (A full client with Twin properties and messages):

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IoTHubClientGeneratorSDK;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Exceptions;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;

namespace IoTHubClientGeneratorDemo
{
    class Program
    {
        static async Task Main()
        {
            IoTHubClient iotHubClient = new IoTHubClient();
            await iotHubClient.InitIoTHubClientAsync();
            await iotHubClient.RunSampleAsync(TimeSpan.FromMinutes(5));
        }
    }

    [IoTHub(GeneratedSendMethodName = "SendTelemetryAsync")]
    public partial class IoTHubClient
    {
        private static readonly Random RandomGenerator = new();
        private const int TemperatureThreshold = 30;
        private static readonly TimeSpan SleepDuration = TimeSpan.FromSeconds(5);

        [Device(ConnectionString = "%connectionString%")]
        public DeviceClient DeviceClient { get; set; }

        //desired property are created and managed by the source generator
        [Desired("valueFromTheCloud")] private string DesiredPropertyDemo { get; set; }
        [Desired] private string DesiredPropertyAutoNameDemo { get; set; }
        [Reported("valueFromTheDevice")] private string _reportedPropertyDemo;
        [Reported("ReportedPropertyAutoNameDemo", "reportedPropertyAutoNameDemo")] private string _reportedPropertyAutoNameDemo;

        [ConnectionStatus] 
        private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; }
        
        [IoTHubErrorHandler]
        void IoTHubErrorHandler(string errorMessage, Exception exception)
        {
        if(exception is IotHubException {IsTransient: true})
        {
                Console.WriteLine($"An IotHubException was caught, but will try to recover and retry: {exception}");
        }
        if (ExceptionHelper.IsNetworkExceptionChain(exception))
        {
            Console.WriteLine(
                $"A network related exception was caught, but will try to recover and retry: {exception}");
        }
        Console.WriteLine($"{errorMessage}, Exception: {exception.Message}");
        }
        
        [C2DMessage(AutoComplete = true)]
        private async Task OnC2dMessageReceived2(Message receivedMessage)
        {
            Console.WriteLine(
                $"{DateTime.Now}> C2D message callback - message received with Id={receivedMessage.MessageId}.");

            //do something with the message
        }

        [DirectMethod]
        private Task<MethodResponse> WriteToConsoleAsync(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        [DirectMethod(CloudMethodName = "TestMethod")]
        private Task<MethodResponse> WriteToConsole2Async(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        private async Task SendMessagesAsync(CancellationToken cancellationToken)
        {
            int messageCount = 0;

            while (!cancellationToken.IsCancellationRequested)
            {
                ++messageCount;
                var temperature = RandomGenerator.Next(20, 35);
                var humidity = RandomGenerator.Next(60, 80);
                string messagePayload = $"{{\"temperature\":{temperature},\"humidity\":{humidity}}}";
                var properties = new Dictionary<string, string>()
                {
                    {
                        "temperatureAlert", (temperature > TemperatureThreshold) ? "true" : "false"
                    }
                };

                while (true)
                {
                    var succeeded = await SendTelemetryAsync(messagePayload, messageCount.ToString(), cancellationToken, properties);
                    if (succeeded)
                        break;
                    // wait and retry
                    await Task.Delay(SleepDuration, cancellationToken);
                }
                await Task.Delay(SleepDuration, cancellationToken);
            }
        }

        public async Task RunSampleAsync(TimeSpan sampleRunningTime)
        {
            var cts = new CancellationTokenSource(sampleRunningTime);
            Console.CancelKeyPress += (_, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Sample execution cancellation requested; will exit.");
            };

            Console.WriteLine("Sample execution started, press Control+C to quit the sample.");

            try
            {
                await SendMessagesAsync(cts.Token);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unrecoverable exception caught, user action is required, so exiting...: \n{ex}");
            }
        }
    }
}

V0.1.5

30 Dec 21:31
d042ea6

Choose a tag to compare

V0.1.5 Pre-release
Pre-release

A pre-release version of the IoT Hub Client Generator library.
This is a C# code generation attribute library that makes it very easy to create an Azure IoT Client.

An example (A full client with Twin properties and messages):

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IoTHubClientGeneratorSDK;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Exceptions;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;

namespace IoTHubClientGeneratorDemo
{
    class Program
    {
        static async Task Main()
        {
            IoTHubClient iotHubClient = new IoTHubClient();
            await iotHubClient.InitIoTHubClientAsync();
            await iotHubClient.RunSampleAsync(TimeSpan.FromMinutes(5));
        }
    }

    [IoTHub(GeneratedSendMethodName = "SendTelemetryAsync")]
    public partial class IoTHubClient
    {
        private static readonly Random RandomGenerator = new();
        private const int TemperatureThreshold = 30;
        private static readonly TimeSpan SleepDuration = TimeSpan.FromSeconds(5);

        [Device(ConnectionString = "%connectionString%")]
        public DeviceClient DeviceClient { get; set; }

        //desired property are created and managed by the source generator
        [Desired("valueFromTheCloud")] private string DesiredPropertyDemo { get; set; }
        [Desired] private string DesiredPropertyAutoNameDemo { get; set; }
        [Reported("valueFromTheDevice")] private string _reportedPropertyDemo;
        [Reported("ReportedPropertyAutoNameDemo", "reportedPropertyAutoNameDemo")] private string _reportedPropertyAutoNameDemo;

        [ConnectionStatus] 
        private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; }
        
        [IoTHubErrorHandler]
        void IoTHubErrorHandler(string errorMessage, Exception exception)
        {
        if(exception is IotHubException {IsTransient: true})
        {
                Console.WriteLine($"An IotHubException was caught, but will try to recover and retry: {exception}");
        }
        if (ExceptionHelper.IsNetworkExceptionChain(exception))
        {
            Console.WriteLine(
                $"A network related exception was caught, but will try to recover and retry: {exception}");
        }
        Console.WriteLine($"{errorMessage}, Exception: {exception.Message}");
        }
        
        [C2DMessage(AutoComplete = true)]
        private async Task OnC2dMessageReceived2(Message receivedMessage)
        {
            Console.WriteLine(
                $"{DateTime.Now}> C2D message callback - message received with Id={receivedMessage.MessageId}.");

            //do something with the message
        }

        [DirectMethod]
        private Task<MethodResponse> WriteToConsoleAsync(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        [DirectMethod(CloudMethodName = "TestMethod")]
        private Task<MethodResponse> WriteToConsole2Async(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        private async Task SendMessagesAsync(CancellationToken cancellationToken)
        {
            int messageCount = 0;

            while (!cancellationToken.IsCancellationRequested)
            {
                ++messageCount;
                var temperature = RandomGenerator.Next(20, 35);
                var humidity = RandomGenerator.Next(60, 80);
                string messagePayload = $"{{\"temperature\":{temperature},\"humidity\":{humidity}}}";
                var properties = new Dictionary<string, string>()
                {
                    {
                        "temperatureAlert", (temperature > TemperatureThreshold) ? "true" : "false"
                    }
                };

                while (true)
                {
                    var succeeded = await SendTelemetryAsync(messagePayload, messageCount.ToString(), cancellationToken, properties);
                    if (succeeded)
                        break;
                    // wait and retry
                    await Task.Delay(SleepDuration, cancellationToken);
                }
                await Task.Delay(SleepDuration, cancellationToken);
            }
        }

        public async Task RunSampleAsync(TimeSpan sampleRunningTime)
        {
            var cts = new CancellationTokenSource(sampleRunningTime);
            Console.CancelKeyPress += (_, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Sample execution cancellation requested; will exit.");
            };

            Console.WriteLine("Sample execution started, press Control+C to quit the sample.");

            try
            {
                await SendMessagesAsync(cts.Token);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unrecoverable exception caught, user action is required, so exiting...: \n{ex}");
            }
        }
    }
}

V0.1.4

28 Dec 22:41

Choose a tag to compare

V0.1.4 Pre-release
Pre-release

A pre-release version of the IoT Hub Client Generator library and SDK.
This is a C# code generation attribute library that makes it very easy to create an Azure IoT Client.

An example (A full client with Twin properties and messages):

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IoTHubClientGeneratorSDK;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Exceptions;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;

namespace IoTHubClientGeneratorDemo
{
    class Program
    {
        static async Task Main()
        {
            IoTHubClient iotHubClient = new IoTHubClient();
            await iotHubClient.InitIoTHubClientAsync();
            await iotHubClient.RunSampleAsync(TimeSpan.FromMinutes(5));
        }
    }

    [IoTHub(GeneratedSendMethodName = "SendTelemetryAsync")]
    public partial class IoTHubClient
    {
        private static readonly Random RandomGenerator = new();
        private const int TemperatureThreshold = 30;
        private static readonly TimeSpan SleepDuration = TimeSpan.FromSeconds(5);

        [Device(ConnectionString = "%connectionString%")]
        public DeviceClient DeviceClient { get; set; }

        //desired property are created and managed by the source generator
        [Desired("valueFromTheCloud")] private string DesiredPropertyDemo { get; set; }
        [Desired] private string DesiredPropertyAutoNameDemo { get; set; }
        [Reported("valueFromTheDevice")] private string _reportedPropertyDemo;
        [Reported("ReportedPropertyAutoNameDemo", "reportedPropertyAutoNameDemo")] private string _reportedPropertyAutoNameDemo;

        [ConnectionStatus] 
        private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; }
        
        [IoTHubErrorHandler]
        void IoTHubErrorHandler(string errorMessage, Exception exception)
        {
        if(exception is IotHubException {IsTransient: true})
        {
                Console.WriteLine($"An IotHubException was caught, but will try to recover and retry: {exception}");
        }
        if (ExceptionHelper.IsNetworkExceptionChain(exception))
        {
            Console.WriteLine(
                $"A network related exception was caught, but will try to recover and retry: {exception}");
        }
        Console.WriteLine($"{errorMessage}, Exception: {exception.Message}");
        }
        
        [C2DMessage(AutoComplete = true)]
        private async Task OnC2dMessageReceived2(Message receivedMessage)
        {
            Console.WriteLine(
                $"{DateTime.Now}> C2D message callback - message received with Id={receivedMessage.MessageId}.");

            //do something with the message
        }

        [DirectMethod]
        private Task<MethodResponse> WriteToConsoleAsync(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        [DirectMethod(CloudMethodName = "TestMethod")]
        private Task<MethodResponse> WriteToConsole2Async(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        private async Task SendMessagesAsync(CancellationToken cancellationToken)
        {
            int messageCount = 0;

            while (!cancellationToken.IsCancellationRequested)
            {
                ++messageCount;
                var temperature = RandomGenerator.Next(20, 35);
                var humidity = RandomGenerator.Next(60, 80);
                string messagePayload = $"{{\"temperature\":{temperature},\"humidity\":{humidity}}}";
                var properties = new Dictionary<string, string>()
                {
                    {
                        "temperatureAlert", (temperature > TemperatureThreshold) ? "true" : "false"
                    }
                };

                while (true)
                {
                    var succeeded = await SendTelemetryAsync(messagePayload, messageCount.ToString(), cancellationToken, properties);
                    if (succeeded)
                        break;
                    // wait and retry
                    await Task.Delay(SleepDuration, cancellationToken);
                }
                await Task.Delay(SleepDuration, cancellationToken);
            }
        }

        public async Task RunSampleAsync(TimeSpan sampleRunningTime)
        {
            var cts = new CancellationTokenSource(sampleRunningTime);
            Console.CancelKeyPress += (_, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Sample execution cancellation requested; will exit.");
            };

            Console.WriteLine("Sample execution started, press Control+C to quit the sample.");

            try
            {
                await SendMessagesAsync(cts.Token);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unrecoverable exception caught, user action is required, so exiting...: \n{ex}");
            }
        }
    }
}

V0.1.3

28 Dec 21:29

Choose a tag to compare

V0.1.3 Pre-release
Pre-release

A pre-release version of the IoT Hub Client Generator library.
This is a C# code generation library that makes it very easy to create an Azure IoT Client.

An example (A full client with Twin properties and messages):

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IoTHubClientGeneratorSDK;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Exceptions;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;

namespace IoTHubClientGeneratorDemo
{
    class Program
    {
        static async Task Main()
        {
            IoTHubClient iotHubClient = new IoTHubClient();
            await iotHubClient.InitIoTHubClientAsync();
            await iotHubClient.RunSampleAsync(TimeSpan.FromMinutes(5));
        }
    }

    [IoTHub(GeneratedSendMethodName = "SendTelemetryAsync")]
    public partial class IoTHubClient
    {
        private static readonly Random RandomGenerator = new();
        private const int TemperatureThreshold = 30;
        private static readonly TimeSpan SleepDuration = TimeSpan.FromSeconds(5);

        [Device(ConnectionString = "%connectionString%")]
        public DeviceClient DeviceClient { get; set; }

        //desired property are created and managed by the source generator
        [Desired("valueFromTheCloud")] private string DesiredPropertyDemo { get; set; }
        [Desired] private string DesiredPropertyAutoNameDemo { get; set; }
        [Reported("valueFromTheDevice")] private string _reportedPropertyDemo;
        [Reported("ReportedPropertyAutoNameDemo", "reportedPropertyAutoNameDemo")] private string _reportedPropertyAutoNameDemo;

        [ConnectionStatus] 
        private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; }
        
        [IoTHubErrorHandler]
        void IoTHubErrorHandler(string errorMessage, Exception exception)
        {
        if(exception is IotHubException {IsTransient: true})
        {
                Console.WriteLine($"An IotHubException was caught, but will try to recover and retry: {exception}");
        }
        if (ExceptionHelper.IsNetworkExceptionChain(exception))
        {
            Console.WriteLine(
                $"A network related exception was caught, but will try to recover and retry: {exception}");
        }
        Console.WriteLine($"{errorMessage}, Exception: {exception.Message}");
        }
        
        [C2DMessage(AutoComplete = true)]
        private async Task OnC2dMessageReceived2(Message receivedMessage)
        {
            Console.WriteLine(
                $"{DateTime.Now}> C2D message callback - message received with Id={receivedMessage.MessageId}.");

            //do something with the message
        }

        [DirectMethod]
        private Task<MethodResponse> WriteToConsoleAsync(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        [DirectMethod(CloudMethodName = "TestMethod")]
        private Task<MethodResponse> WriteToConsole2Async(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        private async Task SendMessagesAsync(CancellationToken cancellationToken)
        {
            int messageCount = 0;

            while (!cancellationToken.IsCancellationRequested)
            {
                ++messageCount;
                var temperature = RandomGenerator.Next(20, 35);
                var humidity = RandomGenerator.Next(60, 80);
                string messagePayload = $"{{\"temperature\":{temperature},\"humidity\":{humidity}}}";
                var properties = new Dictionary<string, string>()
                {
                    {
                        "temperatureAlert", (temperature > TemperatureThreshold) ? "true" : "false"
                    }
                };

                while (true)
                {
                    var succeeded = await SendTelemetryAsync(messagePayload, messageCount.ToString(), cancellationToken, properties);
                    if (succeeded)
                        break;
                    // wait and retry
                    await Task.Delay(SleepDuration, cancellationToken);
                }
                await Task.Delay(SleepDuration, cancellationToken);
            }
        }

        public async Task RunSampleAsync(TimeSpan sampleRunningTime)
        {
            var cts = new CancellationTokenSource(sampleRunningTime);
            Console.CancelKeyPress += (_, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Sample execution cancellation requested; will exit.");
            };

            Console.WriteLine("Sample execution started, press Control+C to quit the sample.");

            try
            {
                await SendMessagesAsync(cts.Token);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unrecoverable exception caught, user action is required, so exiting...: \n{ex}");
            }
        }
    }
}

V0.1.2

28 Dec 20:16

Choose a tag to compare

V0.1.2 Pre-release
Pre-release

A pre-release version of IoT Hub Client Generator library.
This is a C# code generation library that makes it very easy to create an Azure IoT Client.

An example (A full client with Twin properties and messages):

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IoTHubClientGeneratorSDK;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Exceptions;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;

namespace IoTHubClientGeneratorDemo
{
    class Program
    {
        static async Task Main()
        {
            IoTHubClient iotHubClient = new IoTHubClient();
            await iotHubClient.InitIoTHubClientAsync();
            await iotHubClient.RunSampleAsync(TimeSpan.FromMinutes(5));
        }
    }

    [IoTHub(GeneratedSendMethodName = "SendTelemetryAsync")]
    public partial class IoTHubClient
    {
        private static readonly Random RandomGenerator = new();
        private const int TemperatureThreshold = 30;
        private static readonly TimeSpan SleepDuration = TimeSpan.FromSeconds(5);

        [Device(ConnectionString = "%connectionString%")]
        public DeviceClient DeviceClient { get; set; }

        //desired property are created and managed by the source generator
        [Desired("valueFromTheCloud")] private string DesiredPropertyDemo { get; set; }
        [Desired] private string DesiredPropertyAutoNameDemo { get; set; }
        [Reported("valueFromTheDevice")] private string _reportedPropertyDemo;
        [Reported("ReportedPropertyAutoNameDemo", "reportedPropertyAutoNameDemo")] private string _reportedPropertyAutoNameDemo;

        [ConnectionStatus] 
        private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; }
        
        [IoTHubErrorHandler]
        void IoTHubErrorHandler(string errorMessage, Exception exception)
        {
        if(exception is IotHubException {IsTransient: true})
        {
                Console.WriteLine($"An IotHubException was caught, but will try to recover and retry: {exception}");
        }
        if (ExceptionHelper.IsNetworkExceptionChain(exception))
        {
            Console.WriteLine(
                $"A network related exception was caught, but will try to recover and retry: {exception}");
        }
        Console.WriteLine($"{errorMessage}, Exception: {exception.Message}");
        }
        
        [C2DMessage(AutoComplete = true)]
        private async Task OnC2dMessageReceived2(Message receivedMessage)
        {
            Console.WriteLine(
                $"{DateTime.Now}> C2D message callback - message received with Id={receivedMessage.MessageId}.");

            //do something with the message
        }

        [DirectMethod]
        private Task<MethodResponse> WriteToConsoleAsync(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        [DirectMethod(CloudMethodName = "TestMethod")]
        private Task<MethodResponse> WriteToConsole2Async(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        private async Task SendMessagesAsync(CancellationToken cancellationToken)
        {
            int messageCount = 0;

            while (!cancellationToken.IsCancellationRequested)
            {
                ++messageCount;
                var temperature = RandomGenerator.Next(20, 35);
                var humidity = RandomGenerator.Next(60, 80);
                string messagePayload = $"{{\"temperature\":{temperature},\"humidity\":{humidity}}}";
                var properties = new Dictionary<string, string>()
                {
                    {
                        "temperatureAlert", (temperature > TemperatureThreshold) ? "true" : "false"
                    }
                };

                while (true)
                {
                    var succeeded = await SendTelemetryAsync(messagePayload, messageCount.ToString(), cancellationToken, properties);
                    if (succeeded)
                        break;
                    // wait and retry
                    await Task.Delay(SleepDuration, cancellationToken);
                }
                await Task.Delay(SleepDuration, cancellationToken);
            }
        }

        public async Task RunSampleAsync(TimeSpan sampleRunningTime)
        {
            var cts = new CancellationTokenSource(sampleRunningTime);
            Console.CancelKeyPress += (_, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Sample execution cancellation requested; will exit.");
            };

            Console.WriteLine("Sample execution started, press Control+C to quit the sample.");

            try
            {
                await SendMessagesAsync(cts.Token);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unrecoverable exception caught, user action is required, so exiting...: \n{ex}");
            }
        }
    }
}

V0.1.1

28 Dec 01:49

Choose a tag to compare

V0.1.1 Pre-release
Pre-release

The first pre-release version of IoT Hub Client Generator library.
This is a C# code generation library that makes it very easy to create an Azure IoT Client.

An example (A full client with Twin properties and messages):

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using IoTHubClientGeneratorSDK;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Exceptions;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;

namespace IoTHubClientGeneratorDemo
{
    class Program
    {
        static async Task Main()
        {
            IoTHubClient iotHubClient = new IoTHubClient();
            await iotHubClient.InitIoTHubClientAsync();
            await iotHubClient.RunSampleAsync(TimeSpan.FromMinutes(5));
        }
    }

    [IoTHub(GeneratedSendMethodName = "SendTelemetryAsync")]
    public partial class IoTHubClient
    {
        private static readonly Random RandomGenerator = new();
        private const int TemperatureThreshold = 30;
        private static readonly TimeSpan SleepDuration = TimeSpan.FromSeconds(5);

        [Device(ConnectionString = "%connectionString%")]
        public DeviceClient DeviceClient { get; set; }

        //desired property are created and managed by the source generator
        [Desired("valueFromTheCloud")] private string DesiredPropertyDemo { get; set; }
        [Desired] private string DesiredPropertyAutoNameDemo { get; set; }
        [Reported("valueFromTheDevice")] private string _reportedPropertyDemo;
        [Reported("ReportedPropertyAutoNameDemo", "reportedPropertyAutoNameDemo")] private string _reportedPropertyAutoNameDemo;

        [ConnectionStatus] 
        private (ConnectionStatus Status, ConnectionStatusChangeReason Reason) DeviceConnectionStatus { get; set; }
        
        [IoTHubErrorHandler]
        void IoTHubErrorHandler(string errorMessage, Exception exception)
        {
        if(exception is IotHubException {IsTransient: true})
        {
                Console.WriteLine($"An IotHubException was caught, but will try to recover and retry: {exception}");
        }
        if (ExceptionHelper.IsNetworkExceptionChain(exception))
        {
            Console.WriteLine(
                $"A network related exception was caught, but will try to recover and retry: {exception}");
        }
        Console.WriteLine($"{errorMessage}, Exception: {exception.Message}");
        }
        
        [C2DMessage(AutoComplete = true)]
        private async Task OnC2dMessageReceived2(Message receivedMessage)
        {
            Console.WriteLine(
                $"{DateTime.Now}> C2D message callback - message received with Id={receivedMessage.MessageId}.");

            //do something with the message
        }

        [DirectMethod]
        private Task<MethodResponse> WriteToConsoleAsync(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        [DirectMethod(CloudMethodName = "TestMethod")]
        private Task<MethodResponse> WriteToConsole2Async(MethodRequest methodRequest)
        {
            Console.WriteLine($"\t *** {methodRequest.Name} was called.");
            Console.WriteLine($"\t{methodRequest.DataAsJson}\n");

            return Task.FromResult(new MethodResponse(new byte[0], 200));
        }
        
        private async Task SendMessagesAsync(CancellationToken cancellationToken)
        {
            int messageCount = 0;

            while (!cancellationToken.IsCancellationRequested)
            {
                ++messageCount;
                var temperature = RandomGenerator.Next(20, 35);
                var humidity = RandomGenerator.Next(60, 80);
                string messagePayload = $"{{\"temperature\":{temperature},\"humidity\":{humidity}}}";
                var properties = new Dictionary<string, string>()
                {
                    {
                        "temperatureAlert", (temperature > TemperatureThreshold) ? "true" : "false"
                    }
                };

                while (true)
                {
                    var succeeded = await SendTelemetryAsync(messagePayload, messageCount.ToString(), cancellationToken, properties);
                    if (succeeded)
                        break;
                    // wait and retry
                    await Task.Delay(SleepDuration, cancellationToken);
                }
                await Task.Delay(SleepDuration, cancellationToken);
            }
        }

        public async Task RunSampleAsync(TimeSpan sampleRunningTime)
        {
            var cts = new CancellationTokenSource(sampleRunningTime);
            Console.CancelKeyPress += (_, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cts.Cancel();
                Console.WriteLine("Sample execution cancellation requested; will exit.");
            };

            Console.WriteLine("Sample execution started, press Control+C to quit the sample.");

            try
            {
                await SendMessagesAsync(cts.Token);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unrecoverable exception caught, user action is required, so exiting...: \n{ex}");
            }
        }
    }
}