public async Task DeviceAuthenticationGoodAuthConfigTest2() { var deviceGoodAuthConfig = new Device("123") { ConnectionState = DeviceConnectionState.Connected, Authentication = new AuthenticationMechanism() { SymmetricKey = null, X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B", SecondaryThumbprint = "921BC9694ADEB8929D4F7FE4B9A3A6DE58B0790B" } } }; var restOpMock = new Mock<IHttpClientHelper>(); restOpMock.Setup( restOp => restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(), It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(), It.IsAny<CancellationToken>())).ReturnsAsync(deviceGoodAuthConfig); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.AddDeviceAsync(deviceGoodAuthConfig); }
public static DeviceClient CreateSelfSignedDevice(TransportType transport, string deviceId) { Console.Write("Connecting to hub.... "); var registryManager = RegistryManager.CreateFromConnectionString(hubConnStr); Console.WriteLine("done"); Console.Write("Creating device with self signed key.... "); var certificate = GetSelfSigned(); var device = new Microsoft.Azure.Devices.Device(deviceId) { Authentication = new AuthenticationMechanism { X509Thumbprint = new X509Thumbprint { PrimaryThumbprint = certificate.Thumbprint } } }; var createdDevice = registryManager.AddDeviceAsync(device).Result; Console.WriteLine($"done. Id='{deviceId}', X509Thumbprint = '{createdDevice.Authentication.X509Thumbprint.PrimaryThumbprint}'"); Console.Write("Connecting to device... "); var auth = new DeviceAuthenticationWithX509Certificate(deviceId, certificate); var client = DeviceClient.Create(hubUrl, auth, transport); Console.WriteLine("done"); return(client); }
private String CreateDeviceConnectionString(Device device) { StringBuilder deviceConnectionString = new StringBuilder(); var hostName = String.Empty; var tokenArray = iotHubConnectionString.Split(';'); for (int i = 0; i < tokenArray.Length; i++) { var keyValueArray = tokenArray[i].Split('='); if (keyValueArray[0] == "HostName") { hostName = tokenArray[i] + ';'; break; } } if (!String.IsNullOrWhiteSpace(hostName)) { deviceConnectionString.Append(hostName); deviceConnectionString.AppendFormat("DeviceId={0}", device.Id); if (device.Authentication != null && device.Authentication.SymmetricKey != null) { deviceConnectionString.AppendFormat(";SharedAccessKey={0}", device.Authentication.SymmetricKey.PrimaryKey); } if (this.protocolGatewayHostName.Length > 0) { deviceConnectionString.AppendFormat(";GatewayHostName=ssl://{0}:8883", this.protocolGatewayHostName); } } return deviceConnectionString.ToString(); }
public async Task <bool> AddDeviceWithSelfSignedCertificateAsync(string deviceId) { try { var device = new Microsoft.Azure.Devices.Device(deviceId) { Authentication = new AuthenticationMechanism { Type = AuthenticationType.SelfSigned, X509Thumbprint = new X509Thumbprint { PrimaryThumbprint = _primaryThumbprint, SecondaryThumbprint = "" } } }; Console.Write($"Adding device '{deviceId}' with self signed certificate auth . . . "); var newDevice = await _registryManager.AddDeviceAsync(device).ConfigureAwait(false); Console.WriteLine("DONE"); return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } }
public override Task<Device> AddDeviceAsync(Device device, CancellationToken cancellationToken) { this.EnsureInstanceNotClosed(); if (device == null) { throw new ArgumentNullException("device"); } if (string.IsNullOrWhiteSpace(device.Id)) { throw new ArgumentException(ApiResources.DeviceIdNotSet); } if (!string.IsNullOrEmpty(device.ETag)) { throw new ArgumentException(ApiResources.ETagSetWhileRegisteringDevice); } // auto generate keys if not specified if (device.Authentication == null) { device.Authentication = new AuthenticationMechanism(); } ValidateDeviceAuthentication(device); return this.httpClientHelper.PutAsync(GetRequestUri(device.Id), device, PutOperationType.CreateEntity, null, cancellationToken); }
/// <summary> /// ctor which takes a Device object along with import mode /// </summary> /// <param name="device"></param> /// <param name="importmode"></param> public ExportImportDevice(Device device, ImportMode importmode) { this.Id = device.Id; this.ETag = device.ETag; this.ImportMode = importmode; this.Status = device.Status; this.StatusReason = device.StatusReason; this.Authentication = device.Authentication; }
public async Task RegisterDeviceAsyncTest() { var deviceToReturn = new Device("123") { ConnectionState = DeviceConnectionState.Connected }; var restOpMock = new Mock<IHttpClientHelper>(); restOpMock.Setup(restOp => restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(), It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(), It.IsAny<CancellationToken>())).ReturnsAsync(deviceToReturn); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); var returnedDevice = await registryManager.AddDeviceAsync(deviceToReturn); Assert.AreSame(deviceToReturn, returnedDevice); restOpMock.VerifyAll(); }
public async Task <IActionResult> Register([FromBody] Device device) { ADevice.Device registeredDevice = await _iotHubService.RegisterDevice(device); HttpContext.Response.StatusCode = 201; return(Json(new { deviceKey = registeredDevice.Authentication.SymmetricKey.PrimaryKey, deviceId = registeredDevice.Id })); }
public DeviceCreatedForm(Device device) { InitializeComponent(); if (device.Authentication.SymmetricKey != null) { richTextBox.Text = $"ID={device.Id}\nPrimaryKey={device.Authentication.SymmetricKey.PrimaryKey}\nSecondaryKey={device.Authentication.SymmetricKey.SecondaryKey}"; } else if (device.Authentication.X509Thumbprint != null) { richTextBox.Text = $"ID={device.Id}\nPrimaryThumbPrint={device.Authentication.X509Thumbprint.PrimaryThumbprint}\nSecondaryThumbPrint={device.Authentication.X509Thumbprint.SecondaryThumbprint}"; } }
public async static Task RemoveDeviceAsync(string deviceId) { Microsoft.Azure.Devices.Device device = await registryManager.GetDeviceAsync(deviceId); try { await registryManager.RemoveDeviceAsync(device); } catch { } }
public async Task GetDeviceAsyncTest() { const string DeviceId = "123"; var deviceToReturn = new Device(DeviceId) { ConnectionState = DeviceConnectionState.Connected }; var restOpMock = new Mock<IHttpClientHelper>(); restOpMock.Setup(restOp => restOp.GetAsync<Device>(It.IsAny<Uri>(), It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(), null, false, It.IsAny<CancellationToken>())).ReturnsAsync(deviceToReturn); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); var device = await registryManager.GetDeviceAsync(DeviceId); Assert.AreSame(deviceToReturn, device); restOpMock.VerifyAll(); }
private static async Task RegisterDeviceAsync() { try { device = await registryManager.AddDeviceAsync(new Device(deviceId)); } catch (DeviceAlreadyExistsException) { device = await registryManager.GetDeviceAsync(deviceId); } deviceKey = device.Authentication.SymmetricKey.PrimaryKey; }
public async Task AddDeviceWithCertificateAuthorityAuthenticationAsync(string deviceId) { var device = new Microsoft.Azure.Devices.Device(deviceId) { Authentication = new AuthenticationMechanism { Type = AuthenticationType.CertificateAuthority } }; Console.Write($"Adding device '{deviceId}' with CA authentication . . . "); await _registryManager.AddDeviceAsync(device).ConfigureAwait(false); Console.WriteLine("COMPLETED"); }
/// <summary> /// This method registers a device with the IoT hub. If the device is already registered then the method will return the device /// </summary> /// <returns></returns> private async static Task RegisterDeviceAsync(string deviceId) { var device = await registryManager.GetDeviceAsync(deviceId); if (device == null) { device = new Microsoft.Azure.Devices.Device(deviceId); device = await registryManager.AddDeviceAsync(device); Console.WriteLine("Device registered: " + device.Authentication.SymmetricKey.PrimaryKey); } else { Console.WriteLine("Device " + deviceId + " exists"); } }
private async void createButton_Click(object sender, EventArgs e) { try { if (String.IsNullOrEmpty(deviceIDTextBox.Text)) { throw new ArgumentNullException("DeviceId cannot be empty!"); } var device = new Device(deviceIDTextBox.Text); device.Authentication = new AuthenticationMechanism(); if (keysRadioButton.Checked) { device.Authentication.SymmetricKey.PrimaryKey = primaryKeyTextBox.Text; device.Authentication.SymmetricKey.SecondaryKey = secondaryKeyTextBox.Text; } else if (x509RadioButton.Checked) { device.Authentication.SymmetricKey = null; device.Authentication.X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = primaryKeyTextBox.Text, SecondaryThumbprint = secondaryKeyTextBox.Text }; } await registryManager.AddDeviceAsync(device); var deviceCreated = new DeviceCreatedForm(device); deviceCreated.ShowDialog(); this.Close(); } catch (Exception ex) { using (new CenterDialog(this)) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
//------------------------------------------------------------------------------------------------------------------------ private async static Task <string> AddDeviceAsync(string deviceId) { Microsoft.Azure.Devices.Device device = null; bool registeredDevicesucceeded; try { device = await registryManager.AddDeviceAsync(new Microsoft.Azure.Devices.Device(deviceId)); registeredDevicesucceeded = true; } catch (DeviceAlreadyExistsException) { registeredDevicesucceeded = false; } if (!registeredDevicesucceeded) { device = await registryManager.GetDeviceAsync(deviceId); } return(device.Authentication.SymmetricKey.PrimaryKey); }
public async Task <Device> GetDevice(string deviceId) { try { Microsoft.Azure.Devices.Device device = await _registryManager.GetDeviceAsync(deviceId); if (device == null) { return(null); } else { return(device); } } catch (Exception e) { Log.Error("Get iotHub Device {@error}", e.Message); throw e; } }
private async void createButton_Click(object sender, EventArgs e) { try { Device device = new Device(deviceIDTextBox.Text); await registryManager.AddDeviceAsync(device); device = await registryManager.GetDeviceAsync(device.Id); device.Authentication.SymmetricKey.PrimaryKey = primaryKeyTextBox.Text; device.Authentication.SymmetricKey.SecondaryKey = secondaryKeyTextBox.Text; device = await registryManager.UpdateDeviceAsync(device); string deviceInfo = String.Format("ID={0}\nPrimaryKey={1}\nSecondaryKey={2}", device.Id, device.Authentication.SymmetricKey.PrimaryKey, device.Authentication.SymmetricKey.SecondaryKey); DeviceCreatedForm deviceCreated = new DeviceCreatedForm(device.Id, device.Authentication.SymmetricKey.PrimaryKey, device.Authentication.SymmetricKey.SecondaryKey); deviceCreated.ShowDialog(); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public async Task DeleteDeviceAsync(string deviceId) { try { Microsoft.Azure.Devices.Device device = await _registryManager.GetDeviceAsync(deviceId); if (device != null) { try { await _registryManager.RemoveDeviceAsync(device); } catch (Exception e) { Console.WriteLine("Device Delete exception" + e.Message); } } } catch (Exception e) { Log.Error("Delete device error {@error}", e.Message); throw e; } }
/// <summary> /// Register a new device with the system /// </summary> /// <param name="device"> /// The Device object to be registered. /// </param> /// <returns>echoes back the Device object with the generated keys and etags</returns> public abstract Task<Device> AddDeviceAsync(Device device);
static void ValidateDeviceAuthentication(Device device) { if (device.Authentication.SymmetricKey != null) { // either both keys should be specified or neither once should be specified (in which case // we will create both the keys in the service) if (string.IsNullOrWhiteSpace(device.Authentication.SymmetricKey.PrimaryKey) ^ string.IsNullOrWhiteSpace(device.Authentication.SymmetricKey.SecondaryKey)) { throw new ArgumentException(ApiResources.DeviceKeysInvalid); } } }
public override Task<Device> AddDeviceAsync(Device device) { return this.AddDeviceAsync(device, CancellationToken.None); }
public override Task RemoveDeviceAsync(Device device) { return this.RemoveDeviceAsync(device, CancellationToken.None); }
public override Task RemoveDeviceAsync(Device device, CancellationToken cancellationToken) { this.EnsureInstanceNotClosed(); if (device == null) { throw new ArgumentNullException("device"); } if (string.IsNullOrWhiteSpace(device.Id)) { throw new ArgumentException(IotHubApiResources.GetString(ApiResources.ParameterCannotBeNullOrWhitespace, "device.Id")); } if (string.IsNullOrWhiteSpace(device.ETag)) { throw new ArgumentException(ApiResources.ETagNotSetWhileDeletingDevice); } return this.RemoveDeviceAsync(device.Id, device, cancellationToken); }
public async Task DeleteDevices2AsyncWithDeviceIdNullTest() { var goodDevice = new Device("123") { ConnectionState = DeviceConnectionState.Connected, ETag = "234" }; var badDevice = new Device(); var restOpMock = new Mock<IHttpClientHelper>(); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.RemoveDevices2Async(new List<Device>() { goodDevice, badDevice }); Assert.Fail("DeleteDevices API did not throw exception when deviceId was null."); }
public override Task<Device> UpdateDeviceAsync(Device device, bool forceUpdate, CancellationToken cancellationToken) { this.EnsureInstanceNotClosed(); if (device == null) { throw new ArgumentNullException("device"); } if (string.IsNullOrWhiteSpace(device.Id)) { throw new ArgumentException(ApiResources.DeviceIdNotSet); } if (string.IsNullOrWhiteSpace(device.ETag) && !forceUpdate) { throw new ArgumentException(ApiResources.ETagNotSetWhileUpdatingDevice); } // auto generate keys if not specified if (device.Authentication == null) { device.Authentication = new AuthenticationMechanism(); } ValidateDeviceAuthentication(device); var errorMappingOverrides = new Dictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>(); errorMappingOverrides.Add(HttpStatusCode.PreconditionFailed, async (responseMessage) => new PreconditionFailedException(await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage))); errorMappingOverrides.Add(HttpStatusCode.NotFound, async responseMessage => { var responseContent = await ExceptionHandlingHelper.GetExceptionMessageAsync(responseMessage); return (Exception) new DeviceNotFoundException(responseContent, (Exception) null); }); PutOperationType operationType = forceUpdate ? PutOperationType.ForceUpdateEntity : PutOperationType.UpdateEntity; return this.httpClientHelper.PutAsync(GetRequestUri(device.Id), device, operationType, errorMappingOverrides, cancellationToken); }
static async Task CreateDevices(Options options) { if (string.IsNullOrEmpty(options.DeviceKey)) { throw new ArgumentException("Device key was not specified."); } RegistryManager registryManager = RegistryManager.CreateFromConnectionString(options.IotHubConnectionString); await registryManager.OpenAsync(); const int BatchSize = 500; var tasks = new List<Task>(BatchSize); foreach (List<int> pack in Enumerable.Range(options.DeviceStartingFrom, options.CreateDeviceCount).InSetsOf(BatchSize)) { tasks.Clear(); Console.WriteLine("Creating devices {0}..{1}", pack.First(), pack.Last()); foreach (int i in pack) { string deviceId = string.Format(options.DeviceNamePattern, i); var device = new Device(deviceId) { Authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = options.DeviceKey, SecondaryKey = options.DeviceKey2 } } }; tasks.Add(registryManager.AddDeviceAsync(device)); } await Task.WhenAll(tasks); } }
public override Task<Device> UpdateDeviceAsync(Device device, bool forceUpdate) { return this.UpdateDeviceAsync(device, forceUpdate, CancellationToken.None); }
public async Task DeviceAuthenticationBadAuthConfigTest7() { var deviceBadAuthConfig = new Device("123") { ConnectionState = DeviceConnectionState.Connected, Authentication = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = CryptoKeyGenerator.GenerateKey(32), SecondaryKey = null }, X509Thumbprint = null } }; var restOpMock = new Mock<IHttpClientHelper>(); restOpMock.Setup( restOp => restOp.PutAsync(It.IsAny<Uri>(), It.IsAny<Device>(), It.IsAny<PutOperationType>(), It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(), It.IsAny<CancellationToken>())).ReturnsAsync(deviceBadAuthConfig); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.AddDeviceAsync(deviceBadAuthConfig); }
/// <summary> /// Deletes a previously registered device from the system. /// </summary> /// <param name="device"> /// The device to be deleted. /// </param> /// <param name="cancellationToken"> /// The token which allows the the operation to be cancelled. /// </param> public abstract Task RemoveDeviceAsync(Device device, CancellationToken cancellationToken);
public async Task RegisterDevices2AsyncWithETagsSetTest() { var goodDevice = new Device("123") { ConnectionState = DeviceConnectionState.Connected }; var badDevice = new Device("234") { ConnectionState = DeviceConnectionState.Connected, ETag = "234" }; var restOpMock = new Mock<IHttpClientHelper>(); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.AddDevices2Async(new List<Device>() { goodDevice, badDevice }); Assert.Fail("RegisterDevices API did not throw exception when ETag was used."); }
public async Task UpdateDevices2AsyncWithNullDeviceTest() { var goodDevice = new Device("123") { ConnectionState = DeviceConnectionState.Connected, ETag = "234" }; Device badDevice = null; var restOpMock = new Mock<IHttpClientHelper>(); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.UpdateDevices2Async(new List<Device>() { goodDevice, badDevice }); Assert.Fail("UpdateDevices API did not throw exception when Null device was used."); }
public async Task DeleteDevices2AsyncForceDeleteFalseTest() { var goodDevice1 = new Device("123") { ConnectionState = DeviceConnectionState.Connected, ETag = "234" }; var goodDevice2 = new Device("234") { ConnectionState = DeviceConnectionState.Connected, ETag = "123" }; var restOpMock = new Mock<IHttpClientHelper>(); restOpMock.Setup(restOp => restOp.PostAsync<IEnumerable<ExportImportDevice>, Task<BulkRegistryOperationResult>>(It.IsAny<Uri>(), It.IsAny<IEnumerable<ExportImportDevice>>(), It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>())).ReturnsAsync(null); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.RemoveDevices2Async(new List<Device>() { goodDevice1, goodDevice2 }, false, CancellationToken.None); }
static async Task<string> selfRegisterAndSetConnString(string DeviceId) { Task<string> deviceConnString = null; try { registryManager = RegistryManager.CreateFromConnectionString(iotHubConnString); Device newDevice = new Device(DeviceId); await registryManager.AddDeviceAsync(newDevice); newDevice = await registryManager.GetDeviceAsync(DeviceId); newDevice.Authentication.SymmetricKey.PrimaryKey = CryptoKeyGenerator.GenerateKey(32); newDevice.Authentication.SymmetricKey.SecondaryKey = CryptoKeyGenerator.GenerateKey(32); newDevice = await registryManager.UpdateDeviceAsync(newDevice); string deviceInfo = String.Format("ID={0}\nPrimaryKey={1}\nSecondaryKey={2}", newDevice.Id, newDevice.Authentication.SymmetricKey.PrimaryKey, newDevice.Authentication.SymmetricKey.SecondaryKey); deviceConnString = Task.FromResult(string.Format("HostName={0};DeviceId={1};SharedAccessKey={2}", iotHubName, newDevice.Id, newDevice.Authentication.SymmetricKey.PrimaryKey)); } catch (Exception ex) { Console.WriteLine("An error occured creating device:{0}", ex.ToString()); } return deviceConnString.Result; }
public override Task<Device> UpdateDeviceAsync(Device device, CancellationToken cancellationToken) { return this.UpdateDeviceAsync(device, false, cancellationToken); }
public async Task RegisterDeviceAsyncWithETagSetTest() { var deviceToReturn = new Device("123") { ConnectionState = DeviceConnectionState.Connected, ETag = "123" }; var restOpMock = new Mock<IHttpClientHelper>(); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.AddDeviceAsync(deviceToReturn); Assert.Fail("RegisterDevice API did not throw exception when ETag was set."); }
public async Task UpdateDevicesAsyncForceUpdateMissingETagTest() { var badDevice1 = new Device("123") { ConnectionState = DeviceConnectionState.Connected }; var badDevice2 = new Device("234") { ConnectionState = DeviceConnectionState.Connected }; var restOpMock = new Mock<IHttpClientHelper>(); restOpMock.Setup(restOp => restOp.PostAsync<IEnumerable<ExportImportDevice>, Task<string[]>>(It.IsAny<Uri>(), It.IsAny<IEnumerable<ExportImportDevice>>(), It.IsAny<IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>())).ReturnsAsync(null); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.UpdateDevicesAsync(new List<Device>() { badDevice1, badDevice2 }, false, CancellationToken.None); }
public async Task DeleteDevicesAsyncWithInvalidDeviceIdTest() { var goodDevice = new Device("123") { ConnectionState = DeviceConnectionState.Connected }; var badDevice = new Device("/baddevice") { ConnectionState = DeviceConnectionState.Connected }; var restOpMock = new Mock<IHttpClientHelper>(); var registryManager = new HttpRegistryManager(restOpMock.Object, IotHubName); await registryManager.RemoveDevicesAsync(new List<Device>() { goodDevice, badDevice }); Assert.Fail("DeleteDevices API did not throw exception when bad deviceid was used."); }
/// <summary> /// Register a new device with the system /// </summary> /// <param name="device"> /// The Device object to be registered. /// </param> /// <param name="cancellationToken"> /// The token which allows the the operation to be cancelled. /// </param> /// <returns>echoes back the Device object with the generated keys and etags</returns> public abstract Task<Device> AddDeviceAsync(Device device, CancellationToken cancellationToken);