diff --git a/common/src/Logging.Common.cs b/common/src/Logging.Common.cs index 5854203881..953a824062 100644 --- a/common/src/Logging.Common.cs +++ b/common/src/Logging.Common.cs @@ -399,7 +399,6 @@ public static void DumpBuffer(object thisOrContextObject, byte[] buffer, int off /// The number of bytes to log. /// The calling member. [NonEvent] - [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "Parameters 'thisOrContextObject' and 'memberName' used in NET451; remove when no longer supported.")] public static unsafe void DumpBuffer(object thisOrContextObject, IntPtr bufferPtr, int count, [CallerMemberName] string memberName = null) { Debug.Assert(bufferPtr != IntPtr.Zero); diff --git a/common/src/device/provisioning/transport/ProvisioningSasBuilder.cs b/common/src/device/provisioning/transport/ProvisioningSasBuilder.cs index ddb53688b8..15a502a765 100644 --- a/common/src/device/provisioning/transport/ProvisioningSasBuilder.cs +++ b/common/src/device/provisioning/transport/ProvisioningSasBuilder.cs @@ -103,7 +103,7 @@ public static string BuildSasSignature(string keyName, string key, string target public static string BuildExpiresOn(TimeSpan timeToLive) { - DateTime epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + var epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime expiresOn = DateTime.UtcNow.Add(timeToLive); TimeSpan secondsFromBaseTime = expiresOn.Subtract(epochTime); long seconds = Convert.ToInt64(secondsFromBaseTime.TotalSeconds, CultureInfo.InvariantCulture); diff --git a/common/src/service/HttpClientHelper.cs b/common/src/service/HttpClientHelper.cs index 5cddb9f422..55563952a8 100644 --- a/common/src/service/HttpClientHelper.cs +++ b/common/src/service/HttpClientHelper.cs @@ -882,10 +882,10 @@ internal static HttpMessageHandler CreateDefaultHttpMessageHandler(IWebProxy web #pragma warning disable CA2000 // Dispose objects before losing scope (object is returned by this method, so the caller is responsible for disposing it) #if NETCOREAPP && !NETCOREAPP2_0 && !NETCOREAPP1_0 && !NETCOREAPP1_1 // SocketsHttpHandler is only available in netcoreapp2.1 and onwards - SocketsHttpHandler httpMessageHandler = new SocketsHttpHandler(); + var httpMessageHandler = new SocketsHttpHandler(); httpMessageHandler.SslOptions.EnabledSslProtocols = TlsVersions.Instance.Preferred; #else - HttpClientHandler httpMessageHandler = new HttpClientHandler(); + var httpMessageHandler = new HttpClientHandler(); #if !NET451 httpMessageHandler.SslProtocols = TlsVersions.Instance.Preferred; httpMessageHandler.CheckCertificateRevocationList = TlsVersions.Instance.CertificateRevocationCheck; diff --git a/common/src/service/StringValidationHelper.cs b/common/src/service/StringValidationHelper.cs index 3529463e18..09482b20ed 100644 --- a/common/src/service/StringValidationHelper.cs +++ b/common/src/service/StringValidationHelper.cs @@ -66,9 +66,9 @@ public static bool IsBase64String(string value) return false; } - var lengthNoPadding = value.Length; + int lengthNoPadding = value.Length; value = value.TrimEnd(Base64Padding); - var lengthPadding = value.Length; + int lengthPadding = value.Length; if ((lengthNoPadding - lengthPadding) > 2) { diff --git a/e2e/test/GlobalSuppressions.cs b/e2e/test/GlobalSuppressions.cs new file mode 100644 index 0000000000..2a5b12c82b --- /dev/null +++ b/e2e/test/GlobalSuppressions.cs @@ -0,0 +1,17 @@ +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Style", + "IDE1006:Naming Styles", + Justification = "Missing Async suffix on test method names. Test method names may be misleading when they have the Async suffix. Additionally, not changing test names help to maintain ADO history.", + Scope = "module")] +[assembly: SuppressMessage( + "CodeQuality", + "IDE0079:Remove unnecessary suppression", + Justification = "Each frameworks consider certain suppressions required by other frameworks unnecessary.", + Scope = "module")] diff --git a/e2e/test/config/TestConfiguration.IoTHub.cs b/e2e/test/config/TestConfiguration.IoTHub.cs index 2e2a9264ec..a94b6f093b 100644 --- a/e2e/test/config/TestConfiguration.IoTHub.cs +++ b/e2e/test/config/TestConfiguration.IoTHub.cs @@ -59,7 +59,7 @@ public static string GetIotHubSharedAccessSignature(TimeSpan timeToLive) public static X509Certificate2 GetCertificateWithPrivateKey() { const string hubPfxCert = "IOTHUB_X509_PFX_CERTIFICATE"; - var cert = GetBase64EncodedCertificate(hubPfxCert, defaultValue: string.Empty); + X509Certificate2 cert = GetBase64EncodedCertificate(hubPfxCert, defaultValue: string.Empty); Assert.IsTrue(cert.NotAfter > DateTime.UtcNow, $"The X509 cert from {hubPfxCert} has expired."); return cert; } @@ -67,7 +67,7 @@ public static X509Certificate2 GetCertificateWithPrivateKey() public static X509Certificate2 GetChainDeviceCertificateWithPrivateKey() { const string hubPfxCert = "HUB_CHAIN_DEVICE_PFX_CERTIFICATE"; - var cert = GetBase64EncodedCertificate(hubPfxCert, defaultValue: string.Empty); + X509Certificate2 cert = GetBase64EncodedCertificate(hubPfxCert, defaultValue: string.Empty); Assert.IsTrue(cert.NotAfter > DateTime.UtcNow, $"The X509 cert from {hubPfxCert} has expired."); return cert; } @@ -75,7 +75,7 @@ public static X509Certificate2 GetChainDeviceCertificateWithPrivateKey() public static X509Certificate2 GetRootCACertificate() { const string hubCert = "HUB_CHAIN_ROOT_CA_CERTIFICATE"; - var cert = GetBase64EncodedCertificate(hubCert); + X509Certificate2 cert = GetBase64EncodedCertificate(hubCert); Assert.IsTrue(cert.NotAfter > DateTime.UtcNow, $"The X509 cert from {hubCert} has expired."); return cert; } @@ -83,7 +83,7 @@ public static X509Certificate2 GetRootCACertificate() public static X509Certificate2 GetIntermediate1Certificate() { const string hubCert = "HUB_CHAIN_INTERMEDIATE1_CERTIFICATE"; - var cert = GetBase64EncodedCertificate(hubCert); + X509Certificate2 cert = GetBase64EncodedCertificate(hubCert); Assert.IsTrue(cert.NotAfter > DateTime.UtcNow, $"The X509 cert from {hubCert} has expired."); return cert; } @@ -91,7 +91,7 @@ public static X509Certificate2 GetIntermediate1Certificate() public static X509Certificate2 GetIntermediate2Certificate() { const string hubCert = "HUB_CHAIN_INTERMEDIATE2_CERTIFICATE"; - var cert = GetBase64EncodedCertificate(hubCert); + X509Certificate2 cert = GetBase64EncodedCertificate(hubCert); Assert.IsTrue(cert.NotAfter > DateTime.UtcNow, $"The X509 cert from {hubCert} has expired."); return cert; } @@ -111,7 +111,7 @@ public static X509Certificate2 GetIntermediate2Certificate() private static string GenerateSasToken(string resourceUri, string sharedAccessKey, TimeSpan timeToLive, string policyName = default) { - DateTime epochTime = new DateTime(1970, 1, 1); + var epochTime = new DateTime(1970, 1, 1); DateTime expiresOn = DateTime.UtcNow.Add(timeToLive); TimeSpan secondsFromEpochTime = expiresOn.Subtract(epochTime); long seconds = Convert.ToInt64(secondsFromEpochTime.TotalSeconds, CultureInfo.InvariantCulture); diff --git a/e2e/test/helpers/StorageContainer.cs b/e2e/test/helpers/StorageContainer.cs index d763128d2f..28b7b24330 100644 --- a/e2e/test/helpers/StorageContainer.cs +++ b/e2e/test/helpers/StorageContainer.cs @@ -136,7 +136,7 @@ protected virtual void Dispose(bool disposing) private async Task InitializeAsync() { - CloudStorageAccount storageAccount = CloudStorageAccount.Parse(TestConfiguration.Storage.ConnectionString); + var storageAccount = CloudStorageAccount.Parse(TestConfiguration.Storage.ConnectionString); CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer = cloudBlobClient.GetContainerReference(ContainerName); await CloudBlobContainer.CreateIfNotExistsAsync().ConfigureAwait(false); diff --git a/e2e/test/helpers/TestDevice.cs b/e2e/test/helpers/TestDevice.cs index 659e5fd770..ef3be3a394 100644 --- a/e2e/test/helpers/TestDevice.cs +++ b/e2e/test/helpers/TestDevice.cs @@ -75,7 +75,7 @@ private static async Task CreateDeviceAsync(TestDeviceType type, str string deviceName = "E2E_" + prefix + Guid.NewGuid(); // Delete existing devices named this way and create a new one. - using RegistryManager rm = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var rm = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); s_logger.Trace($"{nameof(GetTestDeviceAsync)}: Creating device {deviceName} with type {type}."); Client.IAuthenticationMethod auth = null; diff --git a/e2e/test/iothub/AuthenticationWithTokenRefreshDisposalTests.cs b/e2e/test/iothub/AuthenticationWithTokenRefreshDisposalTests.cs index a594c29e9d..b133b8c474 100644 --- a/e2e/test/iothub/AuthenticationWithTokenRefreshDisposalTests.cs +++ b/e2e/test/iothub/AuthenticationWithTokenRefreshDisposalTests.cs @@ -105,7 +105,7 @@ private async Task AuthenticationMethodDisposesTokenRefresher(Client.TransportTy var authenticationMethod = new DeviceAuthenticationSasToken(testDevice.ConnectionString, disposeWithClient: true); // Create an instance of the device client, send a test message and then close and dispose it. - DeviceClient deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); + var deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message1 = new Client.Message(); await deviceClient.SendEventAsync(message1).ConfigureAwait(false); await deviceClient.CloseAsync(); @@ -115,7 +115,7 @@ private async Task AuthenticationMethodDisposesTokenRefresher(Client.TransportTy // Perform the same steps again, reusing the previously created authentication method instance. // Since the default behavior is to dispose AuthenticationWithTokenRefresh authentication method on DeviceClient disposal, // this should now throw an ObjectDisposedException. - DeviceClient deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); + var deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message2 = new Client.Message(); Func act = async () => await deviceClient2.SendEventAsync(message2).ConfigureAwait(false); @@ -131,7 +131,7 @@ private async Task ReuseAuthenticationMethod_SingleDevice(Client.TransportType t var authenticationMethod = new DeviceAuthenticationSasToken(testDevice.ConnectionString, disposeWithClient: false); // Create an instance of the device client, send a test message and then close and dispose it. - DeviceClient deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); + var deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message1 = new Client.Message(); await deviceClient.SendEventAsync(message1).ConfigureAwait(false); await deviceClient.CloseAsync(); @@ -139,8 +139,8 @@ private async Task ReuseAuthenticationMethod_SingleDevice(Client.TransportType t Logger.Trace("Test with instance 1 completed"); // Perform the same steps again, reusing the previously created authentication method instance to ensure - // that the sdk did not dispose the user supplied authentication method instance. - DeviceClient deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); + // that the SDK did not dispose the user supplied authentication method instance. + var deviceClient2 = DeviceClient.Create(testDevice.IoTHubHostName, authenticationMethod, transport); using var message2 = new Client.Message(); await deviceClient2.SendEventAsync(message2).ConfigureAwait(false); await deviceClient2.CloseAsync(); @@ -182,7 +182,7 @@ private async Task ReuseAuthenticationMethod_MuxedDevices(Client.TransportType t for (int i = 0; i < devicesCount; i++) { #pragma warning disable CA2000 // Dispose objects before losing scope - the client instance is disposed during the course of the test. - DeviceClient deviceClient = DeviceClient.Create(testDevices[i].IoTHubHostName, authenticationMethods[i], new ITransportSettings[] { amqpTransportSettings }); + var deviceClient = DeviceClient.Create(testDevices[i].IoTHubHostName, authenticationMethods[i], new ITransportSettings[] { amqpTransportSettings }); #pragma warning restore CA2000 // Dispose objects before losing scope var amqpConnectionStatusChange = new AmqpConnectionStatusChange(testDevices[i].Id, Logger); @@ -246,7 +246,13 @@ private async Task ReuseAuthenticationMethod_MuxedDevices(Client.TransportType t for (int i = 0; i < devicesCount; i++) { #pragma warning disable CA2000 // Dispose objects before losing scope - the client instance is disposed at the end of the test. - DeviceClient deviceClient = DeviceClient.Create(testDevices[i].IoTHubHostName, authenticationMethods[i], new ITransportSettings[] { amqpTransportSettings }); + var deviceClient = DeviceClient.Create( + testDevices[i].IoTHubHostName, + authenticationMethods[i], + new ITransportSettings[] + { + amqpTransportSettings + }); #pragma warning restore CA2000 // Dispose objects before losing scope var amqpConnectionStatusChange = new AmqpConnectionStatusChange(testDevices[i].Id, Logger); diff --git a/e2e/test/iothub/ConnectionStatusChangeHandlerTests.cs b/e2e/test/iothub/ConnectionStatusChangeHandlerTests.cs index 92e1cca9ae..b044d2356f 100644 --- a/e2e/test/iothub/ConnectionStatusChangeHandlerTests.cs +++ b/e2e/test/iothub/ConnectionStatusChangeHandlerTests.cs @@ -116,7 +116,7 @@ private async Task DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base( ConnectionStatusChangeReason? statusChangeReason = null; int deviceDisabledReceivedCount = 0; - using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, protocol)) + using (var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, protocol)) { ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { @@ -135,11 +135,11 @@ private async Task DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base( // Receiving the module twin should succeed right now. Logger.Trace($"{nameof(DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base)}: DeviceClient GetTwinAsync."); - var twin = await deviceClient.GetTwinAsync().ConfigureAwait(false); + Shared.Twin twin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.IsNotNull(twin); // Delete/disable the device in IoT Hub. This should trigger the ConnectionStatusChangesHandler. - using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString)) + using (var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString)) { await registryManagerOperation(registryManager, deviceId).ConfigureAwait(false); } @@ -168,8 +168,8 @@ private async Task DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base( private async Task ModuleClient_Gives_ConnectionStatus_DeviceDisabled_Base( Client.TransportType protocol, Func registryManagerOperation) { - AmqpTransportSettings amqpTransportSettings = new AmqpTransportSettings(protocol); - ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings }; + var amqpTransportSettings = new AmqpTransportSettings(protocol); + var transportSettings = new ITransportSettings[] { amqpTransportSettings }; TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix + $"_{Guid.NewGuid()}", ModulePrefix, Logger).ConfigureAwait(false); ConnectionStatus? status = null; @@ -185,7 +185,7 @@ private async Task ModuleClient_Gives_ConnectionStatus_DeviceDisabled_Base( } }; - using (ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings)) + using (var moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transportSettings)) { moduleClient.SetConnectionStatusChangesHandler(statusChangeHandler); Logger.Trace($"{nameof(ModuleClient_Gives_ConnectionStatus_DeviceDisabled_Base)}: Created {nameof(ModuleClient)} with moduleId={testModule.Id}"); @@ -194,11 +194,11 @@ private async Task ModuleClient_Gives_ConnectionStatus_DeviceDisabled_Base( // Receiving the module twin should succeed right now. Logger.Trace($"{nameof(ModuleClient_Gives_ConnectionStatus_DeviceDisabled_Base)}: ModuleClient GetTwinAsync."); - var twin = await moduleClient.GetTwinAsync().ConfigureAwait(false); + Shared.Twin twin = await moduleClient.GetTwinAsync().ConfigureAwait(false); Assert.IsNotNull(twin); // Delete/disable the device in IoT Hub. - using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString)) + using (var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString)) { await registryManagerOperation(registryManager, testModule.DeviceId).ConfigureAwait(false); } diff --git a/e2e/test/iothub/DeviceClientX509AuthenticationE2ETests.cs b/e2e/test/iothub/DeviceClientX509AuthenticationE2ETests.cs index 9f367eded3..fc7d5de7fe 100644 --- a/e2e/test/iothub/DeviceClientX509AuthenticationE2ETests.cs +++ b/e2e/test/iothub/DeviceClientX509AuthenticationE2ETests.cs @@ -159,7 +159,7 @@ public async Task X509_Cert_Chain_Install_Test_MQTT_TCP() TestConfiguration.IoTHub.X509ChainDeviceName, s_chainCertificateWithPrivateKey, chainCerts); - using DeviceClient deviceClient = DeviceClient.Create( + using var deviceClient = DeviceClient.Create( _hostName, auth, DeviceTransportType.Mqtt_Tcp_Only); @@ -186,7 +186,7 @@ public async Task X509_Cert_Chain_Install_Test_AMQP_TCP() TestConfiguration.IoTHub.X509ChainDeviceName, s_chainCertificateWithPrivateKey, chainCerts); - using DeviceClient deviceClient = DeviceClient.Create( + using var deviceClient = DeviceClient.Create( _hostName, auth, DeviceTransportType.Amqp_Tcp_Only); @@ -253,7 +253,7 @@ private async Task X509InvalidDeviceIdOpenAsyncTest(Client.TransportType transpo { string deviceName = $"DEVICE_NOT_EXIST_{Guid.NewGuid()}"; using var auth = new DeviceAuthenticationWithX509Certificate(deviceName, s_selfSignedCertificateWithPrivateKey); - using DeviceClient deviceClient = DeviceClient.Create(_hostName, auth, transportType); + using var deviceClient = DeviceClient.Create(_hostName, auth, transportType); try { @@ -274,7 +274,7 @@ private async Task X509InvalidDeviceIdOpenAsyncTwiceTest(Client.TransportType tr { string deviceName = $"DEVICE_NOT_EXIST_{Guid.NewGuid()}"; using var auth = new DeviceAuthenticationWithX509Certificate(deviceName, s_selfSignedCertificateWithPrivateKey); - using DeviceClient deviceClient = DeviceClient.Create(_hostName, auth, transportType); + using var deviceClient = DeviceClient.Create(_hostName, auth, transportType); for (int i = 0; i < 2; i++) { diff --git a/e2e/test/iothub/DeviceTokenRefreshE2ETests.cs b/e2e/test/iothub/DeviceTokenRefreshE2ETests.cs index 96f308eacc..601228c2d3 100644 --- a/e2e/test/iothub/DeviceTokenRefreshE2ETests.cs +++ b/e2e/test/iothub/DeviceTokenRefreshE2ETests.cs @@ -31,7 +31,7 @@ public async Task DeviceClient_Not_Exist_AMQP() using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); var config = new TestConfiguration.IoTHub.ConnectionStringParser(testDevice.ConnectionString); - using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString($"HostName={config.IotHubHostName};DeviceId=device_id_not_exist;SharedAccessKey={config.SharedAccessKey}", Client.TransportType.Amqp_Tcp_Only)) + using (var deviceClient = DeviceClient.CreateFromConnectionString($"HostName={config.IotHubHostName};DeviceId=device_id_not_exist;SharedAccessKey={config.SharedAccessKey}", Client.TransportType.Amqp_Tcp_Only)) { await deviceClient.OpenAsync().ConfigureAwait(false); } @@ -45,7 +45,7 @@ public async Task DeviceClient_Bad_Credentials_AMQP() var config = new TestConfiguration.IoTHub.ConnectionStringParser(testDevice.ConnectionString); string invalidKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("invalid_key")); - using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString($"HostName={config.IotHubHostName};DeviceId={config.DeviceID};SharedAccessKey={invalidKey}", Client.TransportType.Amqp_Tcp_Only)) + using (var deviceClient = DeviceClient.CreateFromConnectionString($"HostName={config.IotHubHostName};DeviceId={config.DeviceID};SharedAccessKey={invalidKey}", Client.TransportType.Amqp_Tcp_Only)) { await deviceClient.OpenAsync().ConfigureAwait(false); } @@ -96,7 +96,7 @@ public async Task DeviceClient_TokenConnectionDoubleRelease_Ok() var auth = new DeviceAuthenticationWithToken(deviceId, builder.ToSignature()); - using DeviceClient deviceClient = DeviceClient.Create(iotHub, auth, Client.TransportType.Amqp_Tcp_Only); + using var deviceClient = DeviceClient.Create(iotHub, auth, Client.TransportType.Amqp_Tcp_Only); Logger.Trace($"{deviceId}: Created {nameof(DeviceClient)} ID={TestLogger.IdOf(deviceClient)}"); Logger.Trace($"{deviceId}: DeviceClient OpenAsync."); @@ -183,7 +183,7 @@ private async Task DeviceClient_TokenIsRefreshed_Internal(Client.TransportType t transport, Logger); - using DeviceClient deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, refresher, transport); + using var deviceClient = DeviceClient.Create(testDevice.IoTHubHostName, refresher, transport); Logger.Trace($"Created {nameof(DeviceClient)} ID={TestLogger.IdOf(deviceClient)}"); if (transport == Client.TransportType.Mqtt) diff --git a/e2e/test/iothub/FileUploadFaultInjectionTests.cs b/e2e/test/iothub/FileUploadFaultInjectionTests.cs index 8e261f4312..35a20bfaf0 100644 --- a/e2e/test/iothub/FileUploadFaultInjectionTests.cs +++ b/e2e/test/iothub/FileUploadFaultInjectionTests.cs @@ -87,7 +87,7 @@ private async Task UploadFileDisconnectTransport( { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); TimeSpan operationTimeout = retryDurationInMilliSec == TimeSpan.Zero ? FaultInjection.RecoveryTime : retryDurationInMilliSec; deviceClient.OperationTimeoutInMilliseconds = (uint)operationTimeout.TotalMilliseconds; diff --git a/e2e/test/iothub/SasCredentialAuthenticationTests.cs b/e2e/test/iothub/SasCredentialAuthenticationTests.cs index 827f05ec2b..decc7947ef 100644 --- a/e2e/test/iothub/SasCredentialAuthenticationTests.cs +++ b/e2e/test/iothub/SasCredentialAuthenticationTests.cs @@ -101,7 +101,7 @@ public async Task JobClient_Http_SasCredentialAuth_Success() string jobId = "JOBSAMPLE" + Guid.NewGuid().ToString(); string jobDeviceId = "JobsSample_Device"; string query = $"DeviceId IN ['{jobDeviceId}']"; - Twin twin = new Twin(jobDeviceId); + var twin = new Twin(jobDeviceId); try { diff --git a/e2e/test/iothub/TokenCredentialAuthenticationTests.cs b/e2e/test/iothub/TokenCredentialAuthenticationTests.cs index cbbcc0633c..c7270ef85b 100644 --- a/e2e/test/iothub/TokenCredentialAuthenticationTests.cs +++ b/e2e/test/iothub/TokenCredentialAuthenticationTests.cs @@ -66,7 +66,7 @@ public async Task JobClient_Http_TokenCredentialAuth_Success() string jobId = "JOBSAMPLE" + Guid.NewGuid().ToString(); string jobDeviceId = "JobsSample_Device"; string query = $"DeviceId IN ['{jobDeviceId}']"; - Twin twin = new Twin(jobDeviceId); + var twin = new Twin(jobDeviceId); try { diff --git a/e2e/test/iothub/messaging/AzureSecurityCenterForIoTSecurityMessageE2ETests.cs b/e2e/test/iothub/messaging/AzureSecurityCenterForIoTSecurityMessageE2ETests.cs index a1927d5160..608ff56129 100644 --- a/e2e/test/iothub/messaging/AzureSecurityCenterForIoTSecurityMessageE2ETests.cs +++ b/e2e/test/iothub/messaging/AzureSecurityCenterForIoTSecurityMessageE2ETests.cs @@ -92,7 +92,7 @@ private Client.Message ComposeD2CSecurityTestMessage() private JObject ComposeAzureSecurityCenterForIoTSecurityMessagePayload(string eventId) { - var now = DateTime.UtcNow; + DateTime now = DateTime.UtcNow; return new JObject { { "AgentVersion", "0.0.1" }, diff --git a/e2e/test/iothub/messaging/FaultInjectionPoolAmqpTests.MessageReceiveFaultInjectionPoolAmqpTests.cs b/e2e/test/iothub/messaging/FaultInjectionPoolAmqpTests.MessageReceiveFaultInjectionPoolAmqpTests.cs index e23297a804..9247448d96 100644 --- a/e2e/test/iothub/messaging/FaultInjectionPoolAmqpTests.MessageReceiveFaultInjectionPoolAmqpTests.cs +++ b/e2e/test/iothub/messaging/FaultInjectionPoolAmqpTests.MessageReceiveFaultInjectionPoolAmqpTests.cs @@ -953,7 +953,7 @@ private async Task ReceiveMessageUsingCallbackRecoveryPoolOverAmqpAsync( string proxyAddress = null) { // Initialize the service client - ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); async Task InitOperationAsync(DeviceClient deviceClient, TestDevice testDevice, TestDeviceCallbackHandler testDeviceCallbackHandler) { diff --git a/e2e/test/iothub/messaging/MessageFeedbackE2ETests.cs b/e2e/test/iothub/messaging/MessageFeedbackE2ETests.cs index 8f0ab42de0..239f3aad9c 100644 --- a/e2e/test/iothub/messaging/MessageFeedbackE2ETests.cs +++ b/e2e/test/iothub/messaging/MessageFeedbackE2ETests.cs @@ -33,7 +33,7 @@ private static async Task CompleteMessageMixOrder(TestDeviceType type, Client.Tr { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(logger, s_devicePrefix, type).ConfigureAwait(false); using (DeviceClient deviceClient = testDevice.CreateDeviceClient(transport)) - using (ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString)) + using (var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString)) { await deviceClient.OpenAsync().ConfigureAwait(false); @@ -61,7 +61,7 @@ private static async Task CompleteMessageMixOrder(TestDeviceType type, Client.Tr for (int i = 0; i < MESSAGE_COUNT; i++) { - Stopwatch stopwatch = new Stopwatch(); + var stopwatch = new Stopwatch(); stopwatch.Start(); await deviceClient.CompleteAsync(messages[MESSAGE_COUNT - 1 - i]).ConfigureAwait(false); stopwatch.Stop(); diff --git a/e2e/test/iothub/messaging/MessageReceiveE2ETests.cs b/e2e/test/iothub/messaging/MessageReceiveE2ETests.cs index e3e58f40f1..98762ff820 100644 --- a/e2e/test/iothub/messaging/MessageReceiveE2ETests.cs +++ b/e2e/test/iothub/messaging/MessageReceiveE2ETests.cs @@ -623,7 +623,7 @@ private async Task ReceiveSingleMessageAsync(TestDeviceType type, Client.Transpo { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false); using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); await deviceClient.OpenAsync().ConfigureAwait(false); await serviceClient.OpenAsync().ConfigureAwait(false); @@ -667,7 +667,7 @@ private async Task ReceiveSingleMessageWithCancellationTokenAsync(TestDeviceType { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false); using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); await deviceClient.OpenAsync().ConfigureAwait(false); await serviceClient.OpenAsync().ConfigureAwait(false); @@ -733,7 +733,7 @@ private async Task ReceiveSingleMessageUsingCallbackAsync(TestDeviceType type, C using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); using var testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger); using (msg) @@ -760,7 +760,7 @@ private async Task ReceiveMessageUsingCallbackAndUnsubscribeAsync(TestDeviceType using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); using var testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); // For Mqtt - we will need to subscribe to the Mqtt receive telemetry topic // before the device can begin receiving c2d messages. @@ -837,7 +837,7 @@ private async Task ReceiveMessageUsingCallbackUpdateHandlerAsync(TestDeviceType using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false); using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); // Set the first C2D message handler. await deviceClient.SetReceiveMessageHandlerAsync( @@ -896,7 +896,7 @@ private async Task ReceiveMessagesSentBeforeSubscriptionAsync(TestDeviceType typ DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); var testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger); @@ -939,7 +939,7 @@ private async Task DoNotReceiveMessagesSentBeforeSubscriptionAsync(TestDeviceTyp DeviceClient deviceClient = testDevice.CreateDeviceClient(settings); var testDeviceCallbackHandler = new TestDeviceCallbackHandler(deviceClient, testDevice, Logger); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); (Message msg, string payload, string p1Value) = ComposeC2dTestMessage(Logger); diff --git a/e2e/test/iothub/messaging/MessageSendE2ETests.cs b/e2e/test/iothub/messaging/MessageSendE2ETests.cs index 5872b277e7..4ff3f6024c 100644 --- a/e2e/test/iothub/messaging/MessageSendE2ETests.cs +++ b/e2e/test/iothub/messaging/MessageSendE2ETests.cs @@ -68,18 +68,18 @@ public async Task Message_DeviceSendSingleMessage_Http() [LoggedTestMethod] public async Task Message_DeviceSendSingleMessage_Amqp_WithHeartbeats() { - Client.AmqpTransportSettings amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_Tcp_Only); + var amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_Tcp_Only); amqpTransportSettings.IdleTimeout = TimeSpan.FromMinutes(2); - ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings }; + var transportSettings = new ITransportSettings[] { amqpTransportSettings }; await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false); } [LoggedTestMethod] public async Task Message_DeviceSendSingleMessage_AmqpWs_WithHeartbeats() { - Client.AmqpTransportSettings amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only); + var amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only); amqpTransportSettings.IdleTimeout = TimeSpan.FromMinutes(2); - ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings }; + var transportSettings = new ITransportSettings[] { amqpTransportSettings }; await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false); } @@ -89,9 +89,9 @@ public async Task Message_DeviceSendSingleMessage_AmqpWs_WithHeartbeats() [TestCategory("LongRunning")] public async Task Message_DeviceSendSingleMessage_Http_WithProxy() { - Client.Http1TransportSettings httpTransportSettings = new Client.Http1TransportSettings(); + var httpTransportSettings = new Client.Http1TransportSettings(); httpTransportSettings.Proxy = new WebProxy(s_proxyServerAddress); - ITransportSettings[] transportSettings = new ITransportSettings[] { httpTransportSettings }; + var transportSettings = new ITransportSettings[] { httpTransportSettings }; await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false); } @@ -100,10 +100,10 @@ public async Task Message_DeviceSendSingleMessage_Http_WithProxy() [TestCategory("Proxy")] public async Task Message_DeviceSendSingleMessage_Http_WithCustomProxy() { - Http1TransportSettings httpTransportSettings = new Http1TransportSettings(); - CustomWebProxy proxy = new CustomWebProxy(Logger); + var httpTransportSettings = new Http1TransportSettings(); + var proxy = new CustomWebProxy(Logger); httpTransportSettings.Proxy = proxy; - ITransportSettings[] transportSettings = new ITransportSettings[] { httpTransportSettings }; + var transportSettings = new ITransportSettings[] { httpTransportSettings }; await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false); Assert.AreNotEqual(proxy.Counter, 0); @@ -114,9 +114,9 @@ public async Task Message_DeviceSendSingleMessage_Http_WithCustomProxy() [TestCategory("LongRunning")] public async Task Message_DeviceSendSingleMessage_AmqpWs_WithProxy() { - Client.AmqpTransportSettings amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only); + var amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only); amqpTransportSettings.Proxy = new WebProxy(s_proxyServerAddress); - ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings }; + var transportSettings = new ITransportSettings[] { amqpTransportSettings }; await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false); } @@ -125,10 +125,10 @@ public async Task Message_DeviceSendSingleMessage_AmqpWs_WithProxy() [TestCategory("Proxy")] public async Task Message_DeviceSendSingleMessage_MqttWs_WithProxy() { - Client.Transport.Mqtt.MqttTransportSettings mqttTransportSettings = + var mqttTransportSettings = new Client.Transport.Mqtt.MqttTransportSettings(Client.TransportType.Mqtt_WebSocket_Only); mqttTransportSettings.Proxy = new WebProxy(s_proxyServerAddress); - ITransportSettings[] transportSettings = new ITransportSettings[] { mqttTransportSettings }; + var transportSettings = new ITransportSettings[] { mqttTransportSettings }; await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false); } @@ -137,9 +137,9 @@ public async Task Message_DeviceSendSingleMessage_MqttWs_WithProxy() [TestCategory("Proxy")] public async Task Message_ModuleSendSingleMessage_AmqpWs_WithProxy() { - Client.AmqpTransportSettings amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only); + var amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only); amqpTransportSettings.Proxy = new WebProxy(s_proxyServerAddress); - ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings }; + var transportSettings = new ITransportSettings[] { amqpTransportSettings }; await SendSingleMessageModule(transportSettings).ConfigureAwait(false); } @@ -148,10 +148,10 @@ public async Task Message_ModuleSendSingleMessage_AmqpWs_WithProxy() [TestCategory("Proxy")] public async Task Message_ModuleSendSingleMessage_MqttWs_WithProxy() { - Client.Transport.Mqtt.MqttTransportSettings mqttTransportSettings = + var mqttTransportSettings = new Client.Transport.Mqtt.MqttTransportSettings(Client.TransportType.Mqtt_WebSocket_Only); mqttTransportSettings.Proxy = new WebProxy(s_proxyServerAddress); - ITransportSettings[] transportSettings = new ITransportSettings[] { mqttTransportSettings }; + var transportSettings = new ITransportSettings[] { mqttTransportSettings }; await SendSingleMessageModule(transportSettings).ConfigureAwait(false); } diff --git a/e2e/test/iothub/method/MethodE2ETests.cs b/e2e/test/iothub/method/MethodE2ETests.cs index 973b2dcfbb..5717254ff6 100644 --- a/e2e/test/iothub/method/MethodE2ETests.cs +++ b/e2e/test/iothub/method/MethodE2ETests.cs @@ -159,7 +159,7 @@ await SendMethodAndRespondAsync( public async Task Method_ServiceInvokeDeviceMethodWithUnknownDeviceThrows() { // setup - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval"); methodInvocation.SetPayloadJson("10"); @@ -233,7 +233,7 @@ public async Task Method_ServiceInvokeDeviceMethodWithUnknownModuleThrows() { // setup using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, "ModuleNotFoundTest").ConfigureAwait(false); - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval"); methodInvocation.SetPayloadJson("10"); @@ -283,7 +283,7 @@ await deviceClient .ConfigureAwait(false); using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); - var c2dMethod = new CloudToDeviceMethod(commandName, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)).SetPayloadJson(null); + CloudToDeviceMethod c2dMethod = new CloudToDeviceMethod(commandName, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)).SetPayloadJson(null); // act @@ -572,7 +572,7 @@ private async Task SendMethodAndUnsubscribeAsync( ServiceClientTransportSettings serviceClientTransportSettings = default) { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); await subscribeAndUnsubscribeMethod(deviceClient, MethodName, Logger).ConfigureAwait(false); @@ -588,7 +588,7 @@ private async Task SendMethodAndRespondAsync( ServiceClientTransportSettings serviceClientTransportSettings = default) { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); Task methodReceivedTask = await setDeviceReceiveMethod(deviceClient, MethodName, Logger).ConfigureAwait(false); Task serviceSendTask = ServiceSendMethodAndVerifyResponseAsync( @@ -608,7 +608,7 @@ private async Task SendMethodAndRespondAsync( private async Task SendMethodAndRespondAsync(Client.TransportType transport, Func> setDeviceReceiveMethod, TimeSpan responseTimeout = default, ServiceClientTransportSettings serviceClientTransportSettings = default) { TestModule testModule = await TestModule.GetTestModuleAsync(_devicePrefix, _modulePrefix, Logger).ConfigureAwait(false); - using ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transport); + using var moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, transport); Task methodReceivedTask = await setDeviceReceiveMethod(moduleClient, MethodName, Logger).ConfigureAwait(false); diff --git a/e2e/test/iothub/method/MethodFaultInjectionTests.cs b/e2e/test/iothub/method/MethodFaultInjectionTests.cs index 4b33787d59..1f08a07cfd 100644 --- a/e2e/test/iothub/method/MethodFaultInjectionTests.cs +++ b/e2e/test/iothub/method/MethodFaultInjectionTests.cs @@ -214,7 +214,7 @@ private async Task ServiceSendMethodAndVerifyResponseAsync(string deviceName, st attempt++; try { - using ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var serviceClient = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Logger.Trace($"{nameof(ServiceSendMethodAndVerifyResponseAsync)}: Invoke method {methodName}."); CloudToDeviceMethodResult response = diff --git a/e2e/test/iothub/service/BulkOperationsE2ETests.cs b/e2e/test/iothub/service/BulkOperationsE2ETests.cs index 53ebc5c813..bf686384f0 100644 --- a/e2e/test/iothub/service/BulkOperationsE2ETests.cs +++ b/e2e/test/iothub/service/BulkOperationsE2ETests.cs @@ -21,18 +21,18 @@ public class BulkOperationsE2ETests : E2EMsTestBase [LoggedTestMethod] public async Task BulkOperations_UpdateTwins2Device_Ok() { - var tagName = Guid.NewGuid().ToString(); - var tagValue = Guid.NewGuid().ToString(); + string tagName = Guid.NewGuid().ToString(); + string tagValue = Guid.NewGuid().ToString(); using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Twin twin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false); twin.Tags = new TwinCollection(); twin.Tags[tagName] = tagValue; - var result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); + BulkRegistryOperationResult result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); Assert.IsTrue(result.IsSuccessful, $"UpdateTwins2Async error:\n{ResultErrorsToString(result)}"); Twin twinUpd = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false); @@ -48,18 +48,18 @@ public async Task BulkOperations_UpdateTwins2Device_Ok() [LoggedTestMethod] public async Task BulkOperations_UpdateTwins2DevicePatch_Ok() { - var tagName = Guid.NewGuid().ToString(); - var tagValue = Guid.NewGuid().ToString(); + string tagName = Guid.NewGuid().ToString(); + string tagValue = Guid.NewGuid().ToString(); using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); - Twin twin = new Twin(); + var twin = new Twin(); twin.DeviceId = testDevice.Id; twin.Tags = new TwinCollection(); twin.Tags[tagName] = tagValue; - var result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); + BulkRegistryOperationResult result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); Assert.IsTrue(result.IsSuccessful, $"UpdateTwins2Async error:\n{ResultErrorsToString(result)}"); Twin twinUpd = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false); @@ -75,18 +75,18 @@ public async Task BulkOperations_UpdateTwins2DevicePatch_Ok() [LoggedTestMethod] public async Task BulkOperations_UpdateTwins2Module_Ok() { - var tagName = Guid.NewGuid().ToString(); - var tagValue = Guid.NewGuid().ToString(); + string tagName = Guid.NewGuid().ToString(); + string tagValue = Guid.NewGuid().ToString(); TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix, Logger).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Twin twin = await registryManager.GetTwinAsync(testModule.DeviceId, testModule.Id).ConfigureAwait(false); twin.Tags = new TwinCollection(); twin.Tags[tagName] = tagValue; - var result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); + BulkRegistryOperationResult result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); Assert.IsTrue(result.IsSuccessful, $"UpdateTwins2Async error:\n{ResultErrorsToString(result)}"); Twin twinUpd = await registryManager.GetTwinAsync(testModule.DeviceId, testModule.Id).ConfigureAwait(false); @@ -103,19 +103,19 @@ public async Task BulkOperations_UpdateTwins2Module_Ok() [LoggedTestMethod] public async Task BulkOperations_UpdateTwins2ModulePatch_Ok() { - var tagName = Guid.NewGuid().ToString(); - var tagValue = Guid.NewGuid().ToString(); + string tagName = Guid.NewGuid().ToString(); + string tagValue = Guid.NewGuid().ToString(); TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix, Logger).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); var twin = new Twin(); twin.DeviceId = testModule.DeviceId; twin.ModuleId = testModule.Id; twin.Tags = new TwinCollection(); twin.Tags[tagName] = tagValue; - var result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); + BulkRegistryOperationResult result = await registryManager.UpdateTwins2Async(new List { twin }, true).ConfigureAwait(false); Assert.IsTrue(result.IsSuccessful, $"UpdateTwins2Async error:\n{ResultErrorsToString(result)}"); Twin twinUpd = await registryManager.GetTwinAsync(testModule.DeviceId, testModule.Id).ConfigureAwait(false); @@ -131,9 +131,9 @@ public async Task BulkOperations_UpdateTwins2ModulePatch_Ok() private string ResultErrorsToString(BulkRegistryOperationResult result) { - var errorString = ""; + string errorString = ""; - foreach (var error in result.Errors) + foreach (DeviceRegistryOperationError error in result.Errors) { errorString += $"\t{error.ErrorCode} : {error.ErrorStatus}\n"; } diff --git a/e2e/test/iothub/service/IoTHubCertificateValidationE2ETest.cs b/e2e/test/iothub/service/IoTHubCertificateValidationE2ETest.cs index 0047b1bc78..932020154a 100644 --- a/e2e/test/iothub/service/IoTHubCertificateValidationE2ETest.cs +++ b/e2e/test/iothub/service/IoTHubCertificateValidationE2ETest.cs @@ -19,7 +19,7 @@ public class IoTHubCertificateValidationE2ETest : E2EMsTestBase [LoggedTestMethod] public async Task RegistryManager_QueryDevicesInvalidServiceCertificateHttp_Fails() { - using RegistryManager rm = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionStringInvalidServiceCertificate); + using var rm = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionStringInvalidServiceCertificate); IQuery query = rm.CreateQuery("select * from devices"); IotHubCommunicationException exception = await Assert.ThrowsExceptionAsync( () => query.GetNextAsTwinAsync()).ConfigureAwait(false); @@ -34,7 +34,7 @@ public async Task RegistryManager_QueryDevicesInvalidServiceCertificateHttp_Fail [LoggedTestMethod] public async Task ServiceClient_SendMessageToDeviceInvalidServiceCertificateAmqpTcp_Fails() { - var transport = TransportType.Amqp; + TransportType transport = TransportType.Amqp; await Assert.ThrowsExceptionAsync( () => TestServiceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); } @@ -42,8 +42,8 @@ await Assert.ThrowsExceptionAsync( [LoggedTestMethod] public async Task ServiceClient_SendMessageToDeviceInvalidServiceCertificateAmqpWs_Fails() { - var transport = TransportType.Amqp_WebSocket_Only; - var exception = await Assert.ThrowsExceptionAsync( + TransportType transport = TransportType.Amqp_WebSocket_Only; + WebSocketException exception = await Assert.ThrowsExceptionAsync( () => TestServiceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); Assert.IsInstanceOfType(exception.InnerException.InnerException, typeof(AuthenticationException)); @@ -51,7 +51,7 @@ public async Task ServiceClient_SendMessageToDeviceInvalidServiceCertificateAmqp private static async Task TestServiceClientInvalidServiceCertificate(TransportType transport) { - using ServiceClient service = ServiceClient.CreateFromConnectionString( + using var service = ServiceClient.CreateFromConnectionString( TestConfiguration.IoTHub.ConnectionStringInvalidServiceCertificate, transport); using var testMessage = new Message(); @@ -61,8 +61,8 @@ private static async Task TestServiceClientInvalidServiceCertificate(TransportTy [LoggedTestMethod] public async Task JobClient_ScheduleTwinUpdateInvalidServiceCertificateHttp_Fails() { - using JobClient jobClient = JobClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionStringInvalidServiceCertificate); - var exception = await Assert.ThrowsExceptionAsync( + using var jobClient = JobClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionStringInvalidServiceCertificate); + IotHubCommunicationException exception = await Assert.ThrowsExceptionAsync( () => jobClient.ScheduleTwinUpdateAsync( "testDevice", "DeviceId IN ['testDevice']", @@ -80,7 +80,7 @@ public async Task JobClient_ScheduleTwinUpdateInvalidServiceCertificateHttp_Fail [LoggedTestMethod] public async Task DeviceClient_SendAsyncInvalidServiceCertificateAmqpTcp_Fails() { - var transport = Client.TransportType.Amqp_Tcp_Only; + Client.TransportType transport = Client.TransportType.Amqp_Tcp_Only; await Assert.ThrowsExceptionAsync( () => TestDeviceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); } @@ -88,7 +88,7 @@ await Assert.ThrowsExceptionAsync( [LoggedTestMethod] public async Task DeviceClient_SendAsyncInvalidServiceCertificateMqttTcp_Fails() { - var transport = Client.TransportType.Mqtt_Tcp_Only; + Client.TransportType transport = Client.TransportType.Mqtt_Tcp_Only; await Assert.ThrowsExceptionAsync( () => TestDeviceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); } @@ -96,8 +96,8 @@ await Assert.ThrowsExceptionAsync( [LoggedTestMethod] public async Task DeviceClient_SendAsyncInvalidServiceCertificateHttp_Fails() { - var transport = Client.TransportType.Http1; - var exception = await Assert.ThrowsExceptionAsync( + Client.TransportType transport = Client.TransportType.Http1; + AuthenticationException exception = await Assert.ThrowsExceptionAsync( () => TestDeviceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); #if NET451 || NET472 @@ -110,8 +110,8 @@ public async Task DeviceClient_SendAsyncInvalidServiceCertificateHttp_Fails() [LoggedTestMethod] public async Task DeviceClient_SendAsyncInvalidServiceCertificateAmqpWs_Fails() { - var transport = Client.TransportType.Amqp_WebSocket_Only; - var exception = await Assert.ThrowsExceptionAsync( + Client.TransportType transport = Client.TransportType.Amqp_WebSocket_Only; + AuthenticationException exception = await Assert.ThrowsExceptionAsync( () => TestDeviceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); Assert.IsInstanceOfType(exception.InnerException.InnerException.InnerException, typeof(AuthenticationException)); @@ -120,8 +120,8 @@ public async Task DeviceClient_SendAsyncInvalidServiceCertificateAmqpWs_Fails() [LoggedTestMethod] public async Task DeviceClient_SendAsyncInvalidServiceCertificateMqttWs_Fails() { - var transport = Client.TransportType.Mqtt_WebSocket_Only; - var exception = await Assert.ThrowsExceptionAsync( + Client.TransportType transport = Client.TransportType.Mqtt_WebSocket_Only; + AuthenticationException exception = await Assert.ThrowsExceptionAsync( () => TestDeviceClientInvalidServiceCertificate(transport)).ConfigureAwait(false); Assert.IsInstanceOfType(exception.InnerException.InnerException.InnerException, typeof(AuthenticationException)); @@ -129,15 +129,13 @@ public async Task DeviceClient_SendAsyncInvalidServiceCertificateMqttWs_Fails() private static async Task TestDeviceClientInvalidServiceCertificate(Client.TransportType transport) { - using (DeviceClient deviceClient = + using var deviceClient = DeviceClient.CreateFromConnectionString( TestConfiguration.IoTHub.DeviceConnectionStringInvalidServiceCertificate, - transport)) - { - using var testMessage = new Client.Message(); - await deviceClient.SendEventAsync(testMessage).ConfigureAwait(false); - await deviceClient.CloseAsync().ConfigureAwait(false); - } + transport); + using var testMessage = new Client.Message(); + await deviceClient.SendEventAsync(testMessage).ConfigureAwait(false); + await deviceClient.CloseAsync().ConfigureAwait(false); } } } diff --git a/e2e/test/iothub/service/IoTHubServiceProxyE2ETests.cs b/e2e/test/iothub/service/IoTHubServiceProxyE2ETests.cs index 0cf3a69c07..24a2d778e6 100644 --- a/e2e/test/iothub/service/IoTHubServiceProxyE2ETests.cs +++ b/e2e/test/iothub/service/IoTHubServiceProxyE2ETests.cs @@ -30,7 +30,7 @@ public class IoTHubServiceProxyE2ETests : E2EMsTestBase [LoggedTestMethod] public async Task ServiceClient_Message_SendSingleMessage_WithProxy() { - ServiceClientTransportSettings transportSettings = new ServiceClientTransportSettings(); + var transportSettings = new ServiceClientTransportSettings(); transportSettings.AmqpProxy = new WebProxy(s_proxyServerAddress); transportSettings.HttpProxy = new WebProxy(s_proxyServerAddress); @@ -40,7 +40,7 @@ public async Task ServiceClient_Message_SendSingleMessage_WithProxy() [LoggedTestMethod] public async Task RegistryManager_AddAndRemoveDevice_WithProxy() { - HttpTransportSettings httpTransportSettings = new HttpTransportSettings(); + var httpTransportSettings = new HttpTransportSettings(); httpTransportSettings.Proxy = new WebProxy(s_proxyServerAddress); await RegistryManager_AddDevice(httpTransportSettings).ConfigureAwait(false); @@ -49,7 +49,7 @@ public async Task RegistryManager_AddAndRemoveDevice_WithProxy() [LoggedTestMethod] public async Task JobClient_ScheduleAndRunTwinJob_WithProxy() { - HttpTransportSettings httpTransportSettings = new HttpTransportSettings(); + var httpTransportSettings = new HttpTransportSettings(); httpTransportSettings.Proxy = new WebProxy(s_proxyServerAddress); await JobClient_ScheduleAndRunTwinJob(httpTransportSettings).ConfigureAwait(false); @@ -58,8 +58,8 @@ public async Task JobClient_ScheduleAndRunTwinJob_WithProxy() private async Task SendSingleMessageService(ServiceClientTransportSettings transportSettings) { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); - using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString)) - using (ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString, TransportType.Amqp, transportSettings)) + using (var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString)) + using (var serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString, TransportType.Amqp, transportSettings)) { (Message testMessage, string messageId, string payload, string p1Value) = ComposeD2CTestMessage(); await serviceClient.SendAsync(testDevice.Id, testMessage).ConfigureAwait(false); @@ -73,7 +73,7 @@ private async Task RegistryManager_AddDevice(HttpTransportSettings httpTransport { string deviceName = DevicePrefix + Guid.NewGuid(); - using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(s_connectionString, httpTransportSettings)) + using (var registryManager = RegistryManager.CreateFromConnectionString(s_connectionString, httpTransportSettings)) { await registryManager.AddDeviceAsync(new Device(deviceName)).ConfigureAwait(false); await registryManager.RemoveDeviceAsync(deviceName).ConfigureAwait(false); @@ -82,11 +82,11 @@ private async Task RegistryManager_AddDevice(HttpTransportSettings httpTransport private async Task JobClient_ScheduleAndRunTwinJob(HttpTransportSettings httpTransportSettings) { - Twin twin = new Twin(JobDeviceId); + var twin = new Twin(JobDeviceId); twin.Tags = new TwinCollection(); twin.Tags[JobTestTagName] = JobDeviceId; - using (JobClient jobClient = JobClient.CreateFromConnectionString(s_connectionString, httpTransportSettings)) + using (var jobClient = JobClient.CreateFromConnectionString(s_connectionString, httpTransportSettings)) { int tryCount = 0; while (true) @@ -111,9 +111,9 @@ private async Task JobClient_ScheduleAndRunTwinJob(HttpTransportSettings httpTra private (Message message, string messageId, string payload, string p1Value) ComposeD2CTestMessage() { - var messageId = Guid.NewGuid().ToString(); - var payload = Guid.NewGuid().ToString(); - var p1Value = Guid.NewGuid().ToString(); + string messageId = Guid.NewGuid().ToString(); + string payload = Guid.NewGuid().ToString(); + string p1Value = Guid.NewGuid().ToString(); Logger.Trace($"{nameof(ComposeD2CTestMessage)}: messageId='{messageId}' payload='{payload}' p1Value='{p1Value}'"); var message = new Message(Encoding.UTF8.GetBytes(payload)) diff --git a/e2e/test/iothub/service/PnpServiceTests.cs b/e2e/test/iothub/service/PnpServiceTests.cs index 631309c795..bd8f9c918f 100644 --- a/e2e/test/iothub/service/PnpServiceTests.cs +++ b/e2e/test/iothub/service/PnpServiceTests.cs @@ -38,13 +38,13 @@ public async Task DeviceTwin_Contains_ModelId() { ModelId = TestModelId, }; - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, Client.TransportType.Mqtt_Tcp_Only, options); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, Client.TransportType.Mqtt_Tcp_Only, options); await deviceClient.OpenAsync().ConfigureAwait(false); // Act // Get device twin. - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Twin twin = await registryManager.GetTwinAsync(testDevice.Device.Id).ConfigureAwait(false); // Assert @@ -69,13 +69,13 @@ public async Task DeviceTwin_Contains_ModelId_X509() string hostName = HostNameHelper.GetHostName(TestConfiguration.IoTHub.ConnectionString); X509Certificate2 authCertificate = TestConfiguration.IoTHub.GetCertificateWithPrivateKey(); using var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, authCertificate); - using DeviceClient deviceClient = DeviceClient.Create(hostName, auth, Client.TransportType.Mqtt_Tcp_Only, options); + using var deviceClient = DeviceClient.Create(hostName, auth, Client.TransportType.Mqtt_Tcp_Only, options); await deviceClient.OpenAsync().ConfigureAwait(false); // Act // Get device twin. - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Twin twin = await registryManager.GetTwinAsync(testDevice.Device.Id).ConfigureAwait(false); // Assert @@ -104,13 +104,13 @@ public async Task ModuleTwin_Contains_ModelId() { ModelId = TestModelId, }; - using ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, Client.TransportType.Mqtt_Tcp_Only, options); + using var moduleClient = ModuleClient.CreateFromConnectionString(testModule.ConnectionString, Client.TransportType.Mqtt_Tcp_Only, options); await moduleClient.OpenAsync().ConfigureAwait(false); // Act // Get module twin. - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Twin twin = await registryManager.GetTwinAsync(testModule.DeviceId, testModule.Id).ConfigureAwait(false); // Assert diff --git a/e2e/test/iothub/service/RegistryManagerE2ETests.cs b/e2e/test/iothub/service/RegistryManagerE2ETests.cs index 5729f9b7b4..84941b8fc9 100644 --- a/e2e/test/iothub/service/RegistryManagerE2ETests.cs +++ b/e2e/test/iothub/service/RegistryManagerE2ETests.cs @@ -26,7 +26,7 @@ public class RegistryManagerE2ETests : E2EMsTestBase public async Task RegistryManager_BadProxy_ThrowsException() { // arrange - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString( + using var registryManager = RegistryManager.CreateFromConnectionString( TestConfiguration.IoTHub.ConnectionString, new HttpTransportSettings { @@ -94,7 +94,7 @@ public async Task RegistryManager_AddDeviceWithTwinWithDeviceCapabilities() { string deviceId = _idPrefix + Guid.NewGuid(); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); var twin = new Twin { Tags = new TwinCollection(@"{ companyId: 1234 }"), @@ -120,13 +120,16 @@ public async Task RegistryManager_BulkLifecycle() var devices = new List(); for (int i = 0; i < bulkCount; i++) { - var device = new Device(_idPrefix + Guid.NewGuid()); - device.Scope = "someScope" + Guid.NewGuid(); + var device = new Device(_idPrefix + Guid.NewGuid()) + { + Scope = "someScope" + Guid.NewGuid() + }; + device.ParentScopes.Add("someParentScope" + Guid.NewGuid()); devices.Add(device); } - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); // Test that you can create devices in bulk BulkRegistryOperationResult bulkAddResult = await registryManager.AddDevices2Async(devices).ConfigureAwait(false); @@ -183,7 +186,7 @@ public async Task RegistryManager_AddDeviceWithProxy() Proxy = new WebProxy(TestConfiguration.IoTHub.ProxyServerAddress) }; - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, transportSettings); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, transportSettings); var device = new Device(deviceId); await registryManager.AddDeviceAsync(device).ConfigureAwait(false); } @@ -195,7 +198,7 @@ public async Task RegistryManager_ConfigurationOperations_Work() bool configCreated = false; string configurationId = (_idPrefix + Guid.NewGuid()).ToLower(); // Configuration Id characters must be all lower-case. - using RegistryManager client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); try { @@ -260,7 +263,7 @@ public async Task RegistryManager_ConfigurationOperations_Work() public async Task RegistryManager_Query_Works() { // arrange - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); string deviceId = $"{_idPrefix}{Guid.NewGuid()}"; try @@ -312,7 +315,7 @@ public async Task ModulesClient_GetModulesOnDevice() } Device device = null; - using RegistryManager client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); try { @@ -355,7 +358,7 @@ public async Task ModulesClient_IdentityLifecycle() string testDeviceId = $"IdentityLifecycleDevice{Guid.NewGuid()}"; string testModuleId = $"IdentityLifecycleModule{Guid.NewGuid()}"; - using RegistryManager client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); try { @@ -398,7 +401,7 @@ public async Task ModulesClient_IdentityLifecycle() [LoggedTestMethod] public async Task ModulesClient_DeviceTwinLifecycle() { - using RegistryManager client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var client = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); TestModule module = await TestModule.GetTestModuleAsync(_idPrefix, _idPrefix, Logger).ConfigureAwait(false); try @@ -427,7 +430,7 @@ public async Task ModulesClient_DeviceTwinLifecycle() } } - private async Task CleanupAsync(RegistryManager client, string deviceId) + private static async Task CleanupAsync(RegistryManager client, string deviceId) { // cleanup try diff --git a/e2e/test/iothub/service/RegistryManagerExportDevicesTests.cs b/e2e/test/iothub/service/RegistryManagerExportDevicesTests.cs index c779d0099a..d5f0b17a12 100644 --- a/e2e/test/iothub/service/RegistryManagerExportDevicesTests.cs +++ b/e2e/test/iothub/service/RegistryManagerExportDevicesTests.cs @@ -57,7 +57,7 @@ public async Task RegistryManager_ExportDevices(StorageAuthenticationType storag string edgeId2 = $"{nameof(RegistryManager_ExportDevices)}-Edge-{StorageContainer.GetRandomSuffix(4)}"; string deviceId = $"{nameof(RegistryManager_ExportDevices)}-{StorageContainer.GetRandomSuffix(4)}"; string devicesFileName = $"{nameof(RegistryManager_ExportDevices)}-devicesexport-{StorageContainer.GetRandomSuffix(4)}.txt"; - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Logger.Trace($"Using deviceId {deviceId}"); @@ -73,7 +73,7 @@ public async Task RegistryManager_ExportDevices(StorageAuthenticationType storag ? storageContainer.SasUri : storageContainer.Uri; - var edge1 = await registryManager + Device edge1 = await registryManager .AddDeviceAsync( new Device(edgeId1) { @@ -82,7 +82,7 @@ public async Task RegistryManager_ExportDevices(StorageAuthenticationType storag }) .ConfigureAwait(false); - var edge2 = await registryManager + Device edge2 = await registryManager .AddDeviceAsync( new Device(edgeId2) { @@ -119,7 +119,7 @@ await registryManager }; } - JobProperties jobProperties = JobProperties.CreateForExportJob( + var jobProperties = JobProperties.CreateForExportJob( containerUri.ToString(), true, devicesFileName, diff --git a/e2e/test/iothub/service/RegistryManagerImportDevicesTests.cs b/e2e/test/iothub/service/RegistryManagerImportDevicesTests.cs index 8134adc813..3522d7e9e3 100644 --- a/e2e/test/iothub/service/RegistryManagerImportDevicesTests.cs +++ b/e2e/test/iothub/service/RegistryManagerImportDevicesTests.cs @@ -48,7 +48,7 @@ public async Task RegistryManager_ImportDevices(StorageAuthenticationType storag string deviceId = $"{nameof(RegistryManager_ImportDevices)}-device-{StorageContainer.GetRandomSuffix(4)}"; string devicesFileName = $"{nameof(RegistryManager_ImportDevices)}-{StorageContainer.GetRandomSuffix(4)}.txt"; - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Logger.Trace($"Using deviceId {deviceId}."); diff --git a/e2e/test/iothub/service/ServiceClientE2ETests.cs b/e2e/test/iothub/service/ServiceClientE2ETests.cs index ebad2565b7..d18fdda791 100644 --- a/e2e/test/iothub/service/ServiceClientE2ETests.cs +++ b/e2e/test/iothub/service/ServiceClientE2ETests.cs @@ -50,7 +50,7 @@ private async Task TestTimeout(TimeSpan? timeout) using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); - Stopwatch sw = new Stopwatch(); + var sw = new Stopwatch(); sw.Start(); Logger.Trace($"Testing ServiceClient SendAsync() timeout in ticks={timeout?.Ticks}"); @@ -73,7 +73,7 @@ public async Task ServiceClient_SendsMessage(TransportType transportType) { // arrange using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); - using ServiceClient sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, transportType); + using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, transportType); string messageId = Guid.NewGuid().ToString(); // act and expect no exception @@ -92,7 +92,7 @@ public async Task MessageIdDefaultNotSet_SendEventDoesNotSetMessageId() { // arrange using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); - using ServiceClient sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); string messageId = Guid.NewGuid().ToString(); // act @@ -121,7 +121,7 @@ public async Task MessageIdDefaultSetToNull_SendEventDoesNotSetMessageId() { SdkAssignsMessageId = Shared.SdkAssignsMessageId.Never, }; - using ServiceClient sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, options); + using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, options); string messageId = Guid.NewGuid().ToString(); // act @@ -150,7 +150,7 @@ public async Task MessageIdDefaultSetToGuid_SendEventSetMessageIdIfNotSet() { SdkAssignsMessageId = Shared.SdkAssignsMessageId.WhenUnset, }; - using ServiceClient sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, options); + using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, options); string messageId = Guid.NewGuid().ToString(); // act diff --git a/e2e/test/iothub/twin/FaultInjectionPoolAmqpTests.TwinFaultInjectionPoolAmqpTests.cs b/e2e/test/iothub/twin/FaultInjectionPoolAmqpTests.TwinFaultInjectionPoolAmqpTests.cs index 53736ec57c..419708e302 100644 --- a/e2e/test/iothub/twin/FaultInjectionPoolAmqpTests.TwinFaultInjectionPoolAmqpTests.cs +++ b/e2e/test/iothub/twin/FaultInjectionPoolAmqpTests.TwinFaultInjectionPoolAmqpTests.cs @@ -1481,8 +1481,8 @@ private async Task Twin_DeviceDesiredPropertyUpdateRecoveryPoolOverAmqp( async Task InitOperationAsync(DeviceClient deviceClient, TestDevice testDevice, TestDeviceCallbackHandler testDeviceCallbackHandler) { - var propName = Guid.NewGuid().ToString(); - var propValue = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); + string propValue = Guid.NewGuid().ToString(); twinPropertyMap.Add(testDevice.Id, new List { propName, propValue }); Logger.Trace($"{nameof(FaultInjectionPoolAmqpTests)}: Setting desired propery callback for device {testDevice.Id}"); @@ -1495,8 +1495,8 @@ async Task TestOperationAsync(DeviceClient deviceClient, TestDevice testDevice, using var cts = new CancellationTokenSource(FaultInjection.RecoveryTime); List twinProperties = twinPropertyMap[testDevice.Id]; - var propName = twinProperties[0]; - var propValue = twinProperties[1]; + string propName = twinProperties[0]; + string propValue = twinProperties[1]; testDeviceCallbackHandler.ExpectedTwinPropertyValue = propValue; Logger.Trace($"{nameof(FaultInjectionPoolAmqpTests)}: Updating the desired properties for device {testDevice.Id}"); diff --git a/e2e/test/iothub/twin/TwinE2ETests.cs b/e2e/test/iothub/twin/TwinE2ETests.cs index be9d0aecca..27e4915ee3 100644 --- a/e2e/test/iothub/twin/TwinE2ETests.cs +++ b/e2e/test/iothub/twin/TwinE2ETests.cs @@ -392,7 +392,7 @@ public async Task Twin_ClientSetsReportedPropertyWithoutDesiredPropertyCallback( // arrange using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transportType); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transportType); await Twin_DeviceSetsReportedPropertyAndGetsItBackAsync(deviceClient, testDevice.Id, Guid.NewGuid().ToString(), Logger).ConfigureAwait(false); @@ -418,7 +418,7 @@ public async Task Twin_ClientSetsReportedPropertyWithoutDesiredPropertyCallback( private async Task Twin_DeviceSetsReportedPropertyAndGetsItBackSingleDeviceAsync(Client.TransportType transport) { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); await Twin_DeviceSetsReportedPropertyAndGetsItBackAsync(deviceClient, testDevice.Id, Guid.NewGuid().ToString(), Logger).ConfigureAwait(false); } @@ -426,14 +426,14 @@ private async Task Twin_DeviceSetsReportedPropertyAndGetsItBackSingleDeviceAsync private async Task Twin_DeviceSetsReportedPropertyArrayAndGetsItBackSingleDeviceAsync(Client.TransportType transport) { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); await Twin_DeviceSetsReportedPropertyAndGetsItBackAsync(deviceClient, testDevice.Id, s_listOfPropertyValues, Logger).ConfigureAwait(false); } public static async Task Twin_DeviceSetsReportedPropertyAndGetsItBackAsync(DeviceClient deviceClient, string deviceId, object propValue, MsTestLogger logger) { - var propName = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); logger.Trace($"{nameof(Twin_DeviceSetsReportedPropertyAndGetsItBackAsync)}: name={propName}, value={propValue}"); @@ -443,12 +443,12 @@ public static async Task Twin_DeviceSetsReportedPropertyAndGetsItBackAsync(Devic // Validate the updated twin from the device-client Twin deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); - var actual = deviceTwin.Properties.Reported[propName]; + dynamic actual = deviceTwin.Properties.Reported[propName]; Assert.AreEqual(JsonConvert.SerializeObject(actual), JsonConvert.SerializeObject(propValue)); // Validate the updated twin from the service-client Twin completeTwin = await _registryManager.GetTwinAsync(deviceId).ConfigureAwait(false); - var actualProp = completeTwin.Properties.Reported[propName]; + dynamic actualProp = completeTwin.Properties.Reported[propName]; Assert.AreEqual(JsonConvert.SerializeObject(actualProp), JsonConvert.SerializeObject(propValue)); } @@ -523,7 +523,7 @@ await deviceClient public static async Task RegistryManagerUpdateDesiredPropertyAsync(string deviceId, string propName, object propValue) { - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; @@ -534,12 +534,12 @@ public static async Task RegistryManagerUpdateDesiredPropertyAsync(string device private async Task Twin_ServiceSetsDesiredPropertyAndDeviceUnsubscribes(Client.TransportType transport, object propValue) { - var propName = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); Logger.Trace($"{nameof(Twin_ServiceSetsDesiredPropertyAndDeviceReceivesEventAsync)}: name={propName}, value={propValue}"); using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); // Set a callback await deviceClient. @@ -569,12 +569,12 @@ await RegistryManagerUpdateDesiredPropertyAsync(testDevice.Id, propName, propVal private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesEventAsync(Client.TransportType transport, Func> setTwinPropertyUpdateCallbackAsync, object propValue) { - var propName = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); Logger.Trace($"{nameof(Twin_ServiceSetsDesiredPropertyAndDeviceReceivesEventAsync)}: name={propName}, value={propValue}"); using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); Task updateReceivedTask = await setTwinPropertyUpdateCallbackAsync(deviceClient, propName, propValue, Logger).ConfigureAwait(false); @@ -584,12 +584,12 @@ await Task.WhenAll( // Validate the updated twin from the device-client Twin deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); - var actual = deviceTwin.Properties.Desired[propName]; + dynamic actual = deviceTwin.Properties.Desired[propName]; Assert.AreEqual(JsonConvert.SerializeObject(actual), JsonConvert.SerializeObject(propValue)); // Validate the updated twin from the service-client Twin completeTwin = await _registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false); - var actualProp = completeTwin.Properties.Desired[propName]; + dynamic actualProp = completeTwin.Properties.Desired[propName]; Assert.AreEqual(JsonConvert.SerializeObject(actualProp), JsonConvert.SerializeObject(propValue)); await deviceClient.SetDesiredPropertyUpdateCallbackAsync(null, null).ConfigureAwait(false); @@ -598,12 +598,12 @@ await Task.WhenAll( private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesItOnNextGetAsync(Client.TransportType transport) { - var propName = Guid.NewGuid().ToString(); - var propValue = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); + string propValue = Guid.NewGuid().ToString(); using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; @@ -618,12 +618,12 @@ private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesItOnNextGetAs private async Task Twin_DeviceSetsReportedPropertyAndServiceReceivesItAsync(Client.TransportType transport) { - var propName = Guid.NewGuid().ToString(); - var propValue = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); + string propValue = Guid.NewGuid().ToString(); using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); var patch = new TwinCollection(); patch[propName] = propValue; @@ -638,13 +638,13 @@ private async Task Twin_DeviceSetsReportedPropertyAndServiceReceivesItAsync(Clie private async Task Twin_ServiceDoesNotCreateNullPropertyInCollectionAsync(Client.TransportType transport) { - var propName1 = Guid.NewGuid().ToString(); - var propName2 = Guid.NewGuid().ToString(); - var propEmptyValue = "{}"; + string propName1 = Guid.NewGuid().ToString(); + string propName2 = Guid.NewGuid().ToString(); + string propEmptyValue = "{}"; using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); await deviceClient .UpdateReportedPropertiesAsync( @@ -690,14 +690,14 @@ await deviceClient private async Task Twin_ClientHandlesRejectionInvalidPropertyNameAsync(Client.TransportType transport) { - var propName1 = "$" + Guid.NewGuid().ToString(); - var propName2 = Guid.NewGuid().ToString(); + string propName1 = "$" + Guid.NewGuid().ToString(); + string propName2 = Guid.NewGuid().ToString(); using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); - using DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); - var exceptionThrown = false; + bool exceptionThrown = false; try { await deviceClient diff --git a/e2e/test/iothub/twin/TwinFaultInjectionTests.cs b/e2e/test/iothub/twin/TwinFaultInjectionTests.cs index 0d76a46aec..eb94dd3fbc 100644 --- a/e2e/test/iothub/twin/TwinFaultInjectionTests.cs +++ b/e2e/test/iothub/twin/TwinFaultInjectionTests.cs @@ -219,12 +219,12 @@ private async Task Twin_DeviceReportedPropertiesRecovery( TimeSpan delayInSec, string proxyAddress = null) { - var propName = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); var props = new TwinCollection(); Func testOperation = async (deviceClient, testDevice) => { - var propValue = Guid.NewGuid().ToString(); + string propValue = Guid.NewGuid().ToString(); props[propName] = propValue; await deviceClient.UpdateReportedPropertiesAsync(props).ConfigureAwait(false); @@ -256,7 +256,7 @@ await FaultInjection private async Task RegistryManagerUpdateDesiredPropertyAsync(string deviceId, string propName, string propValue) { - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; @@ -273,10 +273,10 @@ private async Task Twin_DeviceDesiredPropertyUpdateRecoveryAsync( string proxyAddress = null) { TestDeviceCallbackHandler testDeviceCallbackHandler = null; - using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); + using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); using var cts = new CancellationTokenSource(FaultInjection.RecoveryTime); - var propName = Guid.NewGuid().ToString(); + string propName = Guid.NewGuid().ToString(); var props = new TwinCollection(); // Configure the callback and start accepting twin changes. @@ -289,7 +289,7 @@ async Task InitOperationAsync(DeviceClient deviceClient, TestDevice testDevice) // Change the twin from the service side and verify the device received it. async Task TestOperationAsync(DeviceClient deviceClient, TestDevice testDevice) { - var propValue = Guid.NewGuid().ToString(); + string propValue = Guid.NewGuid().ToString(); testDeviceCallbackHandler.ExpectedTwinPropertyValue = propValue; Logger.Trace($"{nameof(Twin_DeviceDesiredPropertyUpdateRecoveryAsync)}: name={propName}, value={propValue}"); diff --git a/e2e/test/provisioning/ProvisioningCertificateValidationE2ETest.cs b/e2e/test/provisioning/ProvisioningCertificateValidationE2ETest.cs index 31d790610c..ca3afe1125 100644 --- a/e2e/test/provisioning/ProvisioningCertificateValidationE2ETest.cs +++ b/e2e/test/provisioning/ProvisioningCertificateValidationE2ETest.cs @@ -20,12 +20,12 @@ public class ProvisioningCertificateValidationE2ETest : E2EMsTestBase [LoggedTestMethod] public async Task ProvisioningServiceClient_QueryInvalidServiceCertificateHttp_Fails() { - using ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString( + using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString( TestConfiguration.Provisioning.ConnectionStringInvalidServiceCertificate); Query q = provisioningServiceClient.CreateEnrollmentGroupQuery( new QuerySpecification("SELECT * FROM enrollmentGroups")); - var exception = await Assert.ThrowsExceptionAsync( + ProvisioningServiceClientTransportException exception = await Assert.ThrowsExceptionAsync( () => q.NextAsync()).ConfigureAwait(false); #if NET472 || NET451 @@ -39,7 +39,7 @@ public async Task ProvisioningServiceClient_QueryInvalidServiceCertificateHttp_F public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificateAmqpTcp_Fails() { using var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly); - var exception = await Assert.ThrowsExceptionAsync( + ProvisioningTransportException exception = await Assert.ThrowsExceptionAsync( () => TestInvalidServiceCertificate(transport)).ConfigureAwait(false); Assert.IsInstanceOfType(exception.InnerException, typeof(AuthenticationException)); @@ -49,7 +49,7 @@ public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificat public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificateMqttTcp_Fails() { using var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly); - var exception = await Assert.ThrowsExceptionAsync( + ProvisioningTransportException exception = await Assert.ThrowsExceptionAsync( () => TestInvalidServiceCertificate(transport)).ConfigureAwait(false); if (exception.InnerException == null) @@ -66,7 +66,7 @@ public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificat public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificateHttp_Fails() { using var transport = new ProvisioningTransportHandlerHttp(); - var exception = await Assert.ThrowsExceptionAsync( + ProvisioningTransportException exception = await Assert.ThrowsExceptionAsync( () => TestInvalidServiceCertificate(transport)).ConfigureAwait(false); #if NET472 || NET451 @@ -80,7 +80,7 @@ public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificat public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificateAmqpWs_Fails() { using var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.WebSocketOnly); - var exception = await Assert.ThrowsExceptionAsync( + ProvisioningTransportException exception = await Assert.ThrowsExceptionAsync( () => TestInvalidServiceCertificate(transport)).ConfigureAwait(false); Assert.IsInstanceOfType(exception.InnerException.InnerException.InnerException, typeof(AuthenticationException)); @@ -90,7 +90,7 @@ public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificat public async Task ProvisioningDeviceClient_RegisterAsyncInvalidServiceCertificateMqttWs_Fails() { using var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.WebSocketOnly); - var exception = await Assert.ThrowsExceptionAsync( + ProvisioningTransportException exception = await Assert.ThrowsExceptionAsync( () => TestInvalidServiceCertificate(transport)).ConfigureAwait(false); Assert.IsInstanceOfType(exception.InnerException.InnerException.InnerException, typeof(AuthenticationException)); @@ -100,7 +100,7 @@ private static async Task TestInvalidServiceCertificate(ProvisioningTransportHan { using X509Certificate2 cert = TestConfiguration.Provisioning.GetIndividualEnrollmentCertificate(); using var security = new SecurityProviderX509Certificate(cert); - ProvisioningDeviceClient provisioningDeviceClient = ProvisioningDeviceClient.Create( + var provisioningDeviceClient = ProvisioningDeviceClient.Create( TestConfiguration.Provisioning.GlobalDeviceEndpointInvalidServiceCertificate, "0ne00000001", security, diff --git a/e2e/test/provisioning/ProvisioningE2ETests.cs b/e2e/test/provisioning/ProvisioningE2ETests.cs index 5f56f48c22..61c73f1698 100644 --- a/e2e/test/provisioning/ProvisioningE2ETests.cs +++ b/e2e/test/provisioning/ProvisioningE2ETests.cs @@ -4,14 +4,12 @@ using System; using System.Collections.Generic; using System.Net; -using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Devices.Client; -using Microsoft.Azure.Devices.E2ETests.Helpers; using Microsoft.Azure.Devices.Provisioning.Client; using Microsoft.Azure.Devices.Provisioning.Client.Transport; using Microsoft.Azure.Devices.Provisioning.Security.Samples; @@ -559,7 +557,7 @@ private async Task ProvisioningDeviceClientValidRegistrationIdRegisterOkAsync( transport.Proxy = (proxyServerAddress != null) ? new WebProxy(s_proxyServerAddress) : null; } - ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( + var provClient = ProvisioningDeviceClient.Create( s_globalDeviceEndpoint, TestConfiguration.Provisioning.IdScope, security, @@ -577,14 +575,9 @@ private async Task ProvisioningDeviceClientValidRegistrationIdRegisterOkAsync( { try { - if (timeout != TimeSpan.MaxValue) - { - result = await provClient.RegisterAsync(timeout).ConfigureAwait(false); - } - else - { - result = await provClient.RegisterAsync(cts.Token).ConfigureAwait(false); - } + result = timeout != TimeSpan.MaxValue + ? await provClient.RegisterAsync(timeout).ConfigureAwait(false) + : await provClient.RegisterAsync(cts.Token).ConfigureAwait(false); break; } // Catching all ProvisioningTransportException as the status code is not the same for Mqtt, Amqp and Http. @@ -653,7 +646,7 @@ private async Task ProvisioningDeviceClientProvisioningFlowCustomAllocationAlloc transport.Proxy = (proxyServerAddress != null) ? new WebProxy(s_proxyServerAddress) : null; } - ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( + var provClient = ProvisioningDeviceClient.Create( s_globalDeviceEndpoint, TestConfiguration.Provisioning.IdScope, security, @@ -720,7 +713,7 @@ public async Task ProvisioningDeviceClient_InvalidRegistrationId_TpmRegister_Fai { using ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportProtocol); using SecurityProvider security = new SecurityProviderTpmSimulator("invalidregistrationid"); - ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( + var provClient = ProvisioningDeviceClient.Create( s_globalDeviceEndpoint, TestConfiguration.Provisioning.IdScope, security, @@ -829,7 +822,7 @@ private async Task ProvisioningDeviceClientInvalidIdScopeRegisterFailAsync( { using ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportProtocol); using SecurityProvider security = await CreateSecurityProviderFromNameAsync(attestationType, enrollmentType, groupId, null, AllocationPolicy.Hashed, null, null).ConfigureAwait(false); - ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( + var provClient = ProvisioningDeviceClient.Create( s_globalDeviceEndpoint, InvalidIdScope, security, @@ -837,7 +830,7 @@ private async Task ProvisioningDeviceClientInvalidIdScopeRegisterFailAsync( using var cts = new CancellationTokenSource(FailingTimeoutMiliseconds); - var exception = await Assert.ThrowsExceptionAsync( + ProvisioningTransportException exception = await Assert.ThrowsExceptionAsync( () => provClient.RegisterAsync(cts.Token)).ConfigureAwait(false); Logger.Trace($"Exception: {exception}"); @@ -887,7 +880,7 @@ private async Task ProvisioningDeviceClientInvalidGlobalAddressRegisterFailAsync using ProvisioningTransportHandler transport = CreateTransportHandlerFromName(transportProtocol); using SecurityProvider security = await CreateSecurityProviderFromNameAsync(attestationType, enrollmentType, groupId, null, AllocationPolicy.Hashed, null, null).ConfigureAwait(false); - ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( + var provClient = ProvisioningDeviceClient.Create( InvalidGlobalAddress, TestConfiguration.Provisioning.IdScope, security, @@ -936,7 +929,7 @@ public static ProvisioningTransportHandler CreateTransportHandlerFromName(Client /// CreateSecurityProviderFromNameAsync(Attesta { _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromNameAsync)}({attestationType})"); - using ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); + using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); switch (attestationType) { @@ -1016,7 +1009,7 @@ private async Task CreateSecurityProviderFromNameAsync(Attesta case EnrollmentType.Group: EnrollmentGroup symmetricKeyEnrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, AttestationMechanismType.SymmetricKey, groupId, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs, capabilities).ConfigureAwait(false); Assert.IsTrue(symmetricKeyEnrollmentGroup.Attestation is SymmetricKeyAttestation); - SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollmentGroup.Attestation; + var symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollmentGroup.Attestation; string registrationIdSymmetricKey = _idPrefix + Guid.NewGuid(); string primaryKeyEnrollmentGroup = symmetricKeyAttestation.PrimaryKey; string secondaryKeyEnrollmentGroup = symmetricKeyAttestation.SecondaryKey; diff --git a/e2e/test/provisioning/ProvisioningServiceClientE2ETests.cs b/e2e/test/provisioning/ProvisioningServiceClientE2ETests.cs index 3757ae6825..1ada9be022 100644 --- a/e2e/test/provisioning/ProvisioningServiceClientE2ETests.cs +++ b/e2e/test/provisioning/ProvisioningServiceClientE2ETests.cs @@ -76,7 +76,7 @@ public async Task ProvisioningServiceClient_SymmetricKey_GroupEnrollments_Create //This webhook won't actually work for reprovisioning, but this test is only testing that the field is accepted by the service var customAllocationDefinition = new CustomAllocationDefinition { ApiVersion = "2019-03-31", WebhookUrl = "https://www.microsoft.com" }; var reprovisionPolicy = new ReprovisionPolicy { MigrateDeviceData = false, UpdateHubAssignment = true }; - var allocationPolicy = AllocationPolicy.GeoLatency; + AllocationPolicy allocationPolicy = AllocationPolicy.GeoLatency; await ProvisioningServiceClient_GroupEnrollments_Create_Ok("", AttestationMechanismType.SymmetricKey, reprovisionPolicy, allocationPolicy, customAllocationDefinition, null).ConfigureAwait(false); } @@ -112,7 +112,7 @@ public async Task ProvisioningServiceClient_GetEnrollmentGroupAttestation_Symmet public async Task ProvisioningServiceClient_GetIndividualEnrollmentAttestation(AttestationMechanismType attestationType) { - using ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); + using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); IndividualEnrollment individualEnrollment = await CreateIndividualEnrollment(provisioningServiceClient, attestationType, null, AllocationPolicy.Static, null, null, null); AttestationMechanism attestationMechanism = await provisioningServiceClient.GetIndividualEnrollmentAttestationAsync(individualEnrollment.RegistrationId); @@ -120,21 +120,21 @@ public async Task ProvisioningServiceClient_GetIndividualEnrollmentAttestation(A if (attestationType == AttestationMechanismType.SymmetricKey) { Assert.AreEqual(AttestationMechanismType.SymmetricKey, attestationMechanism.Type); - SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation(); + var symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((SymmetricKeyAttestation)individualEnrollment.Attestation).PrimaryKey, symmetricKeyAttestation.PrimaryKey); Assert.AreEqual(((SymmetricKeyAttestation)individualEnrollment.Attestation).SecondaryKey, symmetricKeyAttestation.SecondaryKey); } else if (attestationType == AttestationMechanismType.X509) { Assert.AreEqual(AttestationMechanismType.X509, attestationMechanism.Type); - X509Attestation x509Attestation = (X509Attestation)attestationMechanism.GetAttestation(); + var x509Attestation = (X509Attestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((X509Attestation)individualEnrollment.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint); Assert.AreEqual(((X509Attestation)individualEnrollment.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint); } else { Assert.AreEqual(AttestationMechanismType.Tpm, attestationMechanism.Type); - TpmAttestation tpmAttestation = (TpmAttestation)attestationMechanism.GetAttestation(); + var tpmAttestation = (TpmAttestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((TpmAttestation)individualEnrollment.Attestation).EndorsementKey, tpmAttestation.EndorsementKey); Assert.AreEqual(((TpmAttestation)individualEnrollment.Attestation).StorageRootKey, tpmAttestation.StorageRootKey); } @@ -142,7 +142,7 @@ public async Task ProvisioningServiceClient_GetIndividualEnrollmentAttestation(A public async Task ProvisioningServiceClient_GetEnrollmentGroupAttestation(AttestationMechanismType attestationType) { - using ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); + using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); string groupId = AttestationTypeToString(attestationType) + "-" + Guid.NewGuid(); EnrollmentGroup enrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, attestationType, groupId, null, AllocationPolicy.Static, null, null, null); @@ -152,14 +152,14 @@ public async Task ProvisioningServiceClient_GetEnrollmentGroupAttestation(Attest if (attestationType == AttestationMechanismType.SymmetricKey) { Assert.AreEqual(AttestationMechanismType.SymmetricKey, attestationMechanism.Type); - SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation(); + var symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((SymmetricKeyAttestation)enrollmentGroup.Attestation).PrimaryKey, symmetricKeyAttestation.PrimaryKey); Assert.AreEqual(((SymmetricKeyAttestation)enrollmentGroup.Attestation).SecondaryKey, symmetricKeyAttestation.SecondaryKey); } else if (attestationType == AttestationMechanismType.X509) { Assert.AreEqual(AttestationMechanismType.X509, attestationMechanism.Type); - X509Attestation x509Attestation = (X509Attestation)attestationMechanism.GetAttestation(); + var x509Attestation = (X509Attestation)attestationMechanism.GetAttestation(); Assert.AreEqual(((X509Attestation)enrollmentGroup.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint); Assert.AreEqual(((X509Attestation)enrollmentGroup.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint); } @@ -266,7 +266,7 @@ public static async Task CreateIndividualEnrollment(Provis using (var tpmSim = new SecurityProviderTpmSimulator(registrationId)) { string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey()); - using ProvisioningServiceClient provisioningService = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); + using var provisioningService = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString); individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek)) { Capabilities = capabilities, diff --git a/e2e/test/provisioning/ReprovisioningE2ETests.cs b/e2e/test/provisioning/ReprovisioningE2ETests.cs index f647a52d02..d80d2170ef 100644 --- a/e2e/test/provisioning/ReprovisioningE2ETests.cs +++ b/e2e/test/provisioning/ReprovisioningE2ETests.cs @@ -211,7 +211,7 @@ public async Task ProvisioningDeviceClient_ReprovisioningBlockingWorks_MqttWs_Sy /// private async Task ProvisioningDeviceClient_ReprovisioningFlow_ResetTwin(Client.TransportType transportProtocol, AttestationMechanismType attestationType, EnrollmentType enrollmentType, bool setCustomProxy, string customServerProxy = null) { - IotHubConnectionStringBuilder connectionString = IotHubConnectionStringBuilder.Create(TestConfiguration.IoTHub.ConnectionString); + var connectionString = IotHubConnectionStringBuilder.Create(TestConfiguration.IoTHub.ConnectionString); ICollection iotHubsToStartAt = new List() { TestConfiguration.Provisioning.FarAwayIotHubHostName }; ICollection iotHubsToReprovisionTo = new List() { connectionString.HostName }; await ProvisioningDeviceClient_ReprovisioningFlow(transportProtocol, attestationType, enrollmentType, setCustomProxy, new ReprovisionPolicy { MigrateDeviceData = false, UpdateHubAssignment = true }, AllocationPolicy.Hashed, null, iotHubsToStartAt, iotHubsToReprovisionTo, customServerProxy).ConfigureAwait(false); @@ -223,7 +223,7 @@ private async Task ProvisioningDeviceClient_ReprovisioningFlow_ResetTwin(Client. /// private async Task ProvisioningDeviceClient_ReprovisioningFlow_KeepTwin(Client.TransportType transportProtocol, AttestationMechanismType attestationType, EnrollmentType enrollmentType, bool setCustomProxy, string customServerProxy = null) { - IotHubConnectionStringBuilder connectionString = IotHubConnectionStringBuilder.Create(TestConfiguration.IoTHub.ConnectionString); + var connectionString = IotHubConnectionStringBuilder.Create(TestConfiguration.IoTHub.ConnectionString); ICollection iotHubsToStartAt = new List() { TestConfiguration.Provisioning.FarAwayIotHubHostName }; ICollection iotHubsToReprovisionTo = new List() { connectionString.HostName }; await ProvisioningDeviceClient_ReprovisioningFlow(transportProtocol, attestationType, enrollmentType, setCustomProxy, new ReprovisionPolicy { MigrateDeviceData = true, UpdateHubAssignment = true }, AllocationPolicy.Hashed, null, iotHubsToStartAt, iotHubsToReprovisionTo, customServerProxy).ConfigureAwait(false); @@ -234,7 +234,7 @@ private async Task ProvisioningDeviceClient_ReprovisioningFlow_KeepTwin(Client.T /// private async Task ProvisioningDeviceClient_ReprovisioningFlow_DoNotReprovision(Client.TransportType transportProtocol, AttestationMechanismType attestationType, EnrollmentType enrollmentType, bool setCustomProxy, string customServerProxy = null) { - IotHubConnectionStringBuilder connectionString = IotHubConnectionStringBuilder.Create(TestConfiguration.IoTHub.ConnectionString); + var connectionString = IotHubConnectionStringBuilder.Create(TestConfiguration.IoTHub.ConnectionString); ICollection iotHubsToStartAt = new List() { TestConfiguration.Provisioning.FarAwayIotHubHostName }; ICollection iotHubsToReprovisionTo = new List() { connectionString.HostName }; await ProvisioningDeviceClient_ReprovisioningFlow(transportProtocol, attestationType, enrollmentType, setCustomProxy, new ReprovisionPolicy { MigrateDeviceData = false, UpdateHubAssignment = false }, AllocationPolicy.Hashed, null, iotHubsToStartAt, iotHubsToReprovisionTo, customServerProxy).ConfigureAwait(false); @@ -281,7 +281,7 @@ public async Task ProvisioningDeviceClient_ReprovisioningFlow( transport.Proxy = (proxyServerAddress != null) ? new WebProxy(s_proxyServerAddress) : null; } - ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create( + var provClient = ProvisioningDeviceClient.Create( s_globalDeviceEndpoint, TestConfiguration.Provisioning.IdScope, security, @@ -320,7 +320,7 @@ public async Task ProvisioningDeviceClient_ReprovisioningFlow( /// private async Task ConfirmRegisteredDeviceWorks(DeviceRegistrationResult result, Client.IAuthenticationMethod auth, Client.TransportType transportProtocol, bool sendReportedPropertiesUpdate) { - using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, transportProtocol)) + using (var iotClient = DeviceClient.Create(result.AssignedHub, auth, transportProtocol)) { Logger.Trace("DeviceClient OpenAsync."); await iotClient.OpenAsync().ConfigureAwait(false); @@ -346,7 +346,7 @@ private async Task ConfirmExpectedDeviceCapabilities(DeviceRegistrationResult re if (capabilities != null) { //hardcoding amqp since http does not support twin, but tests that call into this may use http - using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, Client.TransportType.Amqp)) + using (var iotClient = DeviceClient.Create(result.AssignedHub, auth, Client.TransportType.Amqp)) { //Confirm that the device twin reflects what the enrollment dictated Twin twin = await iotClient.GetTwinAsync().ConfigureAwait(false); @@ -369,7 +369,7 @@ private async Task CreateSecurityProviderFromName(AttestationM string base64Ek = Convert.ToBase64String(tpmSim.GetEndorsementKey()); - using (ProvisioningServiceClient provisioningService = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString)) + using (var provisioningService = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString)) { Logger.Trace($"Getting enrollment: RegistrationID = {registrationId}"); var individualEnrollment = new IndividualEnrollment(registrationId, new TpmAttestation(base64Ek)) { AllocationPolicy = allocationPolicy, ReprovisionPolicy = reprovisionPolicy, IotHubs = iothubs, CustomAllocationDefinition = customAllocationDefinition, Capabilities = capabilities }; @@ -409,7 +409,7 @@ private async Task CreateSecurityProviderFromName(AttestationM case EnrollmentType.Group: EnrollmentGroup symmetricKeyEnrollmentGroup = await CreateEnrollmentGroup(provisioningServiceClient, AttestationMechanismType.SymmetricKey, groupId, reprovisionPolicy, allocationPolicy, customAllocationDefinition, iothubs, capabilities).ConfigureAwait(false); Assert.IsTrue(symmetricKeyEnrollmentGroup.Attestation is SymmetricKeyAttestation); - SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollmentGroup.Attestation; + var symmetricKeyAttestation = (SymmetricKeyAttestation)symmetricKeyEnrollmentGroup.Attestation; string registrationIdSymmetricKey = _devicePrefix + Guid.NewGuid(); string primaryKeyEnrollmentGroup = symmetricKeyAttestation.PrimaryKey; string secondaryKeyEnrollmentGroup = symmetricKeyAttestation.SecondaryKey; @@ -525,7 +525,7 @@ private void ConfirmDeviceInExpectedHub(DeviceRegistrationResult result, Reprovi private async Task ConfirmDeviceWorksAfterReprovisioning(DeviceRegistrationResult result, Client.IAuthenticationMethod auth, Client.TransportType transportProtocol, ReprovisionPolicy reprovisionPolicy, bool twinOperationsAllowed) { - using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth, transportProtocol)) + using (var iotClient = DeviceClient.Create(result.AssignedHub, auth, transportProtocol)) { Logger.Trace("DeviceClient OpenAsync."); await iotClient.OpenAsync().ConfigureAwait(false); diff --git a/iothub/device/src/AuthenticationMethodFactory.cs b/iothub/device/src/AuthenticationMethodFactory.cs index 85f68a908d..c371040a20 100644 --- a/iothub/device/src/AuthenticationMethodFactory.cs +++ b/iothub/device/src/AuthenticationMethodFactory.cs @@ -33,16 +33,14 @@ internal static IAuthenticationMethod GetAuthenticationMethod(IotHubConnectionSt } else if (iotHubConnectionStringBuilder.SharedAccessSignature != null) { - if (iotHubConnectionStringBuilder.ModuleId != null) - { - return new ModuleAuthenticationWithToken( - iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.ModuleId, iotHubConnectionStringBuilder.SharedAccessSignature); - } - else - { - return new DeviceAuthenticationWithToken( - iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessSignature); - } + return iotHubConnectionStringBuilder.ModuleId != null + ? new ModuleAuthenticationWithToken( + iotHubConnectionStringBuilder.DeviceId, + iotHubConnectionStringBuilder.ModuleId, + iotHubConnectionStringBuilder.SharedAccessSignature) + : (IAuthenticationMethod)new DeviceAuthenticationWithToken( + iotHubConnectionStringBuilder.DeviceId, + iotHubConnectionStringBuilder.SharedAccessSignature); } else if (iotHubConnectionStringBuilder.UsingX509Cert) { diff --git a/iothub/device/src/ClientFactory.cs b/iothub/device/src/ClientFactory.cs index 3532c5516c..3ab6d9b710 100644 --- a/iothub/device/src/ClientFactory.cs +++ b/iothub/device/src/ClientFactory.cs @@ -122,12 +122,11 @@ internal static InternalClient Create( throw new ArgumentException("No certificate was found. To use certificate authentication certificate must be present."); } -#pragma warning disable CA2000 // This is returned to client so cannot be disposed here. InternalClient dc = CreateFromConnectionString( connectionStringBuilder.ToString(), PopulateCertificateInTransportSettings(connectionStringBuilder, transportType), options); -#pragma warning restore CA2000 + dc.Certificate = connectionStringBuilder.Certificate; // Install all the intermediate certificates in the chain if specified. @@ -438,7 +437,7 @@ internal static InternalClient CreateFromConnectionString( builder.SasTokenRenewalBuffer = options?.SasTokenRenewalBuffer ?? default; } - IotHubConnectionString iotHubConnectionString = builder.ToIotHubConnectionString(); + var iotHubConnectionString = builder.ToIotHubConnectionString(); foreach (ITransportSettings transportSetting in transportSettings) { @@ -612,7 +611,7 @@ private static ITransportSettings[] PopulateCertificateInTransportSettings( private static ITransportSettings[] PopulateCertificateInTransportSettings(IotHubConnectionStringBuilder connectionStringBuilder, ITransportSettings[] transportSettings) { - foreach (var transportSetting in transportSettings) + foreach (ITransportSettings transportSetting in transportSettings) { switch (transportSetting.GetTransportType()) { diff --git a/iothub/device/src/Common/Amqp/ClientWebSocketTransport.cs b/iothub/device/src/Common/Amqp/ClientWebSocketTransport.cs index e17018693b..da7e9f7eb3 100644 --- a/iothub/device/src/Common/Amqp/ClientWebSocketTransport.cs +++ b/iothub/device/src/Common/Amqp/ClientWebSocketTransport.cs @@ -249,7 +249,7 @@ private static void OnReadComplete(IAsyncResult result) private static void HandleReadComplete(IAsyncResult result) { - Task taskResult = (Task)result; + var taskResult = (Task)result; var args = (TransportAsyncCallbackArgs)taskResult.AsyncState; ReadTaskDone(taskResult, args); @@ -291,7 +291,7 @@ private static void OnWriteComplete(IAsyncResult result) private static void HandleWriteComplete(IAsyncResult result) { - Task taskResult = (Task)result; + var taskResult = (Task)result; var args = (TransportAsyncCallbackArgs)taskResult.AsyncState; WriteTaskDone(taskResult, args); args.CompletedCallback(args); diff --git a/iothub/device/src/Common/Extensions/CommonExtensions.cs b/iothub/device/src/Common/Extensions/CommonExtensions.cs index 95f2c6ddb1..944e21eda8 100644 --- a/iothub/device/src/Common/Extensions/CommonExtensions.cs +++ b/iothub/device/src/Common/Extensions/CommonExtensions.cs @@ -121,7 +121,7 @@ public static string GetMaskedClientIpAddress(this HttpRequestMessage requestMes // note that this only works if we are hosted as an OWIN app if (requestMessage.Properties.ContainsKey("MS_OwinContext")) { - OwinContext owinContext = requestMessage.Properties["MS_OwinContext"] as OwinContext; + var owinContext = requestMessage.Properties["MS_OwinContext"] as OwinContext; if (owinContext != null) { string remoteIpAddress = owinContext.Request.RemoteIpAddress; diff --git a/iothub/device/src/Common/Fx.cs b/iothub/device/src/Common/Fx.cs index 14dc31e8ec..12d03b05b6 100644 --- a/iothub/device/src/Common/Fx.cs +++ b/iothub/device/src/Common/Fx.cs @@ -212,7 +212,7 @@ internal static Type[] BreakOnExceptionTypes string[] typeNames = value as string[]; if (typeNames != null && typeNames.Length > 0) { - List types = new List(typeNames.Length); + var types = new List(typeNames.Length); for (int i = 0; i < typeNames.Length; i++) { types.Add(Type.GetType(typeNames[i], false)); diff --git a/iothub/device/src/Common/PartialTrustHelpers.cs b/iothub/device/src/Common/PartialTrustHelpers.cs index fbd857815e..0d7976e9bd 100644 --- a/iothub/device/src/Common/PartialTrustHelpers.cs +++ b/iothub/device/src/Common/PartialTrustHelpers.cs @@ -173,7 +173,7 @@ internal static bool HasEtwPermissions() throw new NotImplementedException(); #else //Currently unrestricted permissions are required to create Etw provider. - PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted); + var permissions = new PermissionSet(PermissionState.Unrestricted); return CheckAppDomainPermissions(permissions); #endif } diff --git a/iothub/device/src/Common/ReadOnlyDictionary45.cs b/iothub/device/src/Common/ReadOnlyDictionary45.cs index 7faf42c1a6..f63baf8af2 100644 --- a/iothub/device/src/Common/ReadOnlyDictionary45.cs +++ b/iothub/device/src/Common/ReadOnlyDictionary45.cs @@ -283,7 +283,7 @@ bool IDictionary.Contains(object key) IDictionaryEnumerator IDictionary.GetEnumerator() { - IDictionary d = Dictionary as IDictionary; + var d = Dictionary as IDictionary; if (d != null) { return d.GetEnumerator(); @@ -352,17 +352,17 @@ void ICollection.CopyTo(Array array, int index) throw Fx.Exception.Argument(nameof(array), Resources.InvalidBufferSize); } - KeyValuePair[] pairs = array as KeyValuePair[]; + var pairs = array as KeyValuePair[]; if (pairs != null) { Dictionary.CopyTo(pairs, index); } else { - DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; + var dictEntryArray = array as DictionaryEntry[]; if (dictEntryArray != null) { - foreach (var item in Dictionary) + foreach (KeyValuePair item in Dictionary) { dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value); } @@ -377,7 +377,7 @@ void ICollection.CopyTo(Array array, int index) try { - foreach (var item in Dictionary) + foreach (KeyValuePair item in Dictionary) { objects[index++] = new KeyValuePair(item.Key, item.Value); } @@ -401,7 +401,7 @@ object ICollection.SyncRoot { if (_syncRoot == null) { - ICollection c = Dictionary as ICollection; + var c = Dictionary as ICollection; if (c != null) { _syncRoot = c.SyncRoot; @@ -568,7 +568,7 @@ object ICollection.SyncRoot { if (_syncRoot == null) { - ICollection c = _collection as ICollection; + var c = _collection as ICollection; if (c != null) { _syncRoot = c.SyncRoot; @@ -715,7 +715,7 @@ object ICollection.SyncRoot { if (m_syncRoot == null) { - ICollection c = m_collection as ICollection; + var c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; diff --git a/iothub/device/src/Common/SynchronizedPool.cs b/iothub/device/src/Common/SynchronizedPool.cs index 5fce4fc1b4..25ca74a7bd 100644 --- a/iothub/device/src/Common/SynchronizedPool.cs +++ b/iothub/device/src/Common/SynchronizedPool.cs @@ -201,7 +201,7 @@ private void RecordTakeFromGlobalPool(int thisThreadID) } else { - PendingEntry[] newPending = new PendingEntry[localPending.Length * 2]; + var newPending = new PendingEntry[localPending.Length * 2]; Array.Copy(localPending, newPending, localPending.Length); this.pending = newPending; } diff --git a/iothub/device/src/Common/TaskHelpers.cs b/iothub/device/src/Common/TaskHelpers.cs index a258da2980..6fffea7e20 100644 --- a/iothub/device/src/Common/TaskHelpers.cs +++ b/iothub/device/src/Common/TaskHelpers.cs @@ -122,7 +122,7 @@ internal static void MarshalTaskResults(Task source, TaskCompletionSour break; case TaskStatus.RanToCompletion: - Task castedSource = source as Task; + var castedSource = source as Task; proxy.TrySetResult( castedSource == null ? default(TResult) : // source is a Task castedSource.Result); // source is a Task diff --git a/iothub/device/src/Common/Utils.cs b/iothub/device/src/Common/Utils.cs index a858b3ed2a..11baccaa08 100644 --- a/iothub/device/src/Common/Utils.cs +++ b/iothub/device/src/Common/Utils.cs @@ -115,7 +115,7 @@ public static IReadOnlyDictionary MergeDictionaries( throw new ArgumentNullException(nameof(dictionaries), "Provided dictionaries should not be null"); } - Dictionary result = dictionaries.SelectMany(dict => dict) + var result = dictionaries.SelectMany(dict => dict) .ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); diff --git a/iothub/device/src/GlobalSuppressions.cs b/iothub/device/src/GlobalSuppressions.cs index 30c80222e1..0dc33d307d 100644 --- a/iothub/device/src/GlobalSuppressions.cs +++ b/iothub/device/src/GlobalSuppressions.cs @@ -7,7 +7,35 @@ using System.Diagnostics.CodeAnalysis; -[assembly: SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] -[assembly: SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Public API cannot be changed.", Scope = "type", Target = "~T:Microsoft.Azure.Devices.Client.ConnectionStatusChangeReason")] -[assembly: SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "Public API cannot be changed.", Scope = "type", Target = "~T:Microsoft.Azure.Devices.Client.ConnectionStatus")] +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] +[assembly: SuppressMessage( + "Naming", + "CA1707:Identifiers should not contain underscores", + Justification = "Public API cannot be changed.", + Scope = "type", + Target = "~T:Microsoft.Azure.Devices.Client.ConnectionStatusChangeReason")] +[assembly: SuppressMessage( + "Naming", + "CA1707:Identifiers should not contain underscores", + Justification = "Public API cannot be changed.", + Scope = "type", + Target = "~T:Microsoft.Azure.Devices.Client.ConnectionStatus")] +[assembly: SuppressMessage( + "Style", + "IDE0011:Add braces", + Justification = "Agreement in the team to keep this style as is for logging methods only.", + Scope = "module")] +[assembly: SuppressMessage( + "CodeQuality", + "IDE0079:Remove unnecessary suppression", + Justification = "Each frameworks consider certain suppressions required by other frameworks unnecessary.", + Scope = "module")] diff --git a/iothub/device/src/IotHubClientDiagnostic.cs b/iothub/device/src/IotHubClientDiagnostic.cs index 4ed50de462..603576b4a4 100644 --- a/iothub/device/src/IotHubClientDiagnostic.cs +++ b/iothub/device/src/IotHubClientDiagnostic.cs @@ -34,7 +34,7 @@ internal static bool HasDiagnosticProperties(Message message) private static string GenerateEightRandomCharacters() { - var stringChars = new char[8]; + char[] stringChars = new char[8]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { diff --git a/iothub/device/src/ModernDotNet/HsmAuthentication/Transport/HttpUdsMessageHandler.cs b/iothub/device/src/ModernDotNet/HsmAuthentication/Transport/HttpUdsMessageHandler.cs index 66a0ea0372..62889cf2d3 100644 --- a/iothub/device/src/ModernDotNet/HsmAuthentication/Transport/HttpUdsMessageHandler.cs +++ b/iothub/device/src/ModernDotNet/HsmAuthentication/Transport/HttpUdsMessageHandler.cs @@ -40,7 +40,7 @@ protected override async Task SendAsync(HttpRequestMessage private async Task GetConnectedSocketAsync() { - Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); + var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); // The Edge Agent uses unix sockets for communication with the modules deployed in docker for HSM. // For netstandard 2.0 there was no implementation for a Unix Domain Socket (UDS) so we used a version diff --git a/iothub/device/src/TransientFaultHandling/AsyncExecution[T].cs b/iothub/device/src/TransientFaultHandling/AsyncExecution[T].cs index 7645591a68..278ca97689 100644 --- a/iothub/device/src/TransientFaultHandling/AsyncExecution[T].cs +++ b/iothub/device/src/TransientFaultHandling/AsyncExecution[T].cs @@ -79,7 +79,7 @@ private Task ExecuteAsyncImpl(Task ignore) { return this.previousTask; } - TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); + var taskCompletionSource = new TaskCompletionSource(); taskCompletionSource.TrySetCanceled(); return taskCompletionSource.Task; } @@ -96,7 +96,7 @@ private Task ExecuteAsyncImpl(Task ignore) { throw; } - TaskCompletionSource taskCompletionSource2 = new TaskCompletionSource(); + var taskCompletionSource2 = new TaskCompletionSource(); taskCompletionSource2.TrySetException(ex); task = taskCompletionSource2.Task; } diff --git a/iothub/device/src/Transport/Amqp/AmqpTransportHandler.cs b/iothub/device/src/Transport/Amqp/AmqpTransportHandler.cs index f38a52ef62..df4ab761d6 100644 --- a/iothub/device/src/Transport/Amqp/AmqpTransportHandler.cs +++ b/iothub/device/src/Transport/Amqp/AmqpTransportHandler.cs @@ -21,7 +21,7 @@ internal class AmqpTransportHandler : TransportHandler protected AmqpUnit _amqpUnit; private readonly Action _onDesiredStatePatchListener; private readonly object _lock = new object(); - private ConcurrentDictionary> _twinResponseCompletions = new ConcurrentDictionary>(); + private readonly ConcurrentDictionary> _twinResponseCompletions = new ConcurrentDictionary>(); private bool _closed; static AmqpTransportHandler() @@ -478,7 +478,7 @@ public override async Task EnableEventReceiveAsync(bool isAnEdgeModule, Cancella { Logging.Exit(this, cancellationToken, nameof(EnableEventReceiveAsync)); } - } + } else { await EnableReceiveMessageAsync(cancellationToken).ConfigureAwait(false); diff --git a/iothub/device/src/Transport/AmqpIot/AmqpIotSendingLink.cs b/iothub/device/src/Transport/AmqpIot/AmqpIotSendingLink.cs index cfbd235133..5c8f290897 100644 --- a/iothub/device/src/Transport/AmqpIot/AmqpIotSendingLink.cs +++ b/iothub/device/src/Transport/AmqpIot/AmqpIotSendingLink.cs @@ -117,7 +117,7 @@ internal async Task SendMessagesAsync(IEnumerable messa } Outcome outcome; - using (AmqpMessage amqpMessage = AmqpMessage.Create(messageList)) + using (var amqpMessage = AmqpMessage.Create(messageList)) { amqpMessage.MessageFormat = AmqpConstants.AmqpBatchedMessageFormat; outcome = await SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false); diff --git a/iothub/device/src/Transport/AmqpIot/AmqpIotTransport.cs b/iothub/device/src/Transport/AmqpIot/AmqpIotTransport.cs index 4af039ddb6..3406e2a13d 100644 --- a/iothub/device/src/Transport/AmqpIot/AmqpIotTransport.cs +++ b/iothub/device/src/Transport/AmqpIot/AmqpIotTransport.cs @@ -117,7 +117,7 @@ private async Task CreateClientWebSocketTransportAsync(Cancellati || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1)) { - var websocket = await CreateLegacyClientWebSocketAsync( + IotHubClientWebSocket websocket = await CreateLegacyClientWebSocketAsync( websocketUri, this._amqpTransportSettings.ClientCertificate, cancellationToken) diff --git a/iothub/device/src/Transport/DefaultDelegatingHandler.cs b/iothub/device/src/Transport/DefaultDelegatingHandler.cs index 355cb32507..8c2959b339 100644 --- a/iothub/device/src/Transport/DefaultDelegatingHandler.cs +++ b/iothub/device/src/Transport/DefaultDelegatingHandler.cs @@ -30,10 +30,7 @@ protected DefaultDelegatingHandler(IPipelineContext context, IDelegatingHandler public IDelegatingHandler InnerHandler { - get - { - return _innerHandler; - } + get => _innerHandler; protected set { _innerHandler = value; diff --git a/iothub/device/src/Transport/ErrorDelegatingHandler.cs b/iothub/device/src/Transport/ErrorDelegatingHandler.cs index 9c17a5e97d..a75e34570b 100644 --- a/iothub/device/src/Transport/ErrorDelegatingHandler.cs +++ b/iothub/device/src/Transport/ErrorDelegatingHandler.cs @@ -158,9 +158,12 @@ private static bool IsSecurityExceptionChain(Exception exceptionChain) private static bool IsTlsSecurity(Exception singleException) { if (// WinHttpException (0x80072F8F): A security error occurred. - (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && (singleException.HResult == unchecked((int)0x80072F8F))) || + (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) + && singleException.HResult == unchecked((int)0x80072F8F)) + || // CURLE_SSL_CACERT (60): Peer certificate cannot be authenticated with known CA certificates. - (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && (singleException.HResult == 60)) || + (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && singleException.HResult == 60) + || singleException is AuthenticationException) { return true; diff --git a/iothub/device/src/Transport/Mqtt/MqttIotHubAdapter.cs b/iothub/device/src/Transport/Mqtt/MqttIotHubAdapter.cs index 3ef42f0769..f26b7a7ce1 100644 --- a/iothub/device/src/Transport/Mqtt/MqttIotHubAdapter.cs +++ b/iothub/device/src/Transport/Mqtt/MqttIotHubAdapter.cs @@ -5,6 +5,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; @@ -235,7 +236,7 @@ public override void ChannelRead(IChannelHandlerContext context, object message) // If a message is received when the state is Connected or a CONNACK is received when the state is Connecting, then the message should be processed. if (IsInState(StateFlags.Connected) || IsInState(StateFlags.Connecting) && packet.PacketType == PacketType.CONNACK) { - ProcessMessage(context, packet); + ProcessMessageAsync(context, packet); } else { @@ -697,10 +698,10 @@ private void ProcessUnsubAck(IChannelHandlerContext context, UnsubAckPacket pack #region Receiving - private async void ProcessMessage(IChannelHandlerContext context, Packet packet) + private async void ProcessMessageAsync(IChannelHandlerContext context, Packet packet) { if (Logging.IsEnabled) - Logging.Enter(this, context.Name, packet.PacketType, nameof(ProcessMessage)); + Logging.Enter(this, context.Name, packet.PacketType, nameof(ProcessMessageAsync)); try { @@ -732,7 +733,7 @@ private async void ProcessMessage(IChannelHandlerContext context, Packet packet) default: if (Logging.IsEnabled) - Logging.Error(context, $"Received an unexpected packet type {packet.PacketType}, will shut down.", nameof(ProcessMessage)); + Logging.Error(context, $"Received an unexpected packet type {packet.PacketType}, will shut down.", nameof(ProcessMessageAsync)); ShutdownOnErrorAsync(context, new InvalidOperationException($"Unexpected packet type {packet.PacketType}")); break; @@ -741,18 +742,18 @@ private async void ProcessMessage(IChannelHandlerContext context, Packet packet) catch (Exception ex) when (!ex.IsFatal()) { if (Logging.IsEnabled) - Logging.Error(context, $"Received a non-fatal exception while processing a received packet of type {packet.PacketType}, will shut down: {ex}", nameof(ProcessMessage)); + Logging.Error(context, $"Received a non-fatal exception while processing a received packet of type {packet.PacketType}, will shut down: {ex}", nameof(ProcessMessageAsync)); ShutdownOnErrorAsync(context, ex); } finally { if (Logging.IsEnabled) - Logging.Exit(this, context.Name, packet.PacketType, nameof(ProcessMessage)); + Logging.Exit(this, context.Name, packet.PacketType, nameof(ProcessMessageAsync)); } } - [System.Diagnostics.CodeAnalysis.SuppressMessage( + [SuppressMessage( "Reliability", "CA2000:Dispose objects before losing scope", Justification = "The created message is handed to the user and the user application is in charge of disposing the message.")] diff --git a/iothub/device/src/Transport/Mqtt/MqttIotHubAdapterFactory.cs b/iothub/device/src/Transport/Mqtt/MqttIotHubAdapterFactory.cs index 536a0bfcbe..d15395125a 100644 --- a/iothub/device/src/Transport/Mqtt/MqttIotHubAdapterFactory.cs +++ b/iothub/device/src/Transport/Mqtt/MqttIotHubAdapterFactory.cs @@ -1,17 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using System; - namespace Microsoft.Azure.Devices.Client.Transport.Mqtt { internal class MqttIotHubAdapterFactory { - private readonly MqttTransportSettings settings; + private readonly MqttTransportSettings _settings; public MqttIotHubAdapterFactory(MqttTransportSettings settings) { - this.settings = settings; + _settings = settings; } public MqttIotHubAdapter Create( @@ -21,7 +19,7 @@ public MqttIotHubAdapter Create( ProductInfo productInfo, ClientOptions options) { - IWillMessage willMessage = mqttTransportSettings.HasWill ? this.settings.WillMessage : null; + IWillMessage willMessage = mqttTransportSettings.HasWill ? _settings.WillMessage : null; return new MqttIotHubAdapter( iotHubConnectionString.DeviceId, diff --git a/iothub/device/src/Transport/Mqtt/MqttTransportHandler.cs b/iothub/device/src/Transport/Mqtt/MqttTransportHandler.cs index 9f52f42a88..84dbc6cd66 100644 --- a/iothub/device/src/Transport/Mqtt/MqttTransportHandler.cs +++ b/iothub/device/src/Transport/Mqtt/MqttTransportHandler.cs @@ -1389,7 +1389,7 @@ private static IEventLoopGroup GetEventLoopGroup() if (!string.IsNullOrWhiteSpace(envValue)) { string processorEventCountValue = Environment.ExpandEnvironmentVariables(envValue); - if (int.TryParse(processorEventCountValue, out var processorThreadCount)) + if (int.TryParse(processorEventCountValue, out int processorThreadCount)) { if (Logging.IsEnabled) Logging.Info(null, $"EventLoopGroup threads count {processorThreadCount}."); diff --git a/iothub/device/src/Transport/RetryDelegatingHandler.cs b/iothub/device/src/Transport/RetryDelegatingHandler.cs index 16a59ae9ef..1445db352e 100644 --- a/iothub/device/src/Transport/RetryDelegatingHandler.cs +++ b/iothub/device/src/Transport/RetryDelegatingHandler.cs @@ -53,9 +53,7 @@ private class TransientErrorStrategy : ITransientErrorDetectionStrategy { public bool IsTransient(Exception ex) { - return ex is IotHubException - ? ((IotHubException)ex).IsTransient - : false; + return ex is IotHubException exception && exception.IsTransient; } } @@ -837,8 +835,8 @@ await _internalRetryPolicy { Logging.Enter(this, timeoutHelper, nameof(OpenAsync)); - // Will throw on error. - await base.OpenAsync(timeoutHelper).ConfigureAwait(false); + // Will throw on error. + await base.OpenAsync(timeoutHelper).ConfigureAwait(false); _onConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); } catch (Exception ex) when (!ex.IsFatal()) @@ -852,7 +850,7 @@ await _internalRetryPolicy } } - + } // Triggered from connection loss event diff --git a/iothub/service/src/Common/Amqp/LegacyClientWebSocketTransport.cs b/iothub/service/src/Common/Amqp/LegacyClientWebSocketTransport.cs index 0ed936706e..91987b998e 100644 --- a/iothub/service/src/Common/Amqp/LegacyClientWebSocketTransport.cs +++ b/iothub/service/src/Common/Amqp/LegacyClientWebSocketTransport.cs @@ -197,7 +197,7 @@ protected override bool OpenInternal() protected override bool CloseInternal() { - var webSocketState = this.webSocket.State; + IotHubClientWebSocket.WebSocketState webSocketState = this.webSocket.State; if (webSocketState != IotHubClientWebSocket.WebSocketState.Closed && webSocketState != IotHubClientWebSocket.WebSocketState.Aborted) { this.CloseInternalAsync().Fork(); @@ -237,7 +237,7 @@ void OnReadComplete(IAsyncResult result) return; } - Task taskResult = (Task)result; + var taskResult = (Task)result; var args = (TransportAsyncCallbackArgs)taskResult.AsyncState; this.ReadTaskDone(taskResult, args); @@ -294,7 +294,7 @@ static void OnWriteComplete(IAsyncResult result) return; } - Task taskResult = (Task)result; + var taskResult = (Task)result; var args = (TransportAsyncCallbackArgs)taskResult.AsyncState; WriteTaskDone(taskResult, args); args.CompletedCallback(args); @@ -325,7 +325,7 @@ static bool WriteTaskDone(Task taskResult, TransportAsyncCallbackArgs args) void ThrowIfNotOpen() { - var webSocketState = this.webSocket.State; + IotHubClientWebSocket.WebSocketState webSocketState = this.webSocket.State; if (webSocketState == IotHubClientWebSocket.WebSocketState.Open) { return; diff --git a/iothub/service/src/Common/IOThreadScheduler.cs b/iothub/service/src/Common/IOThreadScheduler.cs index b08a2ccfef..69fc4951f4 100644 --- a/iothub/service/src/Common/IOThreadScheduler.cs +++ b/iothub/service/src/Common/IOThreadScheduler.cs @@ -176,7 +176,7 @@ private bool ScheduleCallbackHelper(Action callback, object state) if (wrapped) { // Wrapped around the circular buffer. Create a new, bigger IOThreadScheduler. - IOThreadScheduler next = + var next = new IOThreadScheduler(Math.Min(this.slots.Length * 2, MaximumCapacity), this.slotsLowPri.Length); Interlocked.CompareExchange(ref IOThreadScheduler.current, next, this); } @@ -234,7 +234,7 @@ private bool ScheduleCallbackLowPriHelper(Action callback, object state) if (wrapped) { - IOThreadScheduler next = + var next = new IOThreadScheduler(this.slots.Length, Math.Min(this.slotsLowPri.Length * 2, MaximumCapacity)); Interlocked.CompareExchange(ref IOThreadScheduler.current, next, this); } diff --git a/iothub/service/src/Common/InternalBufferManager.cs b/iothub/service/src/Common/InternalBufferManager.cs index 3006c792b0..831edd0ec6 100644 --- a/iothub/service/src/Common/InternalBufferManager.cs +++ b/iothub/service/src/Common/InternalBufferManager.cs @@ -181,7 +181,7 @@ public PooledBufferManager(long maxMemoryToPool, int maxBufferSize) { this.tuningLock = new object(); this.remainingMemory = maxMemoryToPool; - List bufferPoolList = new List(); + var bufferPoolList = new List(); for (int bufferSize = minBufferSize; ;) { @@ -236,7 +236,7 @@ private void ChangeQuota(ref BufferPool bufferPool, int delta) { BufferPool oldBufferPool = bufferPool; int newLimit = oldBufferPool.Limit + delta; - BufferPool newBufferPool = BufferPool.CreatePool(oldBufferPool.BufferSize, newLimit); + var newBufferPool = BufferPool.CreatePool(oldBufferPool.BufferSize, newLimit); for (int i = 0; i < newLimit; i++) { byte[] buffer = oldBufferPool.Take(); diff --git a/iothub/service/src/Common/PartialTrustHelpers.cs b/iothub/service/src/Common/PartialTrustHelpers.cs index 96b7de624d..f6a69e5280 100644 --- a/iothub/service/src/Common/PartialTrustHelpers.cs +++ b/iothub/service/src/Common/PartialTrustHelpers.cs @@ -173,7 +173,7 @@ internal static bool HasEtwPermissions() throw new NotImplementedException(); #else //Currently unrestricted permissions are required to create Etw provider. - PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted); + var permissions = new PermissionSet(PermissionState.Unrestricted); return CheckAppDomainPermissions(permissions); #endif } diff --git a/iothub/service/src/Common/ReadOnlyDictionary45.cs b/iothub/service/src/Common/ReadOnlyDictionary45.cs index 30e18eae75..afc25cc36c 100644 --- a/iothub/service/src/Common/ReadOnlyDictionary45.cs +++ b/iothub/service/src/Common/ReadOnlyDictionary45.cs @@ -348,7 +348,7 @@ void ICollection.CopyTo(Array array, int index) throw Fx.Exception.Argument(nameof(array), Resources.InvalidBufferSize); } - KeyValuePair[] pairs = array as KeyValuePair[]; + var pairs = array as KeyValuePair[]; if (pairs != null) { Dictionary.CopyTo(pairs, index); @@ -372,7 +372,7 @@ void ICollection.CopyTo(Array array, int index) try { - foreach (var item in Dictionary) + foreach (KeyValuePair item in Dictionary) { objects[index++] = new KeyValuePair(item.Key, item.Value); } diff --git a/iothub/service/src/Common/SingletonDictionary.cs b/iothub/service/src/Common/SingletonDictionary.cs index 50d2f01446..4561fb8e1a 100644 --- a/iothub/service/src/Common/SingletonDictionary.cs +++ b/iothub/service/src/Common/SingletonDictionary.cs @@ -23,7 +23,7 @@ public void Dispose() if (!this.disposed) { this.disposed = true; - foreach (var kvp in this.dictionary) + foreach (System.Collections.Generic.KeyValuePair> kvp in this.dictionary) { if (kvp.Value.Task.Status == TaskStatus.RanToCompletion) { diff --git a/iothub/service/src/DigitalTwin/DigitalTwinClient.cs b/iothub/service/src/DigitalTwin/DigitalTwinClient.cs index 9f434063d8..1e45bc8a13 100644 --- a/iothub/service/src/DigitalTwin/DigitalTwinClient.cs +++ b/iothub/service/src/DigitalTwin/DigitalTwinClient.cs @@ -229,8 +229,8 @@ protected virtual void Dispose(bool disposing) private DigitalTwinClient(string hostName, DigitalTwinServiceClientCredentials credentials, params DelegatingHandler[] handlers) { - var httpsEndpoint = new UriBuilder(HttpsEndpointPrefix, hostName).Uri; - var httpMessageHandler = HttpClientHelper.CreateDefaultHttpMessageHandler(null, httpsEndpoint, ServicePointHelpers.DefaultConnectionLeaseTimeout); + Uri httpsEndpoint = new UriBuilder(HttpsEndpointPrefix, hostName).Uri; + HttpMessageHandler httpMessageHandler = HttpClientHelper.CreateDefaultHttpMessageHandler(null, httpsEndpoint, ServicePointHelpers.DefaultConnectionLeaseTimeout); #pragma warning disable CA2000 // Dispose objects before losing scope (httpMessageHandlerWithDelegatingHandlers is disposed when the http client owning it is disposed) HttpMessageHandler httpMessageHandlerWithDelegatingHandlers = CreateHttpHandlerPipeline(httpMessageHandler, handlers); #pragma warning restore CA2000 // Dispose objects before losing scope diff --git a/iothub/service/src/GlobalSuppressions.cs b/iothub/service/src/GlobalSuppressions.cs index 7fc7c806ad..576697ce43 100644 --- a/iothub/service/src/GlobalSuppressions.cs +++ b/iothub/service/src/GlobalSuppressions.cs @@ -5,5 +5,20 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] +[assembly: SuppressMessage( + "Usage", + "CA2208:Instantiate argument exceptions correctly", + Justification = "SDK throws a more descriptive argument exception message.", + Scope = "module")] diff --git a/iothub/service/src/IotHubSasCredentialProperties.cs b/iothub/service/src/IotHubSasCredentialProperties.cs index ac7fe649aa..0af2131065 100644 --- a/iothub/service/src/IotHubSasCredentialProperties.cs +++ b/iothub/service/src/IotHubSasCredentialProperties.cs @@ -55,7 +55,7 @@ public override Task GetTokenAsync(Uri namespaceAddress, string applie // Parse the SAS token to find the expiration date and time. // SharedAccessSignature sr=ENCODED(dh://myiothub.azure-devices.net/a/b/c?myvalue1=a)&sig=&se=[&skn=] var tokenParts = _credential.Signature.Split('&').ToList(); - var expiresAtTokenPart = tokenParts.Where(tokenPart => tokenPart.StartsWith("se=", StringComparison.OrdinalIgnoreCase)); + IEnumerable expiresAtTokenPart = tokenParts.Where(tokenPart => tokenPart.StartsWith("se=", StringComparison.OrdinalIgnoreCase)); if (!expiresAtTokenPart.Any()) { @@ -70,8 +70,8 @@ public override Task GetTokenAsync(Uri namespaceAddress, string applie throw new InvalidOperationException($"Invalid seconds from epoch time on {nameof(AzureSasCredential)} signature."); } - DateTime epochTime = new DateTime(1970, 1, 1); - TimeSpan timeToLiveFromEpochTime = TimeSpan.FromSeconds(secondsFromEpochTime); + var epochTime = new DateTime(1970, 1, 1); + var timeToLiveFromEpochTime = TimeSpan.FromSeconds(secondsFromEpochTime); DateTime expiresAt = epochTime.Add(timeToLiveFromEpochTime); var token = new CbsToken( diff --git a/iothub/service/src/Message.cs b/iothub/service/src/Message.cs index 942c17878d..f55023e9bf 100644 --- a/iothub/service/src/Message.cs +++ b/iothub/service/src/Message.cs @@ -368,7 +368,7 @@ public byte[] GetBytes() if (_bodyStream is BufferListStream listStream) { // We can trust Amqp bufferListStream.Length; - var bytes = new byte[listStream.Length]; + byte[] bytes = new byte[listStream.Length]; listStream.Read(bytes, 0, bytes.Length); return bytes; } diff --git a/iothub/service/src/ServiceClient.cs b/iothub/service/src/ServiceClient.cs index 6f39c42e93..5927f9c33d 100644 --- a/iothub/service/src/ServiceClient.cs +++ b/iothub/service/src/ServiceClient.cs @@ -49,10 +49,10 @@ public enum TransportType /// public class ServiceClient : IDisposable { - private const string _statisticsUriFormat = "/statistics/service?" + ClientApiVersionHelper.ApiVersionQueryString; - private const string _purgeMessageQueueFormat = "/devices/{0}/commands?" + ClientApiVersionHelper.ApiVersionQueryString; - private const string _deviceMethodUriFormat = "/twins/{0}/methods?" + ClientApiVersionHelper.ApiVersionQueryString; - private const string _moduleMethodUriFormat = "/twins/{0}/modules/{1}/methods?" + ClientApiVersionHelper.ApiVersionQueryString; + private const string StatisticsUriFormat = "/statistics/service?" + ClientApiVersionHelper.ApiVersionQueryString; + private const string PurgeMessageQueueFormat = "/devices/{0}/commands?" + ClientApiVersionHelper.ApiVersionQueryString; + private const string DeviceMethodUriFormat = "/twins/{0}/methods?" + ClientApiVersionHelper.ApiVersionQueryString; + private const string ModuleMethodUriFormat = "/twins/{0}/modules/{1}/methods?" + ClientApiVersionHelper.ApiVersionQueryString; private static readonly TimeSpan s_defaultOperationTimeout = TimeSpan.FromSeconds(100); @@ -149,7 +149,7 @@ public static ServiceClient Create( { if (string.IsNullOrEmpty(hostName)) { - throw new ArgumentNullException($"{nameof(hostName)}, Parameter cannot be null or empty"); + throw new ArgumentNullException($"{nameof(hostName)}, Parameter cannot be null or empty"); } if (credential == null) @@ -607,25 +607,25 @@ private static TimeSpan GetInvokeDeviceMethodOperationTimeout(CloudToDeviceMetho private static Uri GetStatisticsUri() { - return new Uri(_statisticsUriFormat, UriKind.Relative); + return new Uri(StatisticsUriFormat, UriKind.Relative); } private static Uri GetPurgeMessageQueueAsyncUri(string deviceId) { - return new Uri(_purgeMessageQueueFormat.FormatInvariant(deviceId), UriKind.Relative); + return new Uri(PurgeMessageQueueFormat.FormatInvariant(deviceId), UriKind.Relative); } private static Uri GetDeviceMethodUri(string deviceId) { deviceId = WebUtility.UrlEncode(deviceId); - return new Uri(_deviceMethodUriFormat.FormatInvariant(deviceId), UriKind.Relative); + return new Uri(DeviceMethodUriFormat.FormatInvariant(deviceId), UriKind.Relative); } private static Uri GetModuleMethodUri(string deviceId, string moduleId) { deviceId = WebUtility.UrlEncode(deviceId); moduleId = WebUtility.UrlEncode(moduleId); - return new Uri(_moduleMethodUriFormat.FormatInvariant(deviceId, moduleId), UriKind.Relative); + return new Uri(ModuleMethodUriFormat.FormatInvariant(deviceId, moduleId), UriKind.Relative); } } } diff --git a/iothub/service/src/ServicePointHelpers.cs b/iothub/service/src/ServicePointHelpers.cs index 12c357013a..1e40f8f3b0 100644 --- a/iothub/service/src/ServicePointHelpers.cs +++ b/iothub/service/src/ServicePointHelpers.cs @@ -32,7 +32,7 @@ public static void SetLimits(HttpMessageHandler messageHandler, Uri baseUri, int #if !NET451 httpClientHandler.MaxConnectionsPerServer = DefaultMaxConnectionsPerServer; #endif - var servicePoint = ServicePointManager.FindServicePoint(baseUri); + ServicePoint servicePoint = ServicePointManager.FindServicePoint(baseUri); servicePoint.ConnectionLeaseTimeout = connectionLeaseTimeoutMilliseconds; break; #if NETCOREAPP && !NETCOREAPP2_0 && !NETCOREAPP1_0 && !NETCOREAPP1_1 diff --git a/iothub/service/src/net451/Common/ActionItem.cs b/iothub/service/src/net451/Common/ActionItem.cs index c80e806c9b..39ec1ee79f 100644 --- a/iothub/service/src/net451/Common/ActionItem.cs +++ b/iothub/service/src/net451/Common/ActionItem.cs @@ -215,14 +215,14 @@ static void InvokeWithContext(object state) [Fx.Tag.SecurityNote(Critical = "Called by the scheduler without any user context on the stack")] static void InvokeWithoutContext(object state) { - ActionItem tempState = (ActionItem)state; + var tempState = (ActionItem)state; tempState.Invoke(); tempState.isScheduled = false; } [Fx.Tag.SecurityNote(Critical = "Called after applying the user context on the stack")] static void OnContextApplied(object o) { - ActionItem tempState = (ActionItem)o; + var tempState = (ActionItem)o; tempState.Invoke(); tempState.isScheduled = false; } diff --git a/iothub/service/src/net451/Common/SynchronizedPool.cs b/iothub/service/src/net451/Common/SynchronizedPool.cs index 2d7a3e8f60..ea6ce9bdcf 100644 --- a/iothub/service/src/net451/Common/SynchronizedPool.cs +++ b/iothub/service/src/net451/Common/SynchronizedPool.cs @@ -203,7 +203,7 @@ void RecordTakeFromGlobalPool(int thisThreadID) } else { - PendingEntry[] newPending = new PendingEntry[localPending.Length * 2]; + var newPending = new PendingEntry[localPending.Length * 2]; Array.Copy(localPending, newPending, localPending.Length); this.pending = newPending; } diff --git a/provisioning/device/src/GlobalSuppressions.cs b/provisioning/device/src/GlobalSuppressions.cs index 7fc7c806ad..15f281aa6f 100644 --- a/provisioning/device/src/GlobalSuppressions.cs +++ b/provisioning/device/src/GlobalSuppressions.cs @@ -5,5 +5,15 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] diff --git a/provisioning/service/src/Auth/ServiceConnectionStringBuilder.cs b/provisioning/service/src/Auth/ServiceConnectionStringBuilder.cs index 811c3bce35..5b53cc8d17 100644 --- a/provisioning/service/src/Auth/ServiceConnectionStringBuilder.cs +++ b/provisioning/service/src/Auth/ServiceConnectionStringBuilder.cs @@ -98,7 +98,7 @@ public override string ToString() { Validate(); - StringBuilder stringBuilder = new StringBuilder(); + var stringBuilder = new StringBuilder(); stringBuilder.AppendKeyValuePairIfNotEmpty(HostNamePropertyName, HostName); stringBuilder.AppendKeyValuePairIfNotEmpty(SharedAccessKeyNamePropertyName, SharedAccessKeyName); stringBuilder.AppendKeyValuePairIfNotEmpty(SharedAccessKeyPropertyName, SharedAccessKey); diff --git a/provisioning/service/src/Auth/SharedAccessSignature.cs b/provisioning/service/src/Auth/SharedAccessSignature.cs index 4f50a1c6af..20afe689d4 100644 --- a/provisioning/service/src/Auth/SharedAccessSignature.cs +++ b/provisioning/service/src/Auth/SharedAccessSignature.cs @@ -163,7 +163,7 @@ public void Authorize(Uri targetAddress) public string ComputeSignature(byte[] key) { - List fields = new List(); + var fields = new List(); fields.Add(_encodedAudience); fields.Add(_expiry); diff --git a/provisioning/service/src/Auth/SharedAccessSignatureBuilder.cs b/provisioning/service/src/Auth/SharedAccessSignatureBuilder.cs index 4f0ef1d1ed..41e5ba5249 100644 --- a/provisioning/service/src/Auth/SharedAccessSignatureBuilder.cs +++ b/provisioning/service/src/Auth/SharedAccessSignatureBuilder.cs @@ -48,7 +48,7 @@ private static string BuildSignature(string keyName, string key, string target, { string expiresOn = BuildExpiresOn(timeToLive); string audience = WebUtility.UrlEncode(target); - List fields = new List(); + var fields = new List(); fields.Add(audience); fields.Add(expiresOn); diff --git a/provisioning/service/src/Config/BulkEnrollmentOperation.cs b/provisioning/service/src/Config/BulkEnrollmentOperation.cs index cc7a920b1e..37247453f8 100644 --- a/provisioning/service/src/Config/BulkEnrollmentOperation.cs +++ b/provisioning/service/src/Config/BulkEnrollmentOperation.cs @@ -93,7 +93,7 @@ individualEnrollments is null or empty.] */ /* SRS_BULK_OPERATION_21_002: [The toJson shall return a String with the mode and the collection of individualEnrollments using a JSON format.] */ - BulkOperation bulkOperation = new BulkOperation() { Mode = mode, Enrollments = individualEnrollments }; + var bulkOperation = new BulkOperation() { Mode = mode, Enrollments = individualEnrollments }; return Newtonsoft.Json.JsonConvert.SerializeObject(bulkOperation); } } diff --git a/provisioning/service/src/Config/X509CertificateWithInfo.cs b/provisioning/service/src/Config/X509CertificateWithInfo.cs index 406644e1a2..61b7312c1d 100644 --- a/provisioning/service/src/Config/X509CertificateWithInfo.cs +++ b/provisioning/service/src/Config/X509CertificateWithInfo.cs @@ -140,7 +140,7 @@ private static void ValidateCertificate(X509Certificate2 certificate) private static void ValidateCertificate(string certificate) { byte[] certBytes = System.Text.Encoding.ASCII.GetBytes(certificate ?? throw new ArgumentException("Certificate cannot be null.")); - X509Certificate2 cert = new X509Certificate2(certBytes); + var cert = new X509Certificate2(certBytes); ValidateCertificate(cert); cert.Dispose(); } diff --git a/provisioning/service/src/GlobalSuppressions.cs b/provisioning/service/src/GlobalSuppressions.cs index 7fc7c806ad..15f281aa6f 100644 --- a/provisioning/service/src/GlobalSuppressions.cs +++ b/provisioning/service/src/GlobalSuppressions.cs @@ -5,5 +5,15 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] diff --git a/provisioning/service/src/Query.cs b/provisioning/service/src/Query.cs index b5a6a58dc1..4b449710ab 100644 --- a/provisioning/service/src/Query.cs +++ b/provisioning/service/src/Query.cs @@ -211,7 +211,7 @@ public async Task NextAsync() /* SRS_QUERY_21_017: [The next shall set hasNext as true if the continuationToken is not null, or false if it is null.] */ _hasNext = (ContinuationToken != null); - QueryResult result = new QueryResult(type, httpResponse.Body, ContinuationToken); + var result = new QueryResult(type, httpResponse.Body, ContinuationToken); return result; } diff --git a/provisioning/service/tests/Config/AttestationMechanismTests.cs b/provisioning/service/tests/Config/AttestationMechanismTests.cs index dd22756ece..f7d4ba5b5d 100644 --- a/provisioning/service/tests/Config/AttestationMechanismTests.cs +++ b/provisioning/service/tests/Config/AttestationMechanismTests.cs @@ -85,7 +85,7 @@ public void AttestationMechanismConstructorThrowsOnAttestationNull() public void AttestationMechanismConstructorSucceedOnTPMAttestation() { // arrange - act - AttestationMechanism attestationMechanism = new AttestationMechanism(SampleTpmAttestation); + var attestationMechanism = new AttestationMechanism(SampleTpmAttestation); // assert Assert.IsNotNull(attestationMechanism); @@ -98,7 +98,7 @@ public void AttestationMechanismConstructorSucceedOnTPMAttestation() public void AttestationMechanismConstructorThrowsOnUnknownAttestation() { // arrange - UnknownAttestation unknownAttestation = new UnknownAttestation(); + var unknownAttestation = new UnknownAttestation(); // act - assert TestAssert.Throws(() => new AttestationMechanism(unknownAttestation)); @@ -112,7 +112,7 @@ public void AttestationMechanismConstructorThrowsOnUnknownAttestation() public void AttestationMechanismConstructorSucceedOnX509Attestation() { // arrange - act - AttestationMechanism attestationMechanism = new AttestationMechanism(SampleX509RootAttestation); + var attestationMechanism = new AttestationMechanism(SampleX509RootAttestation); // assert Assert.IsNotNull(attestationMechanism); @@ -237,7 +237,7 @@ public void AttestationMechanismConstructorJSONSucceedOnSymmetricKeyType() Assert.IsNotNull(attestationMechanism); Assert.IsTrue(attestationMechanism.Type == AttestationMechanismType.SymmetricKey); Assert.IsTrue(attestationMechanism.GetAttestation() is SymmetricKeyAttestation); - SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation) attestationMechanism.GetAttestation(); + var symmetricKeyAttestation = (SymmetricKeyAttestation) attestationMechanism.GetAttestation(); Assert.AreEqual(samplePrimaryKey, symmetricKeyAttestation.PrimaryKey); Assert.AreEqual(sampleSecondaryKey, symmetricKeyAttestation.SecondaryKey); diff --git a/provisioning/service/tests/Config/EnrollmentGroupTests.cs b/provisioning/service/tests/Config/EnrollmentGroupTests.cs index 242e2ff80d..072bdf4e24 100644 --- a/provisioning/service/tests/Config/EnrollmentGroupTests.cs +++ b/provisioning/service/tests/Config/EnrollmentGroupTests.cs @@ -79,7 +79,7 @@ public class EnrollmentGroupTests public void EnrollmentGroupConstructorSucceed() { // arrange - act - EnrollmentGroup individualEnrollment = new EnrollmentGroup(SampleEnrollmentGroupId, SampleX509RootAttestation); + var individualEnrollment = new EnrollmentGroup(SampleEnrollmentGroupId, SampleX509RootAttestation); // assert Assert.AreEqual(SampleEnrollmentGroupId, individualEnrollment.EnrollmentGroupId); diff --git a/provisioning/service/tests/Config/IndividualEnrollmentTests.cs b/provisioning/service/tests/Config/IndividualEnrollmentTests.cs index bd2371d5c5..f4cf62b3dc 100644 --- a/provisioning/service/tests/Config/IndividualEnrollmentTests.cs +++ b/provisioning/service/tests/Config/IndividualEnrollmentTests.cs @@ -105,7 +105,7 @@ public class IndividualEnrollmentTests public void IndividualEnrollmentConstructorSucceedOnTPM() { // arrange - act - IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleTpmAttestation); + var individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleTpmAttestation); // assert Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); @@ -116,7 +116,7 @@ public void IndividualEnrollmentConstructorSucceedOnTPM() public void IndividualEnrollmentConstructorSucceedOnX509Client() { // arrange - act - IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleX509ClientAttestation); + var individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleX509ClientAttestation); // assert Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); @@ -127,7 +127,7 @@ public void IndividualEnrollmentConstructorSucceedOnX509Client() public void IndividualEnrollmentConstructorSucceedOnX509CAReference() { // arrange - act - IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleX509CAReferenceAttestation); + var individualEnrollment = new IndividualEnrollment(SampleRegistrationId, SampleX509CAReferenceAttestation); // assert Assert.AreEqual(SampleRegistrationId, individualEnrollment.RegistrationId); diff --git a/provisioning/service/tests/Config/QueryResultTests.cs b/provisioning/service/tests/Config/QueryResultTests.cs index 80fb9c13f8..f11c960430 100644 --- a/provisioning/service/tests/Config/QueryResultTests.cs +++ b/provisioning/service/tests/Config/QueryResultTests.cs @@ -174,7 +174,7 @@ public void QueryResultConstructorThrowsOnInvalidParameters() public void QueryResultConstructorSucceedOnIndividualEnrollment() { // arrange - act - QueryResult queryResult = new QueryResult(SerializedNameEnrollment, SampleEnrollmentsJSON, SampleContinuationToken); + var queryResult = new QueryResult(SerializedNameEnrollment, SampleEnrollmentsJSON, SampleContinuationToken); // assert Assert.IsNotNull(queryResult); @@ -190,7 +190,7 @@ public void QueryResultConstructorSucceedOnIndividualEnrollment() public void QueryResultConstructorSucceedOnEnrollmentGroup() { // arrange - act - QueryResult queryResult = new QueryResult(SerializedNameEnrollmentGroup, SampleEnrollmentGroupJSON, SampleContinuationToken); + var queryResult = new QueryResult(SerializedNameEnrollmentGroup, SampleEnrollmentGroupJSON, SampleContinuationToken); // assert Assert.IsNotNull(queryResult); @@ -206,7 +206,7 @@ public void QueryResultConstructorSucceedOnEnrollmentGroup() public void QueryResultConstructorSucceedOnDeviceRegistration() { // arrange - act - QueryResult queryResult = new QueryResult(SerializedNameDeviceRegistration, SampleRegistrationStatusJSON, SampleContinuationToken); + var queryResult = new QueryResult(SerializedNameDeviceRegistration, SampleRegistrationStatusJSON, SampleContinuationToken); // assert Assert.IsNotNull(queryResult); @@ -222,7 +222,7 @@ public void QueryResultConstructorSucceedOnDeviceRegistration() public void QueryResultConstructorSucceedOnUnknownWithNullBody() { // arrange - act - QueryResult queryResult = new QueryResult(SerializedNameUnknown, null, SampleContinuationToken); + var queryResult = new QueryResult(SerializedNameUnknown, null, SampleContinuationToken); // assert Assert.IsNotNull(queryResult); @@ -236,7 +236,7 @@ public void QueryResultConstructorSucceedOnUnknownWithNullBody() public void QueryResultConstructorSucceedOnUnknownWithObjectListBody() { // arrange - act - QueryResult queryResult = new QueryResult(SerializedNameUnknown, SampleListJObjectJSON, SampleContinuationToken); + var queryResult = new QueryResult(SerializedNameUnknown, SampleListJObjectJSON, SampleContinuationToken); // assert Assert.IsNotNull(queryResult); @@ -252,7 +252,7 @@ public void QueryResultConstructorSucceedOnUnknownWithObjectListBody() public void QueryResultConstructorSucceedOnUnknownWithIntegerListBody() { // arrange - act - QueryResult queryResult = new QueryResult(SerializedNameUnknown, SampleListIntJSON, SampleContinuationToken); + var queryResult = new QueryResult(SerializedNameUnknown, SampleListIntJSON, SampleContinuationToken); // assert Assert.IsNotNull(queryResult); @@ -271,7 +271,7 @@ public void QueryResultConstructorSucceedOnUnknownWithStringBody() string body = "This is a non deserializable body"; // act - QueryResult queryResult = new QueryResult(SerializedNameUnknown, body, SampleContinuationToken); + var queryResult = new QueryResult(SerializedNameUnknown, body, SampleContinuationToken); // assert Assert.IsNotNull(queryResult); @@ -290,7 +290,7 @@ public void QueryResultConstructorSucceedOnNullContinuationToken() string body = "This is a non deserializable body"; // act - QueryResult queryResult = new QueryResult(SerializedNameUnknown, body, null); + var queryResult = new QueryResult(SerializedNameUnknown, body, null); // assert Assert.IsNotNull(queryResult); @@ -304,7 +304,7 @@ public void QueryResultConstructorSucceedOnEmptyContinuationToken() string body = "This is a non deserializable body"; // act - QueryResult queryResult = new QueryResult(SerializedNameUnknown, body, ""); + var queryResult = new QueryResult(SerializedNameUnknown, body, ""); // assert Assert.IsNotNull(queryResult); diff --git a/provisioning/service/tests/Config/SymmetricKeyAttestationTest.cs b/provisioning/service/tests/Config/SymmetricKeyAttestationTest.cs index 20f5037fa4..46b8e3beff 100644 --- a/provisioning/service/tests/Config/SymmetricKeyAttestationTest.cs +++ b/provisioning/service/tests/Config/SymmetricKeyAttestationTest.cs @@ -17,7 +17,7 @@ public class SymmetricKeyAttestationTest [TestMethod] public void constructorAllowsBase64EncodedKeys() { - SymmetricKeyAttestation symmetricKeyAttestation = new SymmetricKeyAttestation(validKeyValue, validKeyValue2); + var symmetricKeyAttestation = new SymmetricKeyAttestation(validKeyValue, validKeyValue2); Assert.AreEqual(validKeyValue, symmetricKeyAttestation.PrimaryKey); Assert.AreEqual(validKeyValue2, symmetricKeyAttestation.SecondaryKey); @@ -32,7 +32,7 @@ public void jsonSerializingWorks() "\"secondaryKey\":\"" + validKeyValue2 + "\"" + "}"; - SymmetricKeyAttestation symmetricKeyAttestation = new SymmetricKeyAttestation(validKeyValue, validKeyValue2); + var symmetricKeyAttestation = new SymmetricKeyAttestation(validKeyValue, validKeyValue2); string json = Newtonsoft.Json.JsonConvert.SerializeObject(symmetricKeyAttestation); diff --git a/provisioning/service/tests/Config/TpmAttestationTests.cs b/provisioning/service/tests/Config/TpmAttestationTests.cs index ceca77869d..ebdb045427 100644 --- a/provisioning/service/tests/Config/TpmAttestationTests.cs +++ b/provisioning/service/tests/Config/TpmAttestationTests.cs @@ -48,7 +48,7 @@ public void TpmAttestationSucceedOnNullStorageRootKey() string storageRootKey = null; // act - assert - TpmAttestation tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); + var tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); // assert Assert.AreEqual(endorsementKey, tpmAttestation.EndorsementKey); @@ -63,7 +63,7 @@ public void TpmAttestationSucceedOnEmptyStorageRootKey() string storageRootKey = ""; // act - assert - TpmAttestation tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); + var tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); // assert Assert.AreEqual(endorsementKey, tpmAttestation.EndorsementKey); @@ -78,7 +78,7 @@ public void TpmAttestationSucceedOnValidEndorsementKey() string endorsementKey = Key; // act - TpmAttestation tpmAttestation = new TpmAttestation(endorsementKey); + var tpmAttestation = new TpmAttestation(endorsementKey); // assert Assert.AreEqual(endorsementKey, tpmAttestation.EndorsementKey); @@ -93,7 +93,7 @@ public void TpmAttestationSucceedOnValidEndorsementKeyAndStorageRootKey() string storageRootKey = Key; // act - TpmAttestation tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); + var tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); // assert Assert.AreEqual(endorsementKey, tpmAttestation.EndorsementKey); @@ -112,7 +112,7 @@ public void TpmAttestationSucceedOnSerialization() " \"endorsementKey\":\""+endorsementKey+"\"," + " \"storageRootKey\":\"" + storageRootKey + "\"" + "}"; - TpmAttestation tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); + var tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); // act string json = Newtonsoft.Json.JsonConvert.SerializeObject(tpmAttestation); @@ -130,7 +130,7 @@ public void TpmAttestationSucceedOnSerializationWithoutStorageRootKey() "{" + " \"endorsementKey\":\"" + endorsementKey + "\"" + "}"; - TpmAttestation tpmAttestation = new TpmAttestation(endorsementKey); + var tpmAttestation = new TpmAttestation(endorsementKey); // act string json = Newtonsoft.Json.JsonConvert.SerializeObject(tpmAttestation); @@ -150,7 +150,7 @@ public void TpmAttestationSucceedOnSerializationWithEmptyStorageRootKey() " \"endorsementKey\":\"" + endorsementKey + "\"," + " \"storageRootKey\":\"" + storageRootKey + "\"" + "}"; - TpmAttestation tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); + var tpmAttestation = new TpmAttestation(endorsementKey, storageRootKey); // act string json = Newtonsoft.Json.JsonConvert.SerializeObject(tpmAttestation); diff --git a/provisioning/service/tests/Config/TwinStateTests.cs b/provisioning/service/tests/Config/TwinStateTests.cs index 6653237ba6..cc7b24dd60 100644 --- a/provisioning/service/tests/Config/TwinStateTests.cs +++ b/provisioning/service/tests/Config/TwinStateTests.cs @@ -73,7 +73,7 @@ public void TwinStateSucceedOnNull() TwinCollection desiredProperties = null; // act - TwinState initialTwin = new TwinState(tags, desiredProperties); + var initialTwin = new TwinState(tags, desiredProperties); // assert Assert.IsNull(initialTwin.Tags); @@ -88,7 +88,7 @@ public void TwinStateSucceedOnTagsWitoutDesiredProperties() TwinCollection desiredProperties = null; // act - TwinState initialTwin = new TwinState(tags, desiredProperties); + var initialTwin = new TwinState(tags, desiredProperties); // assert Assert.AreEqual(tags, initialTwin.Tags); @@ -106,7 +106,7 @@ public void TwinStateSucceedOnDesiredPropertiesWitoutTags() TwinCollection desiredProperties = SampleDesiredProperties; // act - TwinState initialTwin = new TwinState(tags, desiredProperties); + var initialTwin = new TwinState(tags, desiredProperties); // assert Assert.IsNull(initialTwin.Tags); @@ -121,7 +121,7 @@ public void TwinStateSucceedOnDesiredPropertiesAndTags() TwinCollection desiredProperties = SampleDesiredProperties; // act - TwinState initialTwin = new TwinState(tags, desiredProperties); + var initialTwin = new TwinState(tags, desiredProperties); // assert Assert.AreEqual(tags, initialTwin.Tags); @@ -134,7 +134,7 @@ public void TwinStateSucceedOnTagsToJson() // arrange TwinCollection tags = SampleTags; TwinCollection desiredProperties = null; - TwinState initialTwin = new TwinState(tags, desiredProperties); + var initialTwin = new TwinState(tags, desiredProperties); // act string jsonResult = JsonConvert.SerializeObject(initialTwin); @@ -149,7 +149,7 @@ public void TwinStateSucceedOnDesiredPropertiesToJson() // arrange TwinCollection tags = null; TwinCollection desiredProperties = SampleDesiredProperties; - TwinState initialTwin = new TwinState(tags, desiredProperties); + var initialTwin = new TwinState(tags, desiredProperties); // act string jsonResult = JsonConvert.SerializeObject(initialTwin); @@ -164,7 +164,7 @@ public void TwinStateSucceedOnToJson() // arrange TwinCollection tags = SampleTags; TwinCollection desiredProperties = SampleDesiredProperties; - TwinState initialTwin = new TwinState(tags, desiredProperties); + var initialTwin = new TwinState(tags, desiredProperties); // act string jsonResult = JsonConvert.SerializeObject(initialTwin); diff --git a/provisioning/service/tests/Config/X509AttestationTests.cs b/provisioning/service/tests/Config/X509AttestationTests.cs index 71377b4e1e..4373bc83cb 100644 --- a/provisioning/service/tests/Config/X509AttestationTests.cs +++ b/provisioning/service/tests/Config/X509AttestationTests.cs @@ -118,10 +118,10 @@ public void X509AttestationCreateFromRootCertificatesThrowsOnNullPrimaryCertific public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryCertificate() { // arrange - X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); // act - X509Attestation attestation = X509Attestation.CreateFromClientCertificates(primary); + var attestation = X509Attestation.CreateFromClientCertificates(primary); primary.Dispose(); // assert @@ -135,11 +135,11 @@ public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryCertifica public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryAndSecondaryCertificates() { // arrange - X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); - X509Certificate2 secondary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var secondary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); // act - X509Attestation attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); primary.Dispose(); secondary.Dispose(); @@ -154,11 +154,11 @@ public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryAndSecond public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryAndSecondaryNullCertificates() { // arrange - X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); X509Certificate2 secondary = null; // act - X509Attestation attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); primary.Dispose(); // assert @@ -175,7 +175,7 @@ public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryString() string primary = PUBLIC_KEY_CERTIFICATE_STRING; // act - X509Attestation attestation = X509Attestation.CreateFromClientCertificates(primary); + var attestation = X509Attestation.CreateFromClientCertificates(primary); // assert Assert.IsNotNull(attestation.ClientCertificates.Primary); @@ -192,7 +192,7 @@ public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryAndSecond string secondary = PUBLIC_KEY_CERTIFICATE_STRING; // act - X509Attestation attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); // assert Assert.IsNotNull(attestation.ClientCertificates.Primary); @@ -209,7 +209,7 @@ public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryAndSecond string secondary = null; // act - X509Attestation attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromClientCertificates(primary, secondary); // assert Assert.IsNotNull(attestation.ClientCertificates.Primary); @@ -223,10 +223,10 @@ public void X509AttestationCreateFromClientCertificatesSucceedOnPrimaryAndSecond public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryCertificate() { // arrange - X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); // act - X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary); + var attestation = X509Attestation.CreateFromRootCertificates(primary); primary.Dispose(); // assert @@ -240,11 +240,11 @@ public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryCertificate public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryAndSecondaryCertificates() { // arrange - X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); - X509Certificate2 secondary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var secondary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); // act - X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); primary.Dispose(); secondary.Dispose(); @@ -259,11 +259,11 @@ public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryAndSecondar public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryAndSecondaryNullCertificates() { // arrange - X509Certificate2 primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); + var primary = new X509Certificate2(Encoding.ASCII.GetBytes(PUBLIC_KEY_CERTIFICATE_STRING)); X509Certificate2 secondary = null; // act - X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); primary.Dispose(); // assert @@ -280,7 +280,7 @@ public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryString() string primary = PUBLIC_KEY_CERTIFICATE_STRING; // act - X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary); + var attestation = X509Attestation.CreateFromRootCertificates(primary); // assert Assert.IsNotNull(attestation.RootCertificates.Primary); @@ -297,7 +297,7 @@ public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryAndSecondar string secondary = PUBLIC_KEY_CERTIFICATE_STRING; // act - X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); // assert Assert.IsNotNull(attestation.RootCertificates.Primary); @@ -314,7 +314,7 @@ public void X509AttestationCreateFromRootCertificatesSucceedOnPrimaryAndSecondar string secondary = null; // act - X509Attestation attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); + var attestation = X509Attestation.CreateFromRootCertificates(primary, secondary); // assert Assert.IsNotNull(attestation.RootCertificates.Primary); @@ -345,7 +345,7 @@ public void X509AttestationCreateFromCAReferencesSucceedOnPrimaryString() string primary = CA_REFERENCE_STRING; // act - X509Attestation attestation = X509Attestation.CreateFromCAReferences(primary); + var attestation = X509Attestation.CreateFromCAReferences(primary); // assert Assert.IsNotNull(attestation.CAReferences.Primary); @@ -362,7 +362,7 @@ public void X509AttestationCreateFromCAReferencesSucceedOnPrimaryAndSecondaryStr string secondary = CA_REFERENCE_STRING; // act - X509Attestation attestation = X509Attestation.CreateFromCAReferences(primary, secondary); + var attestation = X509Attestation.CreateFromCAReferences(primary, secondary); // assert Assert.IsNotNull(attestation.CAReferences.Primary); @@ -379,7 +379,7 @@ public void X509AttestationCreateFromCAReferencesSucceedOnPrimaryAndSecondaryNul string secondary = null; // act - X509Attestation attestation = X509Attestation.CreateFromCAReferences(primary, secondary); + var attestation = X509Attestation.CreateFromCAReferences(primary, secondary); // assert Assert.IsNotNull(attestation.CAReferences.Primary); diff --git a/provisioning/service/tests/Config/X509CertificateWithInfoTests.cs b/provisioning/service/tests/Config/X509CertificateWithInfoTests.cs index 3878712051..3bfac11ee2 100644 --- a/provisioning/service/tests/Config/X509CertificateWithInfoTests.cs +++ b/provisioning/service/tests/Config/X509CertificateWithInfoTests.cs @@ -143,7 +143,7 @@ public void X509CertificateWithInfoSucceedOnJsonWithInfo() string json = makeJson(SUBJECT_NAME, SHA1THUMBPRINT, SHA256THUMBPRINT, ISSUER_NAME, NOT_BEFORE_UTC_STRING, NOT_AFTER_UTC_STRING, SERIAL_NUMBER, VERSION); // act - var x509CertificateWithInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(json); + X509CertificateWithInfo x509CertificateWithInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(json); // assert Assert.IsNotNull(x509CertificateWithInfo.Info); diff --git a/provisioning/service/tests/Config/X509CertificatesTests.cs b/provisioning/service/tests/Config/X509CertificatesTests.cs index 3dc2f23a16..107c4c54a0 100644 --- a/provisioning/service/tests/Config/X509CertificatesTests.cs +++ b/provisioning/service/tests/Config/X509CertificatesTests.cs @@ -127,7 +127,7 @@ public void X509CertificatesSucceedOnJsonWithPrimaryCertificate() "}"; // act - var x509Certificates = JsonConvert.DeserializeObject(json); + X509Certificates x509Certificates = JsonConvert.DeserializeObject(json); // assert Assert.IsNotNull(x509Certificates.Primary); @@ -148,7 +148,7 @@ public void X509CertificatesSucceedOnJsonWithPrimaryAndSecondaryCertificate() "}"; // act - var x509Certificates = JsonConvert.DeserializeObject(json); + X509Certificates x509Certificates = JsonConvert.DeserializeObject(json); // assert Assert.IsNotNull(x509Certificates.Primary); diff --git a/provisioning/service/tests/TestAssert.cs b/provisioning/service/tests/TestAssert.cs index 1c570bc602..db2c9d8d1a 100644 --- a/provisioning/service/tests/TestAssert.cs +++ b/provisioning/service/tests/TestAssert.cs @@ -98,8 +98,8 @@ public static void AreEqual(JArray expectedJObject, JArray actualJObject) for (int index = 0; index < expectedJObject.Count; index++) { - var expectedItem = expectedJObject[index]; - var actualItem = actualJObject[index]; + JToken expectedItem = expectedJObject[index]; + JToken actualItem = actualJObject[index]; if (expectedItem.Type == JTokenType.Object) { AreEqual((JObject)expectedItem, (JObject)actualItem); diff --git a/provisioning/transport/amqp/src/AmqpAuthStrategySymmetricKey.cs b/provisioning/transport/amqp/src/AmqpAuthStrategySymmetricKey.cs index b0ff294f52..5bcc802b09 100644 --- a/provisioning/transport/amqp/src/AmqpAuthStrategySymmetricKey.cs +++ b/provisioning/transport/amqp/src/AmqpAuthStrategySymmetricKey.cs @@ -34,7 +34,7 @@ public override AmqpSettings CreateAmqpSettings(string idScope) saslProvider.Versions.Add(AmqpConstants.DefaultProtocolVersion); settings.TransportProviders.Add(saslProvider); - SaslPlainHandler saslHandler = new SaslPlainHandler(); + var saslHandler = new SaslPlainHandler(); saslHandler.AuthenticationIdentity = $"{idScope}/registrations/{_security.GetRegistrationID()}"; string key = _security.GetPrimaryKey(); saslHandler.Password = ProvisioningSasBuilder.BuildSasSignature("registration", key, saslHandler.AuthenticationIdentity, TimeSpan.FromDays(1)); diff --git a/provisioning/transport/amqp/src/AmqpAuthStrategyTpm.cs b/provisioning/transport/amqp/src/AmqpAuthStrategyTpm.cs index 46e6484d51..c434da921a 100644 --- a/provisioning/transport/amqp/src/AmqpAuthStrategyTpm.cs +++ b/provisioning/transport/amqp/src/AmqpAuthStrategyTpm.cs @@ -32,7 +32,7 @@ public override AmqpSettings CreateAmqpSettings(string idScope) byte[] ekBuffer = _security.GetEndorsementKey(); byte[] srkBuffer = _security.GetStorageRootKey(); - SaslTpmHandler tpmHandler = new SaslTpmHandler(ekBuffer, srkBuffer, idScope, _security); + var tpmHandler = new SaslTpmHandler(ekBuffer, srkBuffer, idScope, _security); saslProvider.AddHandler(tpmHandler); return settings; diff --git a/provisioning/transport/amqp/src/GlobalSuppressions.cs b/provisioning/transport/amqp/src/GlobalSuppressions.cs index 7fc7c806ad..15f281aa6f 100644 --- a/provisioning/transport/amqp/src/GlobalSuppressions.cs +++ b/provisioning/transport/amqp/src/GlobalSuppressions.cs @@ -5,5 +5,15 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] diff --git a/provisioning/transport/amqp/src/ProvisioningErrorDetailsAmqp.cs b/provisioning/transport/amqp/src/ProvisioningErrorDetailsAmqp.cs index 703ce20d40..45c86d7a72 100644 --- a/provisioning/transport/amqp/src/ProvisioningErrorDetailsAmqp.cs +++ b/provisioning/transport/amqp/src/ProvisioningErrorDetailsAmqp.cs @@ -26,7 +26,7 @@ internal class ProvisioningErrorDetailsAmqp : ProvisioningErrorDetails int secondsToWait; if (int.TryParse(retryAfter.ToString(), out secondsToWait)) { - TimeSpan serviceRecommendedDelay = TimeSpan.FromSeconds(secondsToWait); + var serviceRecommendedDelay = TimeSpan.FromSeconds(secondsToWait); if (serviceRecommendedDelay.TotalSeconds < defaultInterval.TotalSeconds) { diff --git a/provisioning/transport/amqp/src/SaslTpmHandler.cs b/provisioning/transport/amqp/src/SaslTpmHandler.cs index 3b435d9528..da93acffdd 100644 --- a/provisioning/transport/amqp/src/SaslTpmHandler.cs +++ b/provisioning/transport/amqp/src/SaslTpmHandler.cs @@ -75,7 +75,7 @@ public override int GetHashCode() { unchecked { - var hashCode = _endorsementKey != null ? _endorsementKey.GetHashCode() : 0; + int hashCode = _endorsementKey != null ? _endorsementKey.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (_storageRootKey != null ? _storageRootKey.GetHashCode() : 0); #if NETSTANDARD2_1 hashCode = (hashCode * 397) ^ (_idScope != null ? _idScope.GetHashCode(StringComparison.Ordinal) : 0); @@ -105,7 +105,7 @@ public override SaslHandler Clone() public override void OnChallenge(SaslChallenge challenge) { - var challengeAction = GetChallengeAction(challenge); + SaslChallengeAction challengeAction = GetChallengeAction(challenge); switch (challengeAction) { @@ -138,7 +138,7 @@ private void SendLastResponse() _hostName, _nonceBuffer); - var responseBuffer = new byte[sas.Length + 1]; + byte[] responseBuffer = new byte[sas.Length + 1]; responseBuffer[0] = 0x0; Buffer.BlockCopy(Encoding.UTF8.GetBytes(sas), 0, responseBuffer, 1, sas.Length); @@ -148,7 +148,7 @@ private void SendLastResponse() private void SaveEncodedNonceSegment(SaslChallenge saslChallenge) { - var sequenceNumber = GetSequenceNumber(saslChallenge); + byte sequenceNumber = GetSequenceNumber(saslChallenge); if (_nextSequenceNumber != sequenceNumber) { throw new AmqpException(AmqpErrorCode.InvalidField, @@ -182,7 +182,7 @@ private void SendStorageRootKey() private byte[] CreateStorageRootKeyMessage() { - var responseBuffer = new byte[_storageRootKey.Length + 1]; + byte[] responseBuffer = new byte[_storageRootKey.Length + 1]; responseBuffer[0] = 0x0; Buffer.BlockCopy(_storageRootKey, 0, responseBuffer, 1, _storageRootKey.Length); return responseBuffer; @@ -190,7 +190,7 @@ private byte[] CreateStorageRootKeyMessage() private static SaslChallengeAction GetChallengeAction(SaslChallenge saslChallenge) { - var challengeBytes = saslChallenge.Challenge.Array; + byte[] challengeBytes = saslChallenge.Challenge.Array; if (challengeBytes == null || challengeBytes.Length == 0) { @@ -237,7 +237,7 @@ private void SendSaslInitMessage(SaslInit init) private byte[] CreateSaslInitMessage(SaslInit init) { init.HostName = _hostName; - StringBuilder initContent = new StringBuilder(); + var initContent = new StringBuilder(); initContent.Append(_idScope); initContent.Append('\0'); initContent.Append(_security.GetRegistrationID()); @@ -245,7 +245,7 @@ private byte[] CreateSaslInitMessage(SaslInit init) byte[] initContentInBytes = Encoding.UTF8.GetBytes(initContent.ToString()); - var responseBuffer = new byte[initContentInBytes.Length + _endorsementKey.Length + 1]; + byte[] responseBuffer = new byte[initContentInBytes.Length + _endorsementKey.Length + 1]; responseBuffer[0] = 0x0; Buffer.BlockCopy(initContentInBytes, 0, responseBuffer, 1, initContentInBytes.Length); Buffer.BlockCopy(_endorsementKey, 0, responseBuffer, initContentInBytes.Length + 1, _endorsementKey.Length); diff --git a/provisioning/transport/amqp/src/TaskHelpers.cs b/provisioning/transport/amqp/src/TaskHelpers.cs index 1e18b1b634..c15b2d6ec5 100644 --- a/provisioning/transport/amqp/src/TaskHelpers.cs +++ b/provisioning/transport/amqp/src/TaskHelpers.cs @@ -56,7 +56,7 @@ public static IAsyncResult ToAsyncResult(this Task task, AsyncCallback cal public static void EndAsyncResult(IAsyncResult asyncResult) { - Task task = asyncResult as Task; + var task = asyncResult as Task; if (task == null) { throw new ArgumentException($"Given {nameof(asyncResult)} is not subclass of Task."); diff --git a/provisioning/transport/amqp/tests/ProvisioningErrorDetailsAmqpTests.cs b/provisioning/transport/amqp/tests/ProvisioningErrorDetailsAmqpTests.cs index ba0a6e39fc..355029977a 100644 --- a/provisioning/transport/amqp/tests/ProvisioningErrorDetailsAmqpTests.cs +++ b/provisioning/transport/amqp/tests/ProvisioningErrorDetailsAmqpTests.cs @@ -114,7 +114,7 @@ public void GetRetryFromRejectedReturnsNullIfNoError() public void GetRetryAfterFromApplicationPropertiesSuccess() { int expectedRetryAfter = 42; - using AmqpMessage amqpResponse = AmqpMessage.Create(); + using var amqpResponse = AmqpMessage.Create(); amqpResponse.ApplicationProperties = new ApplicationProperties(); amqpResponse.ApplicationProperties.Map.Add(new MapKey("Retry-After"), expectedRetryAfter); TimeSpan? actual = ProvisioningErrorDetailsAmqp.GetRetryAfterFromApplicationProperties(amqpResponse, s_defaultInterval); @@ -126,7 +126,7 @@ public void GetRetryAfterFromApplicationPropertiesSuccess() public void GetRetryAfterFromApplicationPropertiesReturnsDefaultIfRetryAfterValueIsNegative() { int expectedRetryAfter = -1; - using AmqpMessage amqpResponse = AmqpMessage.Create(); + using var amqpResponse = AmqpMessage.Create(); amqpResponse.ApplicationProperties = new ApplicationProperties(); amqpResponse.ApplicationProperties.Map.Add(new MapKey("Retry-After"), expectedRetryAfter); TimeSpan? actual = ProvisioningErrorDetailsAmqp.GetRetryAfterFromApplicationProperties(amqpResponse, s_defaultInterval); @@ -138,7 +138,7 @@ public void GetRetryAfterFromApplicationPropertiesReturnsDefaultIfRetryAfterValu public void GetRetryAfterFromApplicationPropertiesReturnsDefaultIfRetryAfterValueIsZero() { int expectedRetryAfter = 0; - using AmqpMessage amqpResponse = AmqpMessage.Create(); + using var amqpResponse = AmqpMessage.Create(); amqpResponse.ApplicationProperties = new ApplicationProperties(); amqpResponse.ApplicationProperties.Map.Add(new MapKey("Retry-After"), expectedRetryAfter); TimeSpan? actual = ProvisioningErrorDetailsAmqp.GetRetryAfterFromApplicationProperties(amqpResponse, s_defaultInterval); @@ -149,7 +149,7 @@ public void GetRetryAfterFromApplicationPropertiesReturnsDefaultIfRetryAfterValu [TestMethod] public void GetRetryAfterFromApplicationPropertiesReturnsNullIfNoRetryAfterApplicationProperty() { - using AmqpMessage amqpResponse = AmqpMessage.Create(); + using var amqpResponse = AmqpMessage.Create(); amqpResponse.ApplicationProperties = new ApplicationProperties(); TimeSpan? actual = ProvisioningErrorDetailsAmqp.GetRetryAfterFromApplicationProperties(amqpResponse, s_defaultInterval); Assert.IsNull(actual); @@ -158,7 +158,7 @@ public void GetRetryAfterFromApplicationPropertiesReturnsNullIfNoRetryAfterAppli [TestMethod] public void GetRetryAfterFromApplicationPropertiesReturnsNullIfNoApplicationProperties() { - using AmqpMessage amqpResponse = AmqpMessage.Create(); + using var amqpResponse = AmqpMessage.Create(); TimeSpan? actual = ProvisioningErrorDetailsAmqp.GetRetryAfterFromApplicationProperties(amqpResponse, s_defaultInterval); Assert.IsNull(actual); } diff --git a/provisioning/transport/amqp/tests/RetryJitterTests.cs b/provisioning/transport/amqp/tests/RetryJitterTests.cs index 87580c7486..e7253b5c7a 100644 --- a/provisioning/transport/amqp/tests/RetryJitterTests.cs +++ b/provisioning/transport/amqp/tests/RetryJitterTests.cs @@ -15,7 +15,7 @@ public class RetryJitterTests public void RetryJitterGeneratedDelayLargerOrEqualToDefaultDelay() { int expectedMinimumDelay = 2; - TimeSpan DefaultDelay = TimeSpan.FromSeconds(expectedMinimumDelay); + var DefaultDelay = TimeSpan.FromSeconds(expectedMinimumDelay); TimeSpan GeneratedDelay = RetryJitter.GenerateDelayWithJitterForRetry(DefaultDelay); Assert.IsNotNull(GeneratedDelay); Assert.IsTrue(GeneratedDelay.Seconds >= DefaultDelay.Seconds); @@ -26,7 +26,7 @@ public void RetryJitterGeneratedDelayNoLargerThanFiveSeconds() { //current maximum jitter delay is 5 seconds, may change in the future int expectedMinimumDelay = 0; - TimeSpan DefaultDelay = TimeSpan.FromSeconds(expectedMinimumDelay); + var DefaultDelay = TimeSpan.FromSeconds(expectedMinimumDelay); TimeSpan GeneratedDelay = RetryJitter.GenerateDelayWithJitterForRetry(DefaultDelay); Assert.IsNotNull(GeneratedDelay); Assert.IsTrue(GeneratedDelay.Seconds <= 5); diff --git a/provisioning/transport/http/src/ApiVersionDelegatingHandler.cs b/provisioning/transport/http/src/ApiVersionDelegatingHandler.cs index be725b4b38..09823cb382 100644 --- a/provisioning/transport/http/src/ApiVersionDelegatingHandler.cs +++ b/provisioning/transport/http/src/ApiVersionDelegatingHandler.cs @@ -19,7 +19,7 @@ protected override Task SendAsync(HttpRequestMessage reques Logging.Enter(this, $"{request.RequestUri}", nameof(SendAsync)); } - var valueCollection = HttpUtility.ParseQueryString(request.RequestUri.Query); + System.Collections.Specialized.NameValueCollection valueCollection = HttpUtility.ParseQueryString(request.RequestUri.Query); valueCollection[ClientApiVersionHelper.ApiVersionName] = ClientApiVersionHelper.ApiVersion; var builder = new UriBuilder(request.RequestUri) diff --git a/provisioning/transport/http/src/CertificateChainCredentials.cs b/provisioning/transport/http/src/CertificateChainCredentials.cs index de193c865d..cbfffad02f 100644 --- a/provisioning/transport/http/src/CertificateChainCredentials.cs +++ b/provisioning/transport/http/src/CertificateChainCredentials.cs @@ -24,7 +24,7 @@ public override void InitializeServiceClient(ServiceClient client) { base.InitializeServiceClient(client); - HttpClientHandler httpClientHandler = client.HttpMessageHandlers.FirstOrDefault((handler) => handler is HttpClientHandler) as HttpClientHandler; + var httpClientHandler = client.HttpMessageHandlers.FirstOrDefault((handler) => handler is HttpClientHandler) as HttpClientHandler; Debug.Assert(httpClientHandler != null); httpClientHandler.ClientCertificates.AddRange(_certificateChain.ToArray()); diff --git a/provisioning/transport/http/src/Generated/RuntimeRegistration.cs b/provisioning/transport/http/src/Generated/RuntimeRegistration.cs index 954f915718..93e7cdd305 100644 --- a/provisioning/transport/http/src/Generated/RuntimeRegistration.cs +++ b/provisioning/transport/http/src/Generated/RuntimeRegistration.cs @@ -100,7 +100,7 @@ public async Task> OperationS if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(CultureInfo.InvariantCulture); - Dictionary tracingParameters = new Dictionary + var tracingParameters = new Dictionary { { "registrationId", registrationId }, { "operationId", operationId }, @@ -110,8 +110,8 @@ public async Task> OperationS ServiceClientTracing.Enter(_invocationId, this, "OperationStatusLookup", tracingParameters); } // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new Uri( + string _baseUrl = Client.BaseUri.AbsoluteUri; + string _url = new Uri( new Uri(_baseUrl + (_baseUrl.EndsWith("/", StringComparison.Ordinal) ? "" : "/")), "{idScope}/registrations/{registrationId}/operations/{operationId}").ToString(); @@ -134,7 +134,7 @@ public async Task> OperationS if (customHeaders != null) { - foreach (var _header in customHeaders) + foreach (KeyValuePair> _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { @@ -292,7 +292,7 @@ public async Task> OperationS if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(CultureInfo.InvariantCulture); - Dictionary tracingParameters = new Dictionary + var tracingParameters = new Dictionary { { "registrationId", registrationId }, { "deviceRegistration", deviceRegistration }, @@ -302,8 +302,8 @@ public async Task> OperationS ServiceClientTracing.Enter(_invocationId, this, "DeviceRegistrationStatusLookup", tracingParameters); } // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/", StringComparison.Ordinal) ? "" : "/")), "{idScope}/registrations/{registrationId}").ToString(); + string _baseUrl = Client.BaseUri.AbsoluteUri; + string _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/", StringComparison.Ordinal) ? "" : "/")), "{idScope}/registrations/{registrationId}").ToString(); #if NETSTANDARD2_1 _url = _url.Replace("{registrationId}", Uri.EscapeDataString(registrationId), StringComparison.Ordinal); @@ -322,7 +322,7 @@ public async Task> OperationS if (customHeaders != null) { - foreach (var _header in customHeaders) + foreach (KeyValuePair> _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { @@ -473,7 +473,7 @@ public async Task> RegisterDe if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(CultureInfo.InvariantCulture); - Dictionary tracingParameters = new Dictionary + var tracingParameters = new Dictionary { { "registrationId", registrationId }, { "deviceRegistration", deviceRegistration }, @@ -484,8 +484,8 @@ public async Task> RegisterDe ServiceClientTracing.Enter(_invocationId, this, "RegisterDevice", tracingParameters); } // Construct URL - var _baseUrl = Client.BaseUri.AbsoluteUri; - var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/", StringComparison.Ordinal) ? "" : "/")), "{idScope}/registrations/{registrationId}/register").ToString(); + string _baseUrl = Client.BaseUri.AbsoluteUri; + string _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/", StringComparison.Ordinal) ? "" : "/")), "{idScope}/registrations/{registrationId}/register").ToString(); #if NETSTANDARD2_1 _url = _url.Replace("{registrationId}", Uri.EscapeDataString(registrationId), StringComparison.Ordinal); @@ -495,7 +495,7 @@ public async Task> RegisterDe _url = _url.Replace("{idScope}", Uri.EscapeDataString(idScope)); #endif - List _queryParameters = new List(); + var _queryParameters = new List(); if (forceRegistration != null) { _queryParameters.Add(string.Format( @@ -516,7 +516,7 @@ public async Task> RegisterDe if (customHeaders != null) { - foreach (var _header in customHeaders) + foreach (KeyValuePair> _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { diff --git a/provisioning/transport/http/src/Generated/RuntimeRegistrationExtensions.cs b/provisioning/transport/http/src/Generated/RuntimeRegistrationExtensions.cs index 5730b86369..51b034e257 100644 --- a/provisioning/transport/http/src/Generated/RuntimeRegistrationExtensions.cs +++ b/provisioning/transport/http/src/Generated/RuntimeRegistrationExtensions.cs @@ -61,7 +61,7 @@ public static async Task OperationStatusLookupAsync string idScope, CancellationToken cancellationToken = default(CancellationToken)) { - using (var _result = await operations.OperationStatusLookupWithHttpMessagesAsync( + using (Rest.HttpOperationResponse _result = await operations.OperationStatusLookupWithHttpMessagesAsync( registrationId, operationId, idScope, @@ -119,7 +119,7 @@ public static Models.DeviceRegistrationResult DeviceRegistrationStatusLookup( DeviceRegistration deviceRegistration = default(DeviceRegistration), CancellationToken cancellationToken = default(CancellationToken)) { - using (var _result = await operations.DeviceRegistrationStatusLookupWithHttpMessagesAsync( + using (Rest.HttpOperationResponse _result = await operations.DeviceRegistrationStatusLookupWithHttpMessagesAsync( registrationId, idScope, deviceRegistration, @@ -187,7 +187,7 @@ public static async Task RegisterDeviceAsync( bool? forceRegistration = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { - using (var _result = await operations.RegisterDeviceWithHttpMessagesAsync(registrationId, idScope, deviceRegistration, forceRegistration, null, cancellationToken).ConfigureAwait(false)) + using (Rest.HttpOperationResponse _result = await operations.RegisterDeviceWithHttpMessagesAsync(registrationId, idScope, deviceRegistration, forceRegistration, null, cancellationToken).ConfigureAwait(false)) { _result.Body.RetryAfter = _result.Response.Headers.RetryAfter?.Delta; return _result.Body; diff --git a/provisioning/transport/http/src/GlobalSuppressions.cs b/provisioning/transport/http/src/GlobalSuppressions.cs index 7fc7c806ad..15f281aa6f 100644 --- a/provisioning/transport/http/src/GlobalSuppressions.cs +++ b/provisioning/transport/http/src/GlobalSuppressions.cs @@ -5,5 +5,15 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] diff --git a/provisioning/transport/http/src/ProvisioningTransportHandlerHttp.cs b/provisioning/transport/http/src/ProvisioningTransportHandlerHttp.cs index 6014d906a5..c70a7341a1 100644 --- a/provisioning/transport/http/src/ProvisioningTransportHandlerHttp.cs +++ b/provisioning/transport/http/src/ProvisioningTransportHandlerHttp.cs @@ -187,7 +187,7 @@ await Task try { - var errorDetails = JsonConvert.DeserializeObject(ex.Response.Content); + ProvisioningErrorDetailsHttp errorDetails = JsonConvert.DeserializeObject(ex.Response.Content); if (isTransient) { @@ -248,7 +248,7 @@ await Task try { - var errorDetails = JsonConvert.DeserializeObject(ex.Response.Content); + ProvisioningErrorDetailsHttp errorDetails = JsonConvert.DeserializeObject(ex.Response.Content); throw new ProvisioningTransportException(ex.Response.Content, ex, isTransient, errorDetails); } catch (JsonException jex) diff --git a/provisioning/transport/http/src/SymmetricKeyCredentials.cs b/provisioning/transport/http/src/SymmetricKeyCredentials.cs index 88b253eca9..ed652f092e 100644 --- a/provisioning/transport/http/src/SymmetricKeyCredentials.cs +++ b/provisioning/transport/http/src/SymmetricKeyCredentials.cs @@ -30,7 +30,7 @@ public SymmetricKeyCredentials(string symmetricKey) : base() public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string audience = request.RequestUri.AbsolutePath.Trim('/'); - var segments = audience.Split('/'); + string[] segments = audience.Split('/'); _sasToken = ProvisioningSasBuilder.BuildSasSignature(Registration, this.SymmetricKey, string.Concat(segments[0], '/', segments[1], '/', segments[2]), TimeSpan.FromDays(1)); SetAuthorizationHeader(request, _sasToken); diff --git a/provisioning/transport/mqtt/src/GlobalSuppressions.cs b/provisioning/transport/mqtt/src/GlobalSuppressions.cs index 7fc7c806ad..15f281aa6f 100644 --- a/provisioning/transport/mqtt/src/GlobalSuppressions.cs +++ b/provisioning/transport/mqtt/src/GlobalSuppressions.cs @@ -5,5 +5,15 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] diff --git a/provisioning/transport/mqtt/src/ProvisioningErrorDetailsMqtt.cs b/provisioning/transport/mqtt/src/ProvisioningErrorDetailsMqtt.cs index 6c3288875e..8fd143bc5f 100644 --- a/provisioning/transport/mqtt/src/ProvisioningErrorDetailsMqtt.cs +++ b/provisioning/transport/mqtt/src/ProvisioningErrorDetailsMqtt.cs @@ -32,7 +32,7 @@ internal class ProvisioningErrorDetailsMqtt : ProvisioningErrorDetails int secondsToWait; if (int.TryParse(queryKeyAndValue[1], out secondsToWait)) { - TimeSpan serviceRecommendedDelay = TimeSpan.FromSeconds(secondsToWait); + var serviceRecommendedDelay = TimeSpan.FromSeconds(secondsToWait); if (serviceRecommendedDelay.TotalSeconds < defaultPoolingInterval.TotalSeconds) { diff --git a/shared/src/GlobalSuppressions.cs b/shared/src/GlobalSuppressions.cs index 7fc7c806ad..15f281aa6f 100644 --- a/shared/src/GlobalSuppressions.cs +++ b/shared/src/GlobalSuppressions.cs @@ -5,5 +5,15 @@ // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Not localizing", Scope = "module")] -[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "SDK hides non-actionable errors from user", Scope = "module")] +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Globalization", + "CA1303:Do not pass literals as localized parameters", + Justification = "Not localizing", + Scope = "module")] +[assembly: SuppressMessage( + "Design", + "CA1031:Do not catch general exception types", + Justification = "SDK hides non-actionable errors from user", + Scope = "module")] diff --git a/shared/src/TwinCollectionJsonConverter.cs b/shared/src/TwinCollectionJsonConverter.cs index 794feb4ddb..7860decdfd 100644 --- a/shared/src/TwinCollectionJsonConverter.cs +++ b/shared/src/TwinCollectionJsonConverter.cs @@ -21,7 +21,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s return; } - TwinCollection properties = value as TwinCollection; + var properties = value as TwinCollection; if (properties == null) { throw new InvalidOperationException("Object passed is not of type TwinCollection."); diff --git a/shared/src/TwinJsonConverter.cs b/shared/src/TwinJsonConverter.cs index cfe404a3a6..718a3fe703 100644 --- a/shared/src/TwinJsonConverter.cs +++ b/shared/src/TwinJsonConverter.cs @@ -248,7 +248,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist break; case CapabilitiesJsonTag: - var capabilitiesDictionary = serializer.Deserialize>(reader); + Dictionary capabilitiesDictionary = serializer.Deserialize>(reader); twin.Capabilities = new DeviceCapabilities { IotEdge = capabilitiesDictionary.ContainsKey(IotEdgeName) && (bool)capabilitiesDictionary[IotEdgeName]