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

Commit 042befa

Browse files
author
David R. Williamson
authored
Merge pull request #172 from Azure-Samples/drwill/ReadD2cMessages
Cleanup ReadD2cMessages sample
2 parents 98ac09e + 49ee93c commit 042befa

File tree

13 files changed

+269
-172
lines changed

13 files changed

+269
-172
lines changed

iot-hub/Quickstarts/back-end-application/back-end-application.csproj renamed to iot-hub/Quickstarts/InvokeDeviceMethod/InvokeDeviceMethod.csproj

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

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

88
<ItemGroup>
9-
<PackageReference Include="Microsoft.Azure.Devices" Version="1.*" />
9+
<PackageReference Include="Microsoft.Azure.Devices" Version="1.28.1" />
1010
</ItemGroup>
1111

1212
</Project>
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
// This application uses the Azure IoT Hub service SDK for .NET
5+
// For samples see: https://github.com/Azure/azure-iot-sdk-csharp/tree/master/iothub/service
6+
7+
using System;
8+
using System.Linq;
9+
using System.Threading.Tasks;
10+
using Microsoft.Azure.Devices;
11+
12+
namespace InvokeDeviceMethod
13+
{
14+
/// <summary>
15+
/// This sample illustrates the very basics of a service app invoking a method on a device.
16+
/// </summary>
17+
internal class Program
18+
{
19+
private static ServiceClient s_serviceClient;
20+
21+
// Connection string for your IoT Hub
22+
// az iot hub show-connection-string --hub-name {your iot hub name} --policy-name service
23+
private static string s_connectionString = "{Your service connection string here}";
24+
25+
private static async Task Main(string[] args)
26+
{
27+
Console.WriteLine("IoT Hub Quickstarts #2 - InvokeDeviceMethod application.");
28+
29+
// This sample accepts the service connection string as a parameter, if present
30+
ValidateConnectionString(args);
31+
32+
// Create a ServiceClient to communicate with service-facing endpoint on your hub.
33+
s_serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString);
34+
35+
await InvokeMethodAsync();
36+
37+
s_serviceClient.Dispose();
38+
39+
Console.WriteLine("\nPress Enter to exit.");
40+
Console.ReadLine();
41+
}
42+
43+
// Invoke the direct method on the device, passing the payload
44+
private static async Task InvokeMethodAsync()
45+
{
46+
var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval")
47+
{
48+
ResponseTimeout = TimeSpan.FromSeconds(30),
49+
};
50+
methodInvocation.SetPayloadJson("10");
51+
52+
// Invoke the direct method asynchronously and get the response from the simulated device.
53+
var response = await s_serviceClient.InvokeDeviceMethodAsync("MyDotnetDevice", methodInvocation);
54+
55+
Console.WriteLine($"\nResponse status: {response.Status}, payload:\n\t{response.GetPayloadAsJson()}");
56+
}
57+
58+
private static void ValidateConnectionString(string[] args)
59+
{
60+
if (args.Any())
61+
{
62+
try
63+
{
64+
var cs = IotHubConnectionStringBuilder.Create(args[0]);
65+
s_connectionString = cs.ToString();
66+
}
67+
catch (Exception)
68+
{
69+
Console.WriteLine($"Error: Unrecognizable parameter '{args[0]}' as connection string.");
70+
Environment.Exit(1);
71+
}
72+
}
73+
else
74+
{
75+
try
76+
{
77+
_ = IotHubConnectionStringBuilder.Create(s_connectionString);
78+
}
79+
catch (Exception)
80+
{
81+
Console.WriteLine("This sample needs a device connection string to run. Program.cs can be edited to specify it, or it can be included on the command-line as the only parameter.");
82+
Environment.Exit(1);
83+
}
84+
}
85+
}
86+
}
87+
}

