public async Task <DeviceModel> UpdateDeviceEnabledStatusAsync(string deviceId, bool isEnabled) { DeviceModel repositoryDevice = null; ExceptionDispatchInfo capturedException = null; // if an exception happens at this point pass it up the stack to handle it await _iotHubRepository.UpdateDeviceEnabledStatusAsync(deviceId, isEnabled); try { repositoryDevice = await _deviceRegistryCrudRepository.UpdateDeviceEnabledStatusAsync(deviceId, isEnabled); } catch (Exception ex) { // grab the exception so we can attempt an async removal of the device from the IotHub capturedException = ExceptionDispatchInfo.Capture(ex); } // Since the rollback code runs async and async code cannot run within the catch block it is run here if (capturedException != null) { // This is a lazy attempt to revert the enabled status of the device in the IotHub. // If it fails the device status will still remain the same in the IotHub. // A more robust rollback may be needed in some scenarios. await _iotHubRepository.UpdateDeviceEnabledStatusAsync(deviceId, !isEnabled); capturedException.Throw(); } if (repositoryDevice == null || !repositoryDevice.IsSimulatedDevice) { return(repositoryDevice); } return(await this.AddOrRemoveSimulatedDevice(repositoryDevice, isEnabled)); }
public async void UpdateDeviceEnabledStatusAsync() { var deviceId = fixture.Create <string>(); var device = new Device(deviceId); device.Status = DeviceStatus.Enabled; deviceManagerMock.Setup(dm => dm.GetDeviceAsync(deviceId)) .ReturnsAsync(device); deviceManagerMock.Setup(dm => dm.UpdateDeviceAsync(It.IsAny <Device>())) .ReturnsAsync(device); var sameDevice = await iotHubRepository.UpdateDeviceEnabledStatusAsync(deviceId, false); Assert.Equal(sameDevice.Status, DeviceStatus.Disabled); sameDevice = await iotHubRepository.UpdateDeviceEnabledStatusAsync(deviceId, true); Assert.Equal(sameDevice.Status, DeviceStatus.Enabled); }