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

Commit 0f44e89

Browse files
author
David R. Williamson
authored
Merge pull request #110 from Azure-Samples/drwill/serviceSamples
Service samples use best practices and dispose
2 parents ed2e66a + f0cad8f commit 0f44e89

22 files changed

+333
-361
lines changed

iot-hub/Samples/common/DeviceStreamingCommon.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public static class DeviceStreamingCommon
1919
/// <returns>A ClientWebSocket instance connected to the Device Streaming gateway, if successful.</returns>
2020
public static async Task<ClientWebSocket> GetStreamingClientAsync(Uri url, string authorizationToken, CancellationToken cancellationToken)
2121
{
22-
ClientWebSocket wsClient = new ClientWebSocket();
22+
var wsClient = new ClientWebSocket();
2323
wsClient.Options.SetRequestHeader("Authorization", "Bearer " + authorizationToken);
2424

2525
await wsClient.ConnectAsync(url, cancellationToken).ConfigureAwait(false);

iot-hub/Samples/service/CleanUpDevicesSample/CleanUpDevicesSample.cs

Lines changed: 33 additions & 34 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.Linq;
76
using System.Threading;
87
using System.Threading.Tasks;
98

@@ -13,42 +12,42 @@ public class CleanUpDevicesSample
1312
{
1413
private const int QueryBatchSize = 10000;
1514
private const int DeleteBatchSize = 100;
16-
private RegistryManager _rm;
17-
private List<string> _deleteDeviceWithPrefix =
18-
new List<string>{
19-
// C# E2E tests
20-
"E2E_",
21-
22-
// C E2E tests
23-
"e2e_",
24-
"e2e-",
25-
"symmetrickey-registration-id-",
26-
"tpm-registration-id-",
27-
"csdk_",
28-
"someregistrationid-",
29-
"EdgeDeploymentSample_",
30-
};
31-
32-
private List<string> _deleteConfigurationWithPrefix =
33-
new List<string>{
34-
// C# E2E tests
35-
"edgedeploymentsampleconfiguration-",
36-
};
37-
38-
private List<Device> _devicesToDelete = new List<Device>();
39-
private List<Configuration> _configurationsToDelete = new List<Configuration>();
15+
private readonly RegistryManager _rm;
16+
private readonly List<string> _deleteDeviceWithPrefix = new List<string>
17+
{
18+
// C# E2E tests
19+
"E2E_",
20+
21+
// C E2E tests
22+
"e2e_",
23+
"e2e-",
24+
"symmetrickey-registration-id-",
25+
"tpm-registration-id-",
26+
"csdk_",
27+
"someregistrationid-",
28+
"EdgeDeploymentSample_",
29+
};
30+
31+
private readonly List<string> _deleteConfigurationWithPrefix = new List<string>
32+
{
33+
// C# E2E tests
34+
"edgedeploymentsampleconfiguration-",
35+
};
36+
37+
private readonly List<Device> _devicesToDelete = new List<Device>();
38+
private readonly List<Configuration> _configurationsToDelete = new List<Configuration>();
4039

4140

4241
public CleanUpDevicesSample(RegistryManager rm)
4342
{
4443
_rm = rm ?? throw new ArgumentNullException(nameof(rm));
4544
}
4645

47-
public async Task RunSampleAsync()
46+
public async Task RunCleanUpAsync()
4847
{
4948
try
5049
{
51-
await PrintDeviceCount();
50+
await PrintDeviceCountAsync().ConfigureAwait(false);
5251

5352
int devicesDeleted = 0;
5453
Console.WriteLine("Clean up devices:");
@@ -97,9 +96,9 @@ public async Task RunSampleAsync()
9796
_bulkDeleteList.Clear();
9897
}
9998

100-
Console.WriteLine($"-- Total no of devices deleted: {devicesDeleted}");
99+
Console.WriteLine($"-- Total # of devices deleted: {devicesDeleted}");
101100

102-
var configurations = await _rm.GetConfigurationsAsync(100, new CancellationToken()).ConfigureAwait(false);
101+
var configurations = await _rm.GetConfigurationsAsync(100).ConfigureAwait(false);
103102
{
104103
foreach (var configuration in configurations)
105104
{
@@ -108,7 +107,7 @@ public async Task RunSampleAsync()
108107
{
109108
if (configurationId.StartsWith(prefix))
110109
{
111-
_configurationsToDelete.Add(new Configuration(configurationId));
110+
_configurationsToDelete.Add(new Configuration(configurationId));
112111
}
113112
}
114113
}
@@ -121,8 +120,8 @@ public async Task RunSampleAsync()
121120
removeConfigTasks.Add(_rm.RemoveConfigurationAsync(configuration.Id));
122121
});
123122

124-
Task.WaitAll(removeConfigTasks.ToArray());
125-
Console.WriteLine($"-- Total no of configurations deleted: {_configurationsToDelete.Count}");
123+
await Task.WhenAll(removeConfigTasks).ConfigureAwait(false);
124+
Console.WriteLine($"-- Total # of configurations deleted: {_configurationsToDelete.Count}");
126125

127126
}
128127
catch (Exception ex)
@@ -131,7 +130,7 @@ public async Task RunSampleAsync()
131130
}
132131
}
133132