iot-hub/Quickstarts/Quickstarts.sln

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ Microsoft Visual Studio Solution File, Format Version 12.00
33
# Visual Studio Version 16
44
VisualStudioVersion = 16.0.30717.126
55
MinimumVisualStudioVersion = 15.0.26124.0
6-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "back-end-application", "back-end-application\back-end-application.csproj", "{F029ED62-3E01-429A-8E32-4862990A35E2}"
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InvokeDeviceMethod", "InvokeDeviceMethod\InvokeDeviceMethod.csproj", "{F029ED62-3E01-429A-8E32-4862990A35E2}"
77
EndProject
8-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "read-d2c-messages", "read-d2c-messages\read-d2c-messages.csproj", "{7701514F-DA48-4344-82FE-4C4A1E7577F9}"
8+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ReadD2cMessages", "ReadD2cMessages\ReadD2cMessages.csproj", "{7701514F-DA48-4344-82FE-4C4A1E7577F9}"
99
EndProject
10-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimulatedDevice", "simulated-device\SimulatedDevice.csproj", "{C22BD1F5-D8A7-452A-96C4-FF0C0553EBF3}"
10+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimulatedDevice", "SimulatedDevice\SimulatedDevice.csproj", "{C22BD1F5-D8A7-452A-96C4-FF0C0553EBF3}"
1111
EndProject
12-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimulatedDeviceWithCommand", "simulated-device-2\SimulatedDeviceWithCommand.csproj", "{3B033BD3-38B4-4B92-8871-2787DD7C86CC}"
12+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimulatedDeviceWithCommand", "SimulatedDeviceWithCommand\SimulatedDeviceWithCommand.csproj", "{3B033BD3-38B4-4B92-8871-2787DD7C86CC}"
1313
EndProject
1414
Global
1515
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using CommandLine;
5+
6+
namespace ReadD2cMessages
7+
{
8+
/// <summary>
9+
/// Parameters for the application
10+
/// </summary>
11+
internal class Parameters
12+
{
13+
internal const string IotHubSharedAccessKeyName = "service";
14+
15+
[Option(
16+
'e',
17+
"EventHubCompatibleEndpoint",
18+
HelpText = "The event hub-compatible endpoint from your IoT Hub instance. Use `az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {your IoT Hub name}` to fetch via the Azure CLI.")]
19+
public string EventHubCompatibleEndpoint { get; set; }
20+
21+
[Option(
22+
'n',
23+
"EventHubName",
24+
HelpText = "The event hub-compatible name of your IoT Hub instance. Use `az iot hub show --query properties.eventHubEndpoints.events.path --name {your IoT Hub name}` to fetch via the Azure CLI.")]
25+
public string EventHubName { get; set; }
26+
27+
[Option(
28+
's',
29+
"SharedAccessKey",
30+
HelpText = "A primary or shared access key from your IoT Hub instance, with the 'service' permission. Use `az iot hub policy show --name service --query primaryKey --hub-name {your IoT Hub name}` to fetch via the Azure CLI.")]
31+
public string SharedAccessKey { get; set; }
32+
33+
[Option(
34+
'c',
35+
"EventHubConnectionString",
36+
HelpText = "The connection string to the event hub-compatible endpoint. Use the Azure portal to get this parameter. If this value is provided, all the others are not necessary.")]
37+
public string EventHubConnectionString { get; set; }
38+
39+
internal string GetEventHubConnectionString()
40+
{
41+
return EventHubConnectionString ?? $"Endpoint={EventHubCompatibleEndpoint};SharedAccessKeyName={IotHubSharedAccessKeyName};SharedAccessKey={SharedAccessKey}";
42+
}
43+
}
44+
}
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
// This application uses the Azure Event Hubs Client for .NET
5+
// For samples see: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/eventhub/Azure.Messaging.EventHubs/samples/README.md
6+
// For documentation see: https://docs.microsoft.com/azure/event-hubs/
7+
8+
using Azure.Messaging.EventHubs.Consumer;
9+
using CommandLine;
10+
using System;
11+
using System.Collections.Generic;
12+
using System.Text;
13+
using System.Threading;
14+
using System.Threading.Tasks;
15+
16+
namespace ReadD2cMessages
17+
{
18+
/// <summary>
19+
/// A sample to illustrate reading Device-to-Cloud messages from a service app.
20+
/// </summary>
21+
internal class Program
22+
{
23+
private static Parameters _parameters;
24+
25+
public static async Task Main(string[] args)
26+
{
27+
// Parse application parameters
28+
ParserResult<Parameters> result = Parser.Default.ParseArguments<Parameters>(args)
29+
.WithParsed(parsedParams =>
30+
{
31+
_parameters = parsedParams;
32+
})
33+
.WithNotParsed(errors =>
34+
{
35+
Environment.Exit(1);
36+
});
37+
38+
// Either the connection string must be supplied, or the set of endpoint, name, and shared access key must be.
39+
if (string.IsNullOrWhiteSpace(_parameters.EventHubConnectionString)
40+
&& (string.IsNullOrWhiteSpace(_parameters.EventHubCompatibleEndpoint)
41+
|| string.IsNullOrWhiteSpace(_parameters.EventHubName)
42+
|| string.IsNullOrWhiteSpace(_parameters.SharedAccessKey)))
43+
{
44+
Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(result, null, null));
45+
Environment.Exit(1);
46+
}
47+
48+
Console.WriteLine("IoT Hub Quickstarts - Read device to cloud messages. Ctrl-C to exit.\n");
49+
50+
// Set up a way for the user to gracefully shutdown
51+
using var cts = new CancellationTokenSource();
52+
Console.CancelKeyPress += (sender, eventArgs) =>
53+
{
54+
eventArgs.Cancel = true;
55+
cts.Cancel();
56+
Console.WriteLine("Exiting...");
57+
};
58+
59+
// Run the sample
60+
await ReceiveMessagesFromDeviceAsync(cts.Token);
61+
62+
Console.WriteLine("Cloud message reader finished.");
63+
}
64+
65+
// Asynchronously create a PartitionReceiver for a partition and then start
66+
// reading any messages sent from the simulated client.
67+
private static async Task ReceiveMessagesFromDeviceAsync(CancellationToken ct)
68+
{
69+
string connectionString = _parameters.GetEventHubConnectionString();
70+
71+
// Create the consumer using the default consumer group using a direct connection to the service.
72+
// Information on using the client with a proxy can be found in the README for this quick start, here:
73+
// https://github.com/Azure-Samples/azure-iot-samples-csharp/tree/master/iot-hub/Quickstarts/ReadD2cMessages/README.md#websocket-and-proxy-support
74+
await using var consumer = new EventHubConsumerClient(
75+
EventHubConsumerClient.DefaultConsumerGroupName,
76+
connectionString,
77+
_parameters.EventHubName);
78+
79+
Console.WriteLine("Listening for messages on all partitions.");
80+
81+
try
82+
{
83+
// Begin reading events for all partitions, starting with the first event in each partition and waiting indefinitely for
84+
// events to become available. Reading can be canceled by breaking out of the loop when an event is processed or by
85+
// signaling the cancellation token.
86+
//
87+
// The "ReadEventsAsync" method on the consumer is a good starting point for consuming events for prototypes
88+
// and samples. For real-world production scenarios, it is strongly recommended that you consider using the
89+
// "EventProcessorClient" from the "Azure.Messaging.EventHubs.Processor" package.
90+
//
91+
// More information on the "EventProcessorClient" and its benefits can be found here:
92+
// https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/eventhub/Azure.Messaging.EventHubs.Processor/README.md
93+
await foreach (PartitionEvent partitionEvent in consumer.ReadEventsAsync(ct))
94+
{
95+
Console.WriteLine($"\nMessage received on partition {partitionEvent.Partition.PartitionId}:");
96+
97+
string data = Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray());
98+
Console.WriteLine($"\tMessage body: {data}");
99+
100+
Console.WriteLine("\tApplication properties (set by device):");
101+
foreach (KeyValuePair<string, object> prop in partitionEvent.Data.Properties)
102+
{
103+
Console.WriteLine($"\t\t{prop.Key}: {prop.Value}");
104+
}
105+
106+
Console.WriteLine("\tSystem properties (set by IoT Hub):");
107+
foreach (KeyValuePair<string, object> prop in partitionEvent.Data.SystemProperties)
108+
{
109+
Console.WriteLine($"\t\t{prop.Key}: {prop.Value}");
110+
}
111+
}
112+
}
113+
catch (TaskCanceledException)
114+
{
115+
// This is expected when the token is signaled; it should not be considered an
116+
// error in this scenario.
117+
}
118+
}
119+
}
120+
}

