Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge latest from main #2895

Merged
merged 13 commits into from
Oct 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion e2e/test/iothub/service/IoTHubServiceProxyE2ETests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ public async Task ServiceClientDevices_AddAndRemoveDevice_WithProxy()

[Ignore]
[LoggedTestMethod]
[Timeout(TestTimeoutMilliseconds)]
[TestCategory("LongRunning")]
[Timeout(LongRunningTestTimeoutMilliseconds)]
public async Task JobClient_ScheduleAndRunTwinJob_WithProxy()
{
const string JobDeviceId = "JobsSample_Device";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,4 @@ output dpsConnectionString string = 'HostName=${DpsName}.azure-devices-provision
output storageAccountConnectionString string = 'DefaultEndpointsProtocol=https;AccountName=${StorageAccountName};AccountKey=${listkeys(storageAccount.id, '2019-06-01').keys[0].value};EndpointSuffix=core.windows.net'
output workspaceId string = (EnableIotHubSecuritySolution) ? '${reference(operationalInsightsWorkspaces.id, '2017-03-15-preview').customerId}' : ''
output keyVaultName string = KeyVaultName
output instrumentationKey string = reference(applicationInsights.id, '2015-05-01').InstrumentationKey
output instrumentationKey string = reference(applicationInsights.id, '2015-05-01').InstrumentationKey
2 changes: 1 addition & 1 deletion e2e/test/prerequisites/E2ETestsSetup/test-resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -387,4 +387,4 @@
"templateHash": "129270437041242196"
}
}
}
}
57 changes: 57 additions & 0 deletions iothub/device/samples/getting started/ReadD2cMessages/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Read device-to-cloud messages

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.
drwill-ms marked this conversation as resolved.
Show resolved Hide resolved

## Prerequisites

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 on your development machine using 'dotnet --version'.

> Note: the Event Hubs client 5.2 does not work with .NET 5.0.

## Obtain the Event Hub-compatible connection string

You can get the Event Hub-compatible connection string to your Iot Hub instance via the Azure portal or by using the Azure CLI.

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.

If using the Azure CLI, you will need to run the below before running this sample to get the details required to form the Event Hubs compatible connection string:

```bash
az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {your IoT Hub name}
az iot hub show --query properties.eventHubEndpoints.events.path --name {your IoT Hub name}
az iot hub policy show --name service --query primaryKey --hub-name {your IoT Hub name}
```

