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

Commit 6097ef1

Browse files
author
David R. Williamson
authored
Merge pull request #132 from Azure-Samples/drwill/params
More device samples using param parser.
2 parents 6feb5c9 + eb1f606 commit 6097ef1

File tree

21 files changed

+267
-254
lines changed

21 files changed

+267
-254
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ public DeviceReconnectionSample(List<string> deviceConnectionStrings, TransportT
5555

5656
public async Task RunSampleAsync()
5757
{
58+
Console.WriteLine("Press Control+C to quit the sample.");
5859
using var cts = new CancellationTokenSource();
59-
6060
Console.CancelKeyPress += (sender, eventArgs) =>
6161
{
6262
eventArgs.Cancel = true;

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ namespace Microsoft.Azure.Devices.Client.Samples
1111
{
1212
public class Program
1313
{
14+
/// <summary>
15+
/// A sample for illustrating how a device should handle connection status updates.
16+
/// </summary>
17+
/// <param name="args">
18+
/// Run with `--help` to see a list of required and optional parameters.
19+
/// </param>
1420
public static async Task<int> Main(string[] args)
1521
{
1622
// Parse application parameters

iot-hub/Samples/device/DeviceStreamingSample/DeviceClientStreamingSample.csproj

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>netcoreapp2.0</TargetFramework>
5+
<TargetFramework>netcoreapp3.1</TargetFramework>
66
<LangVersion>8.0</LangVersion>
77
</PropertyGroup>
88

@@ -11,6 +11,7 @@
1111
</ItemGroup>
1212

1313
<ItemGroup>
14+
<PackageReference Include="CommandLineParser" Version="2.8.0" />
1415
<PackageReference Include="System.Net.WebSockets.Client" Version="4.3.2" />
1516
</ItemGroup>
1617

iot-hub/Samples/device/DeviceStreamingSample/DeviceStreamSample.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,23 +37,23 @@ public async Task RunSampleAsync(bool acceptDeviceStreamingRequest = true)
3737
{
3838
await _deviceClient.AcceptDeviceStreamRequestAsync(streamRequest, cts.Token);
3939

40-
using ClientWebSocket webSocket = await DeviceStreamingCommon
41-
.GetStreamingClientAsync(streamRequest.Url, streamRequest.AuthorizationToken, cts.Token);
40+
using ClientWebSocket webSocket = await DeviceStreamingCommon.GetStreamingClientAsync(
41+
streamRequest.Url,
42+
streamRequest.AuthorizationToken,
43+
cts.Token);
4244

4345
WebSocketReceiveResult receiveResult = await webSocket
4446
.ReceiveAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), cts.Token);
4547
Console.WriteLine("Received stream data: {0}", Encoding.UTF8.GetString(buffer, 0, receiveResult.Count));
4648

47-
await webSocket
48-
.SendAsync(
49-
new ArraySegment<byte>(buffer, 0, receiveResult.Count),
50-
WebSocketMessageType.Binary,
51-
true,
52-
cts.Token);
49+
await webSocket.SendAsync(
50+
new ArraySegment<byte>(buffer, 0, receiveResult.Count),
51+
WebSocketMessageType.Binary,
52+
true,
53+
cts.Token);
5354
Console.WriteLine("Sent stream data: {0}", Encoding.UTF8.GetString(buffer, 0, receiveResult.Count));
5455

55-
await webSocket
56-
.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cts.Token);
56+
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cts.Token);
5757
}
5858
}
5959
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
't',
20+
"TransportType",
21+
Default = TransportType.Mqtt,
22+
Required = false,
23+
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.")]
24+
public TransportType TransportType { get; set; }
25+
}
26+
}
Lines changed: 22 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,42 @@
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 System;
56
using System.Threading.Tasks;
67

78
namespace Microsoft.Azure.Devices.Client.Samples
89
{
910
public static class Program
1011
{
11-
// String containing Hostname, Device Id & Device Key in one of the following formats:
12-
// "HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
13-
// "HostName=<iothub_host_name>;CredentialType=SharedAccessSignature;DeviceId=<device_id>;SharedAccessSignature=SharedAccessSignature sr=<iot_host>/devices/<device_id>&sig=<token>&se=<expiry_time>";
14-
15-
// For this sample either
16-
// - pass this value as a command-prompt argument
17-
// - set the IOTHUB_DEVICE_CONN_STRING environment variable
18-
// - create a launchSettings.json (see launchSettings.json.template) containing the variable
19-
private static string s_deviceConnectionString = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_CONN_STRING");
20-
21-
// Specify one of the following transports used by DeviceClient to connect to IoT Hub.
22-
// Mqtt
23-
// Mqtt_WebSocket_Only
24-
// Mqtt_Tcp_Only
25-
// Amqp
26-
// Amqp_WebSocket_Only
27-
// Amqp_Tcp_only
28-
// Http1
29-
private static readonly string s_transportType = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_TRANSPORT_TYPE");
30-
12+
/// <summary>
13+
/// A sample to illustrate device streaming.
14+
/// </summary>
15+
/// <param name="args">
16+
/// Run with `--help` to see a list of required and optional parameters.
17+
/// </param>
3118
public static async Task<int> Main(string[] args)
3219
{
33-
if (string.IsNullOrEmpty(s_deviceConnectionString) && args.Length > 0)
34-
{
35-
s_deviceConnectionString = args[0];
36-
}
37-
38-
if (string.IsNullOrEmpty(s_deviceConnectionString))
39-
{
40-
Console.WriteLine("Please provide a device connection string");
41-
Console.WriteLine("Usage: DeviceClientC2DStreamingSample [iotHubDeviceConnString]");
42-
return 1;
43-
}
44-
45-
using var deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, GetTransportType(args));
20+
// Parse application parameters
21+
Parameters parameters = null;
22+
ParserResult<Parameters> result = Parser.Default.ParseArguments<Parameters>(args)
23+
.WithParsed(parsedParams =>
24+
{
25+
parameters = parsedParams;
26+
})
27+
.WithNotParsed(errors =>
28+
{
29+
Environment.Exit(1);
30+
});
31+
32+
using var deviceClient = DeviceClient.CreateFromConnectionString(
33+
parameters.PrimaryConnectionString,
34+
parameters.TransportType);
4635
var sample = new DeviceStreamSample(deviceClient);
4736
await sample.RunSampleAsync();
4837

4938
Console.WriteLine("Done.");
5039
return 0;
5140
}
52-
53-
private static TransportType GetTransportType(string[] args)
54-
{
55-
// Check environment variable for transport type
56-
if (Enum.TryParse(s_transportType, true, out TransportType transportType))
57-
{
58-
return transportType;
59-
}
60-
61-
// then check argument for transport type
62-
if (args.Length > 1
63-
&& Enum.TryParse(args[1], true, out transportType))
64-
{
65-
return transportType;
66-
}
67-
68-
// otherwise default to MQTT
69-
return TransportType.Mqtt;
70-
}
7141
}
7242
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ public async Task RunSampleAsync()
106106