iot-hub/Quickstarts/read-d2c-messages/README.md renamed to iot-hub/Quickstarts/ReadD2cMessages/README.md

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
# Read device-to-cloud messages
22

3-
This sample demonstrates how to use the Azure Event Hubs client library for .NET to read messages sent from a device by using the built-in Event Hub that exists by default for every IoT Hub instance.
3+
This sample demonstrates how to use the Azure Event Hubs client library for .NET to read messages sent from a device by using the built-in Event Hub that exists by default for every IoT Hub instance.
44

55
## Prerequisites
66

7-
The .NET Core SDK 3.0.0 or greater is recommended. You can download the .NET Core SDK for multiple platforms from [.NET](https://www.microsoft.com/net/download/all). You can verify the current version of C# on your development machine using 'dotnet --version'.
7+
The .NET SDK 3.1 is recommended. You can download the .NET Core SDK for multiple platforms from [.NET](https://www.microsoft.com/net/download/all). You can verify the current version of C# on your development machine using 'dotnet --version'.
88

9-
This sample can also be compiled using the NET Core SDK 2.1 SDK if the language version of project is changed to `preview`.
9+
> Note: the Event Hubs client 5.2 does not work with .NET 5.0.
1010
11-
## Obtain the Event Hubs-compatible connection string
11+
## Obtain the Event Hub-compatible connection string
1212

13-
You can get the Event Hubs-compatible connection string to your IotHub instance via the Azure portal or
14-
by using the Azure CLI.
13+
You can get the Event Hub-compatible connection string to your Iot Hub instance via the Azure portal or by using the Azure CLI.
1514

1615
If using the Azure portal, see [Built in endpoints for IotHub](https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-messages-read-builtin#read-from-the-built-in-endpoint) to get the Event Hubs-compatible connection string and assign it to the variable `connectionString` in the sample. You can skip the Azure CLI instructions in the sample after this.
1716

@@ -42,7 +41,7 @@ IWebProxy proxy = new WebProxy("<< URI TO PROXY >>", true);
4241
options.ConnectionOptions.Proxy = proxy;
4342
```
4443

45-
Once you have your options, you'll need to pass them to the client constructor. Each constructor accepts a set of options as the last parameter, such as:
44+
Once you have your options, you'll need to pass them to the client constructor. Each constructor accepts a set of options as the last parameter, such as:
4645

4746
```csharp
4847
string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;

iot-hub/Quickstarts/read-d2c-messages/read-d2c-messages.csproj renamed to iot-hub/Quickstarts/ReadD2cMessages/ReadD2cMessages.csproj

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>netcoreapp2.1</TargetFramework>
5+
<TargetFramework>netcoreapp3.1</TargetFramework>
66
<LangVersion>latest</LangVersion>
7+
<Description></Description>
78
</PropertyGroup>
89

910
<ItemGroup>
10-
<PackageReference Include="Azure.Messaging.EventHubs" Version="5.*" />
11+
<PackageReference Include="Azure.Messaging.EventHubs" Version="5.2" />
12+
<PackageReference Include="CommandLineParser" Version="2.8.0" />
1113
</ItemGroup>
1214

1315
</Project>

iot-hub/Quickstarts/simulated-device/Program.cs renamed to iot-hub/Quickstarts/SimulatedDevice/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ private static async Task Main(string[] args)
4545
{
4646
eventArgs.Cancel = true;
4747
cts.Cancel();
48-
Console.WriteLine("Device simulator exit requested...");
48+
Console.WriteLine("Exiting...");
4949
};
5050

5151
// Run the telemetry loop

iot-hub/Quickstarts/simulated-device-2/Program.cs renamed to iot-hub/Quickstarts/SimulatedDeviceWithCommand/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ private static async Task Main(string[] args)
5151
{
5252
eventArgs.Cancel = true;
5353
cts.Cancel();
54-
Console.WriteLine("Device simulator exit requested...");
54+
Console.WriteLine("Exiting...");
5555
};
5656

5757
// Run the telemetry loop

0 commit comments

Comments
 (0)