Skip to content
This repository was archived by the owner on Nov 16, 2023. It is now read-only.

Commit 6feb5c9

Browse files
author
David R. Williamson
authored
Merge pull request #131 from Azure-Samples/drwill/params
Sample using a command-line parser
2 parents c835f29 + e9754eb commit 6feb5c9

File tree

10 files changed

+79
-68
lines changed

10 files changed

+79
-68
lines changed

iot-hub/Samples/device/DeviceReconnectionSample/DeviceReconnectionSample.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,10 @@ public DeviceReconnectionSample(List<string> deviceConnectionStrings, TransportT
4545
throw new ArgumentException("At least one connection string must be provided.", nameof(deviceConnectionStrings));
4646
}
4747
_deviceConnectionStrings = deviceConnectionStrings;
48+
_logger.LogInformation($"Supplied with {_deviceConnectionStrings.Count} connection string(s).");
49+
4850
_transportType = transportType;
51+
_logger.LogInformation($"Using {_transportType} transport.");
4952

5053
InitializeClient();
5154
}
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
55
<TargetFramework>netcoreapp3.1</TargetFramework>
66
<LangVersion>8.0</LangVersion>
7+
<RootNamespace>Microsoft.Azure.Devices.Client.Samples</RootNamespace>
78
</PropertyGroup>
89

910
<ItemGroup>
10-
<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.27.0" />
11-
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.5" />
11+
<PackageReference Include="CommandLineParser" Version="2.8.0" />
12+
<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.28.0" />
13+
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.8" />
1214
</ItemGroup>
1315

1416
</Project>

iot-hub/Samples/device/DeviceReconnectionSample/ExceptionExtensions.cs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
using System;
55
using System.Collections.Generic;
6-
using System.Collections.ObjectModel;
76