107107
fileUploadTime.Stop();
108108

109-
Console.WriteLine($"Time to upload file: {fileUploadTime}");
109+
Console.WriteLine($"Time to upload file: {fileUploadTime.Elapsed}.");
110110
}
111111
}
112112
}

iot-hub/Samples/device/FileUploadSample/FileUploadSample.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
</PropertyGroup>
88

99
<ItemGroup>
10+
<PackageReference Include="CommandLineParser" Version="2.8.0" />
1011
<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.28.0" />
1112
</ItemGroup>
1213

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using CommandLine;
2+
3+
namespace Microsoft.Azure.Devices.Client.Samples
4+
{
5+
/// <summary>
6+
/// Parameters for the application.
7+
/// </summary>
8+
internal class Parameters
9+
{
10+
[Option(
11+
'p',
12+
"PrimaryConnectionString",
13+
Required = true,
14+
HelpText = "The primary connection string for the device to simulate.")]
15+
public string PrimaryConnectionString { get; set; }
16+
17+
[Option(
18+
't',
19+
"TransportType",
20+
Default = TransportType.Mqtt,
21+
Required = false,
22+
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.")]
23+
public TransportType TransportType { get; set; }
24+
}
25+
}
Lines changed: 23 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
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 System;
56
using System.Threading.Tasks;
67

@@ -12,58 +13,35 @@ namespace Microsoft.Azure.Devices.Client.Samples
1213
/// </summary>
1314
public class Program
1415
{
15-
// String containing Hostname, Device Id & Device Key in one of the following formats:
16-
// "HostName=<iothub_host_name>;DeviceId=<device_id>;SharedAccessKey=<device_key>"
17-
// "HostName=<iothub_host_name>;CredentialType=SharedAccessSignature;DeviceId=<device_id>;SharedAccessSignature=SharedAccessSignature sr=<iot_host>/devices/<device_id>&sig=<token>&se=<expiry_time>";
18-
19-
// For this sample either
20-
// - pass this value as a command-prompt argument
21-
// - set the IOTHUB_DEVICE_CONN_STRING environment variable
22-
// - create a launchSettings.json (see launchSettings.json.template) containing the variable
23-
private static string s_deviceConnectionString = Environment.GetEnvironmentVariable("IOTHUB_DEVICE_CONN_STRING");
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-
16+
/// <summary>
17+
/// A sample to illustrate how to upload files from a device.
18+
/// </summary>
19+
/// <param name="args">
20+
/// Run with `--help` to see a list of required and optional parameters.
21+
/// </param>
22+
/// <returns></returns>
3523
public static async Task<int> Main(string[] args)
3624
{
37-
if (string.IsNullOrEmpty(s_deviceConnectionString) && args.Length > 0)
38-
{
39-
s_deviceConnectionString = args[0];
40-
}
41-
42-
using var deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, GetTransportType(args));
25+
// Parse application parameters
26+
Parameters parameters = null;
27+
ParserResult<Parameters> result = Parser.Default.ParseArguments<Parameters>(args)
28+
.WithParsed(parsedParams =>
29+
{
30+
parameters = parsedParams;
31+
})
32+
.WithNotParsed(errors =>
33+
{
34+
Environment.Exit(1);
35+
});
36+
37+
using var deviceClient = DeviceClient.CreateFromConnectionString(
38+
parameters.PrimaryConnectionString,
39+
parameters.TransportType);
4340
var sample = new FileUploadSample(deviceClient);
4441
await sample.RunSampleAsync();
4542

4643
Console.WriteLine("Done.");
4744
return 0;
4845
}
49-
50-
private static TransportType GetTransportType(string[] args)
51-
{
52-
// Check environment variable for transport type
53-
if (Enum.TryParse(s_transportType, true, out TransportType transportType))
54-
{
55-
return transportType;
56-
}
57-
58-
// then check argument for transport type
59-
if (args.Length > 1
60-
&& Enum.TryParse(args[1], true, out transportType))
61-
{
62-
return transportType;
63-
}
64-
65-
// otherwise default to MQTT
66-
return TransportType.Mqtt;
67-
}
6846
}
6947
}

0 commit comments

Comments
 (0)