134-
private async Task PrintDeviceCount()
133+
private async Task PrintDeviceCountAsync()
135134
{
136135
string countSqlQuery = "SELECT COUNT() AS numberOfDevices FROM devices";
137136
IQuery countQuery = _rm.CreateQuery(countSqlQuery);
@@ -140,7 +139,7 @@ private async Task PrintDeviceCount()
140139
IEnumerable<string> result = await countQuery.GetNextAsJsonAsync().ConfigureAwait(false);
141140
foreach (var item in result)
142141
{
143-
Console.WriteLine($"Total no of devices on the hub: \n{item}");
142+
Console.WriteLine($"Total # of devices in the hub: \n{item}");
144143
}
145144
}
146145
}
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
55
<TargetFramework>netcoreapp2.1</TargetFramework>
6+
<LangVersion>8</LangVersion>
67
</PropertyGroup>
78

89
<ItemGroup>
9-
<PackageReference Include="Microsoft.Azure.Devices" Version="1.*" />
10+
<PackageReference Include="Microsoft.Azure.Devices" Version="1.20.0" />
1011
</ItemGroup>
1112

1213
</Project>

iot-hub/Samples/service/CleanUpDevicesSample/Program.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using System;
5+
using System.Threading.Tasks;
56

67
namespace Microsoft.Azure.Devices.Samples
78
{
@@ -15,19 +16,19 @@ public class Program
1516
// - create a launchSettings.json (see launchSettings.json.template) containing the variable
1617
private static string s_connectionString = Environment.GetEnvironmentVariable("IOTHUB_CONN_STRING_CSHARP");
1718

18-
public static int Main(string[] args)
19+
public static async Task<int> Main(string[] args)
1920
{
2021
if (args.Length > 0)
2122
{
2223
s_connectionString = args[0];
2324
}
2425

25-
RegistryManager rm = RegistryManager.CreateFromConnectionString(s_connectionString);
26+
using RegistryManager rm = RegistryManager.CreateFromConnectionString(s_connectionString);
2627

2728
var sample = new CleanUpDevicesSample(rm);
28-
sample.RunSampleAsync().GetAwaiter().GetResult();
29+
await sample.RunCleanUpAsync().ConfigureAwait(false);
2930

30-
Console.WriteLine("Done.\n");
31+
Console.WriteLine("Done.");
3132
return 0;
3233
}
3334
}

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

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using System;
5-
using System.Net;
6-
using System.Net.Sockets;
75
using System.Net.WebSockets;
86
using System.Text;
97
using System.Threading;
@@ -14,10 +12,10 @@ namespace Microsoft.Azure.Devices.Samples
1412
{
1513
public class DeviceStreamSample
1614
{
17-
private ServiceClient _serviceClient;
18-
private String _deviceId;
15+
private readonly ServiceClient _serviceClient;
16+
private readonly string _deviceId;
1917

20-
public DeviceStreamSample(ServiceClient deviceClient, String deviceId)
18+
public DeviceStreamSample(ServiceClient deviceClient, string deviceId)
2119
{
2220
_serviceClient = deviceClient;
2321
_deviceId = deviceId;
@@ -27,30 +25,25 @@ public async Task RunSampleAsync()
2725
{
2826
try
2927
{
30-
DeviceStreamRequest deviceStreamRequest = new DeviceStreamRequest(
31-
streamName: "TestStream"
32-
);
28+
var deviceStreamRequest = new DeviceStreamRequest("TestStream");
3329

3430
DeviceStreamResponse result = await _serviceClient.CreateStreamAsync(_deviceId, deviceStreamRequest).ConfigureAwait(false);
3531

36-
Console.WriteLine("Stream response received: Name={0} IsAccepted={1}", deviceStreamRequest.StreamName, result.IsAccepted);
32+
Console.WriteLine($"Stream response received: Name={deviceStreamRequest.StreamName} IsAccepted={result.IsAccepted}");
3733

3834
if (result.IsAccepted)
3935
{
40-
using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
41-
using (var stream = await DeviceStreamingCommon.GetStreamingClientAsync(result.Url, result.AuthorizationToken, cancellationTokenSource.Token).ConfigureAwait(false))
42-
{
43-
byte[] sendBuffer = Encoding.UTF8.GetBytes("Streaming data over a stream...");
44-
byte[] receiveBuffer = new byte[1024];
36+
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
37+
using ClientWebSocket stream = await DeviceStreamingCommon.GetStreamingClientAsync(result.Url, result.AuthorizationToken, cts.Token).ConfigureAwait(false);
4538

46-
await stream.SendAsync(sendBuffer, WebSocketMessageType.Binary, true, cancellationTokenSource.Token).ConfigureAwait(false);
39+
byte[] sendBuffer = Encoding.UTF8.GetBytes("Streaming data over a stream...");
40+
byte[] receiveBuffer = new byte[1024];
4741

48-
Console.WriteLine("Sent stream data: {0}", Encoding.UTF8.GetString(sendBuffer, 0, sendBuffer.Length));
42+
await stream.SendAsync(sendBuffer, WebSocketMessageType.Binary, true, cts.Token).ConfigureAwait(false);
43+
Console.WriteLine($"Sent stream data: {Encoding.UTF8.GetString(sendBuffer, 0, sendBuffer.Length)}");
4944

50-
var receiveResult = await stream.ReceiveAsync(receiveBuffer, cancellationTokenSource.Token).ConfigureAwait(false);
51-
52-
Console.WriteLine("Received stream data: {0}", Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count));
53-
}
45+
var receiveResult = await stream.ReceiveAsync(receiveBuffer, cts.Token).ConfigureAwait(false);
46+
Console.WriteLine($"Received stream data: {Encoding.UTF8.GetString(receiveBuffer, 0, receiveResult.Count)}");
5447
}
5548
else
5649
{
@@ -59,7 +52,7 @@ public async Task RunSampleAsync()
5952
}
6053
catch (Exception ex)
6154
{
62-
Console.WriteLine("Got an exception: {0}", ex);
55+
Console.WriteLine($"Got an exception: {ex}");
6356
throw;
6457
}
6558
}

iot-hub/Samples/service/DeviceStreamingSample/Program.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

44
using System;
5+
using System.Threading.Tasks;
56

67
namespace Microsoft.Azure.Devices.Samples
78
{
@@ -25,7 +26,7 @@ public static class Program
2526
private static TransportType s_transportType = TransportType.Amqp;
2627
//private static TransportType s_transportType = TransportType.Amqp_WebSocket_Only;
2728

28-
public static int Main(string[] args)
29+
public static async Task<int> Main(string[] args)
2930
{
3031
if (string.IsNullOrEmpty(s_connectionString) && args.Length > 0)
3132
{
@@ -45,11 +46,9 @@ public static int Main(string[] args)
4546
return 1;
4647
}
4748

48-
using (ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString, s_transportType))
49-
{
50-
var sample = new DeviceStreamSample(serviceClient, s_deviceId);
51-
sample.RunSampleAsync().GetAwaiter().GetResult();
52-
}
49+
using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString, s_transportType);
50+
var sample = new DeviceStreamSample(serviceClient, s_deviceId);
51+
await sample.RunSampleAsync().ConfigureAwait(false);
5352

5453
Console.WriteLine("Done.\n");
5554
return 0;

iot-hub/Samples/service/DeviceStreamingSample/ServiceClientStreamingSample.csproj

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
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>netcoreapp2.1</TargetFramework>
6+
<LangVersion>8</LangVersion>
67
</PropertyGroup>
78

89
<ItemGroup>
@@ -14,7 +15,7 @@
1415
</ItemGroup>
1516

1617
<ItemGroup>
17-
<PackageReference Include="Microsoft.Azure.Devices" Version="1.27.0-preview-*" />
18+
<PackageReference Include="Microsoft.Azure.Devices" Version="1.27.0-preview-004" />
1819
</ItemGroup>
1920

2021
</Project>

0 commit comments

Comments
 (0)