public async void AddDeviceAsync()
 {
     var device = fixture.Create<DeviceModel>();
     var keys = new SecurityKeys("fbsIV6w7gfVUyoRIQFSVgw ==", "1fLjiNCMZF37LmHnjZDyVQ ==");
     var sameDevice = await iotHubRepository.AddDeviceAsync(device, keys);
     Assert.Equal(sameDevice, device);
 }
        public static dynamic GetSampleDevice(Random randomNumber, SecurityKeys keys)
        {
            string deviceId = string.Format("00000-DEV-{0}C-{1}LK-{2}D-{3}",
                MAX_COMMANDS_SUPPORTED, randomNumber.Next(99999));
            dynamic device = DeviceSchemaHelper.BuildDeviceStructure(deviceId, false);
            device.ObjectName = "IoT Device Description";

            AssignDeviceProperties(deviceId, device);
            AssignCommands(device);

            return device;
        }
        public static DeviceModel GetSampleDevice(Random randomNumber, SecurityKeys keys)
        {
            var deviceId = string.Format(
                    CultureInfo.InvariantCulture,
                    "00000-DEV-{0}C-{1}LK-{2}D-{3}",
                    MAX_COMMANDS_SUPPORTED, 
                    randomNumber.Next(99999),
                    randomNumber.Next(99999),
                    randomNumber.Next(99999));

            var device = DeviceCreatorHelper.BuildDeviceStructure(deviceId, false, null);
            device.ObjectName = "IoT Device Description";

            AssignDeviceProperties(device);
            AssignTelemetry(device);
            AssignCommands(device);

            return device;
        }
        /// <summary>
        ///     Adds the provided device to the IoT hub with the provided security keys
        /// </summary>
        /// <param name="device"></param>
        /// <param name="securityKeys"></param>
        /// <returns></returns>
        public async Task<DeviceModel> AddDeviceAsync(DeviceModel device, SecurityKeys securityKeys)
        {
            var iotHubDevice = new Device(device.DeviceProperties.DeviceID);

            var authentication = new AuthenticationMechanism
                                 {
                                     SymmetricKey = new SymmetricKey
                                                    {
                                                        PrimaryKey = securityKeys.PrimaryKey,
                                                        SecondaryKey = securityKeys.SecondaryKey
                                                    }
                                 };

            iotHubDevice.Authentication = authentication;

            await AzureRetryHelper.OperationWithBasicRetryAsync(async () =>
                                                                await this._deviceManager.AddDeviceAsync(iotHubDevice));

            return device;
        }
        /// <summary>
        /// Adds the provided device to the IoT hub with the provided security keys
        /// </summary>
        /// <param name="device"></param>
        /// <param name="securityKeys"></param>
        /// <returns></returns>
        public async Task<dynamic> AddDeviceAsync(dynamic device, SecurityKeys securityKeys)
        {

            Azure.Devices.Device iotHubDevice = new Azure.Devices.Device(DeviceSchemaHelper.GetDeviceID(device));

            var authentication = new AuthenticationMechanism
            {
                SymmetricKey = new SymmetricKey
                {
                    PrimaryKey = securityKeys.PrimaryKey,
                    SecondaryKey = securityKeys.SecondaryKey
                }
            };

            iotHubDevice.Authentication = authentication;

            await AzureRetryHelper.OperationWithBasicRetryAsync<Azure.Devices.Device>(async () =>
                await _deviceManager.AddDeviceAsync(iotHubDevice));

            return device;
        }
 public DeviceWithKeys(DeviceModel device, SecurityKeys securityKeys)
 {
     Device = device;
     SecurityKeys = securityKeys;
 }
        /// <summary>
        /// Adds the given device and assigned keys to the underlying repositories 
        /// </summary>
        /// <param name="device">Device to add to repositories</param>
        /// <param name="securityKeys">Keys to assign to the device</param>
        /// <returns>Device that was added to the device registry</returns>
        private async Task<dynamic> AddDeviceToRepositoriesAsync(dynamic device, SecurityKeys securityKeys)
        {
            dynamic registryRepositoryDevice = null;
            ExceptionDispatchInfo capturedException = null;

            // if an exception happens at this point pass it up the stack to handle it
            // (Making this call first then the call against the Registry removes potential issues
            // with conflicting rollbacks if the operation happens to still be in progress.)
            await _iotHubRepository.AddDeviceAsync(device, securityKeys);

            try
            {
                registryRepositoryDevice = await _deviceRegistryCrudRepository.AddDeviceAsync(device);
            }
            catch (Exception ex)
            {
                // grab the exception so we can attempt an async removal of the device from the IotHub
                capturedException = ExceptionDispatchInfo.Capture(ex);

            }

            //Create a device in table storage if it is a simulated type of device 
            //and the document was stored correctly without an exception
            bool isSimulatedAsBool = false;
            try
            {
                isSimulatedAsBool = (bool)device.IsSimulatedDevice;
            }
            catch (InvalidCastException ex)
            {
                Trace.TraceError("The IsSimulatedDevice property was in an invalid format. Exception Error Message: {0}", ex.Message);
            }
            if (capturedException == null && isSimulatedAsBool) 
            {
                try
                {
                    await _virtualDeviceStorage.AddOrUpdateDeviceAsync(new InitialDeviceConfig() 
                    {
                        DeviceId = DeviceSchemaHelper.GetDeviceID(device),
                        HostName = _configProvider.GetConfigurationSettingValue("iotHub.HostName"),
                        Key = securityKeys.PrimaryKey
                    });
                }
                catch (Exception ex)
                {
                    //if we fail adding to table storage for the device simulator just continue
                    Trace.TraceError("Failed to add simulated device : {0}", ex.Message);
                }
            }
            

            // 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 remove the device from the Iot Hub.  If it fails
                // the device will still remain in the Iot Hub.  A more robust rollback may be needed
                // in some scenarios.
                await _iotHubRepository.TryRemoveDeviceAsync(DeviceSchemaHelper.GetDeviceID(device));
                capturedException.Throw();
            }

            return registryRepositoryDevice;
        }
        public async void AddDeviceAsyncTest()
        {
            var d1 = this.fixture.Create<DeviceModel>();
            this._iotHubRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny<DeviceModel>(), It.IsAny<SecurityKeys>()))
                .ReturnsAsync(d1);

            //Add device without DeviceProperties
            d1.DeviceProperties = null;
            await Assert.ThrowsAsync<ValidationException>(async () => await this._deviceLogic.AddDeviceAsync(d1));

            //Add device with Null or empty DeviceId
            d1.DeviceProperties = this.fixture.Create<DeviceProperties>();
            d1.DeviceProperties.DeviceID = null;
            await Assert.ThrowsAsync<ValidationException>(async () => await this._deviceLogic.AddDeviceAsync(d1));
            d1.DeviceProperties.DeviceID = "";
            await Assert.ThrowsAsync<ValidationException>(async () => await this._deviceLogic.AddDeviceAsync(d1));

            //Add existing device
            var d2 = this.fixture.Create<DeviceModel>();
            this._deviceRegistryCrudRepositoryMock.Setup(x => x.GetDeviceAsync(d2.DeviceProperties.DeviceID))
                .ReturnsAsync(d2);
            await Assert.ThrowsAsync<ValidationException>(async () => await this._deviceLogic.AddDeviceAsync(d2));

            d1.DeviceProperties.DeviceID = this.fixture.Create<string>();
            var keys = new SecurityKeys("fbsIV6w7gfVUyoRIQFSVgw ==", "1fLjiNCMZF37LmHnjZDyVQ ==");
            this._securityKeyGeneratorMock.Setup(x => x.CreateRandomKeys()).Returns(keys);
            var hostname = this.fixture.Create<string>();
            this._configProviderMock.Setup(x => x.GetConfigurationSettingValue(It.IsAny<string>())).Returns(hostname);

            //Device registry throws exception
            this._deviceRegistryCrudRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny<DeviceModel>()))
                .ThrowsAsync(new Exception());
            this._iotHubRepositoryMock.Setup(x => x.TryRemoveDeviceAsync(It.IsAny<string>())).ReturnsAsync(true).Verifiable();
            await Assert.ThrowsAsync<Exception>(async () => await this._deviceLogic.AddDeviceAsync(d1));
            this._virtualDeviceStorageMock.Verify(x => x.AddOrUpdateDeviceAsync(It.IsAny<InitialDeviceConfig>()),
                                                  Times.Never());
            this._iotHubRepositoryMock.Verify(x => x.TryRemoveDeviceAsync(d1.DeviceProperties.DeviceID), Times.Once());

            //Custom device
            d1.IsSimulatedDevice = false;
            this._deviceRegistryCrudRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny<DeviceModel>())).ReturnsAsync(d1);
            var ret = await this._deviceLogic.AddDeviceAsync(d1);
            this._virtualDeviceStorageMock.Verify(x => x.AddOrUpdateDeviceAsync(It.IsAny<InitialDeviceConfig>()),
                                                  Times.Never());
            Assert.NotNull(ret);
            Assert.Equal(d1, ret.Device);
            Assert.Equal(keys, ret.SecurityKeys);

            //Simulated device
            this._deviceRegistryCrudRepositoryMock.Setup(x => x.AddDeviceAsync(It.IsAny<DeviceModel>())).ReturnsAsync(d1);
            this._virtualDeviceStorageMock.Setup(x => x.AddOrUpdateDeviceAsync(It.IsAny<InitialDeviceConfig>())).Verifiable();
            d1.IsSimulatedDevice = true;
            ret = await this._deviceLogic.AddDeviceAsync(d1);
            this._virtualDeviceStorageMock.Verify(x => x.AddOrUpdateDeviceAsync(It.IsAny<InitialDeviceConfig>()),
                                                  Times.Once());
            Assert.NotNull(ret);
            Assert.Equal(d1, ret.Device);
            Assert.Equal(keys, ret.SecurityKeys);
        }
 public DeviceWithKeys(dynamic device, SecurityKeys securityKeys)
 {
     Device = device;
     SecurityKeys = securityKeys;
 }