예제 #1
0
        private bool ValidateDeviceId(dynamic device, List <string> validationErrors)
        {
            if (DeviceSchemaHelper.GetDeviceProperties(device) == null || string.IsNullOrWhiteSpace(DeviceSchemaHelper.GetDeviceID(device)))
            {
                validationErrors.Add(Strings.ValidationDeviceIdMissing);
                return(false);
            }

            return(true);
        }
예제 #2
0
        public DeviceListLocationsModel ExtractLocationsData(List <dynamic> devices)
        {
            var result = new DeviceListLocationsModel();

            // Initialize defaults to opposite extremes to ensure mins and maxes are beyond any actual values
            double minLat  = double.MaxValue;
            double maxLat  = double.MinValue;
            double minLong = double.MaxValue;
            double maxLong = double.MinValue;

            var locationList = new List <DeviceLocationModel>();

            foreach (dynamic device in devices)
            {
                dynamic props = DeviceSchemaHelper.GetDeviceProperties(device);
                if (props.Longitude == null || props.Latitude == null)
                {
                    continue;
                }

                double latitude;
                double longitude;

                try
                {
                    latitude  = DeviceSchemaHelper.GetDeviceProperties(device).Latitude;
                    longitude = DeviceSchemaHelper.GetDeviceProperties(device).Longitude;
                }
                catch (FormatException)
                {
                    continue;
                }

                var location = new DeviceLocationModel()
                {
                    DeviceId  = DeviceSchemaHelper.GetDeviceID(device),
                    Longitude = longitude,
                    Latitude  = latitude
                };
                locationList.Add(location);

                if (longitude < minLong)
                {
                    minLong = longitude;
                }
                if (longitude > maxLong)
                {
                    maxLong = longitude;
                }
                if (latitude < minLat)
                {
                    minLat = latitude;
                }
                if (latitude > maxLat)
                {
                    maxLat = latitude;
                }
            }

            if (locationList.Count == 0)
            {
                // reinitialize bounds to center on Seattle area if no devices
                minLat  = 17.431978;
                maxLat  = 17.431978;
                minLong = 78.343696;
                maxLong = 78.343696;
            }

            double offset = 0.05;

            result.DeviceLocationList = locationList;
            result.MinimumLatitude    = minLat - offset;
            result.MaximumLatitude    = maxLat + offset;
            result.MinimumLongitude   = minLong - offset;
            result.MaximumLongitude   = maxLong + offset;

            return(result);
        }
        /// <summary>
        /// Sorts the device list on the given column in the given order
        /// </summary>
        /// <param name="deviceList">List of devices to sort</param>
        /// <param name="sortColumn">Column to sort on</param>
        /// <param name="sortOrder">Order to sort (asc/desc)</param>
        /// <returns>Sorted device list</returns>
        private IQueryable <dynamic> SortDeviceList(IQueryable <dynamic> deviceList, string sortColumn, QuerySortOrder sortOrder)
        {
            Func <dynamic, dynamic> getPropVal;
            Func <dynamic, dynamic> keySelector;

            // if a sort column was not provided then return the full device list in its original sort
            if (string.IsNullOrWhiteSpace(sortColumn))
            {
                return(deviceList);
            }

            getPropVal =
                ReflectionHelper.ProducePropertyValueExtractor(
                    sortColumn,
                    false,
                    false);

            keySelector =
                (item) =>
            {
                dynamic deviceProperties;

                if (item == null)
                {
                    return(null);
                }

                if (string.Equals(
                        "hubEnabledState",
                        sortColumn,
                        StringComparison.CurrentCultureIgnoreCase))
                {
                    try
                    {
                        return(DeviceSchemaHelper.GetHubEnabledState(item));
                    }
                    catch (DeviceRequiredPropertyNotFoundException)
                    {
                        return(null);
                    }
                }

                try
                {
                    deviceProperties =
                        DeviceSchemaHelper.GetDeviceProperties(item);
                }
                catch (DeviceRequiredPropertyNotFoundException)
                {
                    return(null);
                }

                return(getPropVal(deviceProperties));
            };

            if (sortOrder == QuerySortOrder.Ascending)
            {
                return(deviceList.OrderBy(keySelector).AsQueryable());
            }
            else
            {
                return(deviceList.OrderByDescending(keySelector).AsQueryable());
            }
        }
        private async Task ValidateDevice(dynamic device)
        {
            List <string> validationErrors = new List <string>();

            if (ValidateDeviceId(device, validationErrors))
            {
                await CheckIfDeviceExists(device, validationErrors);
            }

            if (validationErrors.Count > 0)
            {
                var validationException =
                    new ValidationException(DeviceSchemaHelper.GetDeviceProperties(device) != null ? DeviceSchemaHelper.GetDeviceID(device) : null);

                foreach (string error in validationErrors)
                {
                    validationException.Errors.Add(error);
                }

                throw validationException;
            }
        }
        /// <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);
        }
예제 #6
0
        public void GetCreatedTimeShouldThrowIfMissingCreatedTime()
        {
            var d = GetDeviceWithMissingCreatedTime();

            Assert.Throws <DeviceRequiredPropertyNotFoundException>(() => DeviceSchemaHelper.GetCreatedTime(d));
        }
예제 #7
0
        public void GetDeviceIDShouldThrowIfMissingDeviceProperties()
        {
            var d = GetDeviceWithMissingDeviceProperties();

            Assert.Throws <DeviceRequiredPropertyNotFoundException>(() => DeviceSchemaHelper.GetDeviceID(d));
        }