If you can do neither of the above and need to programmatically get this information, the sample [How to request the IoT Hub built-in Event Hubs-compatible endpoint connection string](https://github.com/Azure/azure-sdk-for-net/blob/main/samples/iothub-connect-to-eventhubs/README.md) demonstrates how to do so.

## WebSocket and proxy support

If you would like to use WebSockts, with our without a proxy, you will need to create a set of options for the [`EventHubConsumerClient`](https://docs.microsoft.com/en-us/dotnet/api/azure.messaging.eventhubs.consumer.eventhubconsumerclient?view=azure-dotnet) to configure its behavior. Proxy support is offered via the [`IWebProxy`](https://docs.microsoft.com/dotnet/api/system.net.iwebproxy?view=netcore-3.1) interface, which includes the built-in [`WebProxy`](https://docs.microsoft.com/dotnet/api/system.net.webproxy?view=netcore-3.1) class. Any proxy must be explicitly passed; the client does not assume that any proxy set via the ambient environment or system-wide is desired.

The options may be created as follows:

```csharp
var options = new EventHubConsumerClientOptions();

// This line sets the transport to use WebSockets.
options.ConnectionOptions.TransportType = EventHubsTransportType.AmqpWebSockets;

// The following lines configure the options for proxy use.
IWebProxy proxy = new WebProxy("<< URI TO PROXY >>", true);
options.ConnectionOptions.Proxy = proxy;
```

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:

```csharp
string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName;
await using var consumer = new EventHubConsumerClient(consumerGroup, "<< CONNECTION STRING >>", "<< EVENT HUB >>", options);
```

## Additional Resources

- [Event Hubs Product Documentation](https://docs.microsoft.com/azure/event-hubs/)
- [Event Hubs Client Library Documentation](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventhub/Azure.Messaging.EventHubs/README.md)
- [Event Hubs Samples](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventhub/Azure.Messaging.EventHubs/samples/README.md)
- [Event Processor Client Library Documentation](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventhub/Azure.Messaging.EventHubs.Processor/README.md)
- [Event Processor Samples](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventhub/Azure.Messaging.EventHubs.Processor/samples/README.md)
6 changes: 3 additions & 3 deletions iothub/device/samples/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,6 @@ You need to clone the repository or download the sample (the one you want to try
[m-message-sample]: https://github.com/Azure-Samples/azure-iot-samples-csharp/tree/main/iot-hub/Samples/module/ModuleSample
[lnk-setup-iot-hub]: https://aka.ms/howtocreateazureiothub
[lnk-manage-iot-device]: https://github.com/Azure/azure-iot-device-ecosystem/blob/master/setup_iothub.md#create-new-device-in-the-iot-hub-device-identity-registry
[d-read-d2c-messages-sample]: https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/Getting%20Started/ReadD2cMessages
[d-simulated-device-sample]: https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/Getting%20Started/SimulatedDevice
[d-simulated-device-with-command-sample]: https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/Getting%20Started/SimulatedDeviceWithCommand
[d-read-d2c-messages-sample]: https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/getting%20started/ReadD2cMessages
drwill-ms marked this conversation as resolved.
Show resolved Hide resolved
[d-simulated-device-sample]: https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/getting%20started/SimulatedDevice
[d-simulated-device-with-command-sample]: https://github.com/Azure/azure-iot-sdk-csharp/tree/main/iothub/device/samples/getting%20started/SimulatedDeviceWithCommand
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ private string BuildSignature(string keyName, string key, string target, TimeSpa
SharedAccessSignatureConstants.SignatureFieldName, WebUtility.UrlEncode(signature),
SharedAccessSignatureConstants.ExpiryFieldName, WebUtility.UrlEncode(expiresOn));

if (!keyName.IsNullOrWhiteSpace())
if (!string.IsNullOrWhiteSpace(keyName))
{
buffer.AppendFormat(CultureInfo.InvariantCulture, "&{0}={1}",
SharedAccessSignatureConstants.KeyNameFieldName, WebUtility.UrlEncode(keyName));
Expand Down
2 changes: 1 addition & 1 deletion iothub/device/src/Utilities/ExceptionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ public static IEnumerable<Exception> Unwind(this Exception exception, bool unwin
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.Azure.Devices.Provisioning.Client.Samples
/// <summary>
/// This sample demonstrates how to derive the symmetric key for a particular device enrollment within an enrollment
/// group. Best security practices dictate that the enrollment group level symmetric key should never be saved to a
/// particular device, so this code is deliberately separate from the SymmetricKeySample in this same directory.
/// particular device, so this code is deliberately separate from the SymmetricKeySample in this same directory.
/// Users are advised to run this code to generate the derived symmetric key once, and to save
/// the derived key to the device. Users are not advised to derive the device symmetric key from the enrollment group
/// level key within each device as that is unsecure.
Expand All @@ -26,31 +26,29 @@ public ComputeDerivedKeySample(Parameters parameters)

public void RunSample()
{
string derivedKey = ComputeDerivedSymmetricKey(_parameters.PrimaryKey, _parameters.Id);
string derivedKey = ComputeDerivedSymmetricKey(_parameters.PrimaryKey, _parameters.RegistrationId);

Console.WriteLine("Your derived key is:");
Console.WriteLine(derivedKey);
Console.WriteLine($"Your derived device key is:'{derivedKey}'");
}


/// <summary>
/// Compute a symmetric key for the provisioned device from the enrollment group symmetric key used in attestation.
/// </summary>
/// <param name="enrollmentKey">Enrollment group symmetric key.</param>
/// <param name="deviceId">The device Id of the key to create.</param>
/// <param name="registrationId">The registration Id of the key to create.</param>
/// <returns>The key for the specified device Id registration in the enrollment group.</returns>
/// <seealso>
/// https://docs.microsoft.com/en-us/azure/iot-edge/how-to-auto-provision-symmetric-keys?view=iotedge-2018-06#derive-a-device-key
/// </seealso>
private static string ComputeDerivedSymmetricKey(string enrollmentKey, string deviceId)
private static string ComputeDerivedSymmetricKey(string enrollmentKey, string registrationId)
{
if (string.IsNullOrWhiteSpace(enrollmentKey))
{
return enrollmentKey;
}

using var hmac = new HMACSHA256(Convert.FromBase64String(enrollmentKey));
return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(deviceId)));
return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(registrationId)));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ namespace Microsoft.Azure.Devices.Provisioning.Client.Samples
internal class Parameters
{
[Option(
'd',
"DeviceId",
'r',
drwill-ms marked this conversation as resolved.
Show resolved Hide resolved
"RegistrationId",
Required = true,
HelpText = "The desired device Id of the device that will use this derived key.")]
public string Id { get; set; }
HelpText = "The desired registration Id of the device that will use this derived key.")]
public string RegistrationId { get; set; }

[Option(
'p',
Expand Down