87
namespace Microsoft.Azure.Devices.Client.Samples
98
{
@@ -14,22 +13,25 @@ internal static IEnumerable<Exception> Unwind(this Exception exception, bool unw
1413
while (exception != null)
1514
{
1615
yield return exception;
16+
1717
if (!unwindAggregate)
1818
{
1919
exception = exception.InnerException;
2020
continue;
2121
}
22-
ReadOnlyCollection<Exception> excepetions = (exception as AggregateException)?.InnerExceptions;
23-
if (excepetions != null)
22+
23+
if (exception is AggregateException aggEx
24+
&& aggEx.InnerExceptions != null)
2425
{
25-
foreach (Exception ex in excepetions)
26+
foreach (Exception ex in aggEx.InnerExceptions)
2627
{
2728
foreach (Exception innerEx in ex.Unwind(true))
2829
{
2930
yield return innerEx;
3031
}
3132
}
3233
}
34+
3335
exception = exception.InnerException;
3436
}
3537
}

iot-hub/Samples/device/DeviceReconnectionSample/ColorConsoleLogger.cs renamed to iot-hub/Samples/device/DeviceReconnectionSample/Logging/ColorConsoleLogger.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ namespace Microsoft.Azure.Devices.Client.Samples
1010
{
1111
/// <summary>
1212
/// The ILogger implementation for writing color log entries to console.
13+
/// For additional details, see https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger?view=dotnet-plat-ext-3.1.
1314
/// </summary>
1415
public class ColorConsoleLogger : ILogger
1516
{

iot-hub/Samples/device/DeviceReconnectionSample/ColorConsoleLoggerConfiguration.cs renamed to iot-hub/Samples/device/DeviceReconnectionSample/Logging/ColorConsoleLoggerConfiguration.cs

File renamed without changes.

iot-hub/Samples/device/DeviceReconnectionSample/ColorConsoleLoggerExtensions.cs renamed to iot-hub/Samples/device/DeviceReconnectionSample/Logging/ColorConsoleLoggerExtensions.cs

File renamed without changes.

iot-hub/Samples/device/DeviceReconnectionSample/ColorConsoleLoggerProvider.cs renamed to iot-hub/Samples/device/DeviceReconnectionSample/Logging/ColorConsoleLoggerProvider.cs

File renamed without changes.

iot-hub/Samples/device/DeviceReconnectionSample/ConsoleEventListener.cs renamed to iot-hub/Samples/device/DeviceReconnectionSample/Logging/ConsoleEventListener.cs

File renamed without changes.
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
using CommandLine;
2+
using System.Collections.Generic;
3+
4+
namespace Microsoft.Azure.Devices.Client.Samples
5+
{
6+
/// <summary>
7+
/// Parameters for the application.
8+
/// </summary>
9+
internal class Parameters
10+
{
11+
[Option(
12+
'p',
13+
"PrimaryConnectionString",
14+
Required = true,
15+
HelpText = "The primary connection string for the device to simulate.")]
16+
public string PrimaryConnectionString { get; set; }
17+
18+
[Option(
19+
's',
20+
"SecondaryConnectionString",
21+
Required = false,
22+
HelpText = "The secondary connection string for the device to simulate.")]
23+
public string SecondaryConnectionString { get; set; }
24+
25+
[Option(
26+
't',
27+
"TransportType",
28+
Default = TransportType.Mqtt,
29+
Required = false,
30+
HelpText = "The transport to use to communicate with the IoT Hub. Possible values include Mqtt, Mqtt_WebSocket_Only, Mqtt_Tcp_Only, Amqp, Amqp_WebSocket_Only, Amqp_Tcp_only, and Http1.")]
31+
public TransportType TransportType { get; set; }
32+
33+
public List<string> GetConnectionStrings()
34+
{
35+
var cs = new List<string>(2)
36+
{
37+
PrimaryConnectionString,
38+
};
39+
40+
if (!string.IsNullOrWhiteSpace(SecondaryConnectionString))
41+
{
42+
cs.Add(SecondaryConnectionString);
43+
}
44+
45+
return cs;
46+
}
47+
}
48+
}
Lines changed: 16 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,32 @@
11
// Copyright (c) Microsoft. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4+
using CommandLine;
45
using Microsoft.Extensions.Logging;
56
using System;
6-
using System.Collections.Generic;
77
using System.Diagnostics.Tracing;
88
using System.Threading.Tasks;
99

1010
namespace Microsoft.Azure.Devices.Client.Samples
1111
{
1212
public class Program
1313
{
14-
// String containing Hostname, Device Id & Device Key in one of the following formats:
15-
// "HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
16-
// "HostName=<iothub_host_name>;CredentialType=SharedAccessSignature;DeviceId=<device_id>;SharedAccessSignature=SharedAccessSignature sr=<iot_host>/devices/<device_id>&sig=<token>&se=<expiry_time>";
17-
18-
// For this sample either
19-
// - pass this value as a command-prompt argument
20-
// - set the IOTHUB_DEVICE_CONN_STRING environment variable
21-
// - create a launchSettings.json (see launchSettings.json.template) containing the variable
22-
private static string s_deviceConnectionStringPrimary = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_CONN_STRING");
23-
private static string s_deviceConnectionStringSecondary = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_CONN_STRING_SECONDARY");
24-
25-
// Specify one of the following transports used by DeviceClient to connect to IoT Hub.
26-
// Mqtt
27-
// Mqtt_WebSocket_Only
28-
// Mqtt_Tcp_Only
29-
// Amqp
30-
// Amqp_WebSocket_Only
31-
// Amqp_Tcp_only
32-
// Http1
33-
private static readonly string s_transportType = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_TRANSPORT_TYPE");
34-
3514
public static async Task<int> Main(string[] args)
3615
{
37-
// Create a console logger, that logs all events that are categorized at Debug level or higher.
38-
// For additional details, see https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger?view=dotnet-plat-ext-3.1.
39-
ILoggerFactory loggerFactory = new LoggerFactory();
16+
// Parse application parameters
17+
Parameters parameters = null;
18+
ParserResult<Parameters> result = Parser.Default.ParseArguments<Parameters>(args)
19+
.WithParsed(parsedParams =>
20+
{
21+
parameters = parsedParams;
22+
})
23+
.WithNotParsed(errors =>
24+
{
25+
Environment.Exit(1);
26+
});
4027

28+
// Set up logging
29+
ILoggerFactory loggerFactory = new LoggerFactory();
4130
loggerFactory.AddColorConsoleLogger(
4231
new ColorConsoleLoggerConfiguration
4332
{
@@ -49,46 +38,12 @@ public static async Task<int> Main(string[] args)
4938
// Instantiating this seems to do all we need for outputing SDK events to our console log
5039
_ = new ConsoleEventListener(SdkEventProviderPrefix, logger);
5140

52-
var connectionStrings = new List<string>(2);
53-
if (string.IsNullOrEmpty(s_deviceConnectionStringPrimary) && args.Length > 0)
54-
{
55-
s_deviceConnectionStringPrimary = args[0];
56-
}
57-
connectionStrings.Add(s_deviceConnectionStringPrimary);
58-
59-
if (string.IsNullOrEmpty(s_deviceConnectionStringSecondary) && args.Length > 1)
60-
{
61-
s_deviceConnectionStringSecondary = args[1];
62-
}
63-
if (!string.IsNullOrWhiteSpace(s_deviceConnectionStringSecondary))
64-
{
65-
connectionStrings.Add(s_deviceConnectionStringSecondary);
66-
}
67-
68-
var sample = new DeviceReconnectionSample(connectionStrings, GetTransportType(args), logger);
41+
// Run the sample
42+
var sample = new DeviceReconnectionSample(parameters.GetConnectionStrings(), parameters.TransportType, logger);
6943
await sample.RunSampleAsync();
7044

7145
logger.LogInformation("Done.");
7246
return 0;
7347
}
74-
75-
private static TransportType GetTransportType(string[] args)
76-
{
77-
// Check environment variable for transport type
78-
if (Enum.TryParse(s_transportType, true, out TransportType transportType))
79-
{
80-
return transportType;
81-
}
82-
83-
// then check argument for transport type
84-
if (args.Length > 2
85-
&& Enum.TryParse(args[2], true, out transportType))
86-
{
87-
return transportType;
88-
}
89-
90-
// otherwise default to MQTT
91-
return TransportType.Mqtt;
92-
}
9348
}
9449
}

0 commit comments

Comments
 (0)