Esempio n. 1
0
        /// <summary>
        /// Gets <see cref="DevicePropertyValueModel" /> for an edited Device's
        /// properties.
        /// </summary>
        /// <param name="device">
        /// The edited Device.
        /// </param>
        /// <returns>
        /// <see cref="DevicePropertyValueModel" />s, representing
        /// <paramref name="device" />'s properties.
        /// </returns>
        public IEnumerable <DevicePropertyValueModel> ExtractDevicePropertyValuesModels(
            dynamic device)
        {
            dynamic deviceProperties;
            IDynamicMetaObjectProvider dynamicMetaObjectProvider;
            string hostNameValue;
            IEnumerable <DevicePropertyValueModel> propValModels;
            ICustomTypeDescriptor typeDescriptor;

            if (object.ReferenceEquals(device, null))
            {
                throw new ArgumentNullException("device");
            }

            deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);
            if (object.ReferenceEquals(deviceProperties, null))
            {
                throw new ArgumentException(
                          "device.DeviceProperties is a null reference.",
                          "device");
            }

            if ((dynamicMetaObjectProvider =
                     deviceProperties as IDynamicMetaObjectProvider) != null)
            {
                propValModels = ExtractPropertyValueModels(dynamicMetaObjectProvider);
            }
            else if ((typeDescriptor =
                          deviceProperties as ICustomTypeDescriptor) != null)
            {
                propValModels = ExtractPropertyValueModels(typeDescriptor);
            }
            else
            {
                propValModels = ExtractPropertyValueModels((object)deviceProperties);
            }

            hostNameValue =
                _configProvider.GetConfigurationSettingValue("iotHub.HostName");

            if (!string.IsNullOrEmpty(hostNameValue))
            {
                propValModels =
                    propValModels.Concat(
                        new DevicePropertyValueModel[]
                {
                    new DevicePropertyValueModel()
                    {
                        DisplayOrder = 0,
                        IsEditable   = false,
                        IsIncludedWithUnregisteredDevices = true,
                        Name         = "HostName",
                        PropertyType = Models.PropertyType.String,
                        Value        = hostNameValue
                    }
                });
            }

            return(propValModels);
        }
        /// <summary>
        /// Used by the event processor to update the initial data for the device
        /// without deleting the CommandHistory and the original created date
        /// This assumes the device controls and has full knowledge of its metadata except for:
        /// - CreatedTime
        /// - CommandHistory
        /// </summary>
        /// <param name="device">Device information to save to the backend Device Registry</param>
        /// <returns>Combined device that was saved to registry</returns>
        public async Task <dynamic> UpdateDeviceFromDeviceInfoPacketAsync(dynamic device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            dynamic existingDevice = await GetDeviceAsync(DeviceSchemaHelper.GetDeviceID(device));

            // Save the command history, original created date, and system properties (if any) of the existing device
            if (DeviceSchemaHelper.GetDeviceProperties(existingDevice) != null)
            {
                dynamic deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);
                deviceProperties.CreatedTime = DeviceSchemaHelper.GetCreatedTime(existingDevice);
            }

            device.CommandHistory = existingDevice.CommandHistory;

            // Copy the existing system properties, or initialize them if they do not exist
            if (existingDevice.SystemProperties != null)
            {
                device.SystemProperties = existingDevice.SystemProperties;
            }
            else
            {
                DeviceSchemaHelper.InitializeSystemProperties(device, null);
            }

            return(await _deviceRegistryCrudRepository.UpdateDeviceAsync(device));
        }
Esempio n. 3
0
        /// <summary>
        /// Looks in all the Properties of the DeviceProperties instance on a device for the given search term
        /// </summary>
        /// <param name="device">Device to search</param>
        /// <param name="search">Value to search for</param>
        /// <returns>true - if at least one of the properties in DeviceProperties contains the value, false - no match was found</returns>
        private bool SearchTypePropertiesForValue(dynamic device, string search)
        {
            object devProps = null;

            // if the device or its system properties are null then
            // there's nothing that can be searched on
            if ((device == null) ||
                ((devProps = DeviceSchemaHelper.GetDeviceProperties(device)) == null))
            {
                return(false);
            }

            try
            {
                devProps = DeviceSchemaHelper.GetDeviceProperties(device);
            }
            catch (DeviceRequiredPropertyNotFoundException)
            {
                devProps = null;
            }

            if (devProps == null)
            {
                return(false);
            }

            // iterate through the DeviceProperties Properties and look for the search value
            // case insensitive search
            var upperCaseSearch = search.ToUpperInvariant();

            return(devProps.ToKeyValuePairs().Any(
                       t =>
                       (t.Value != null) &&
                       t.Value.ToString().ToUpperInvariant().Contains(upperCaseSearch)));
        }
Esempio n. 4
0
        public async Task <ActionResult> Index()
        {
            string                deviceId;
            DashboardModel        model;
            DeviceListQuery       query;
            DeviceListQueryResult queryResult;

            model = new DashboardModel();

            query = new DeviceListQuery()
            {
                Skip       = 0,
                Take       = MaxDevicesToDisplayOnDashboard,
                SortColumn = "DeviceID"
            };

            //The results of this query are used for populating the dropdown
            //As well as extracting location data. We want to include disabled
            //devices on the map, but not in the dropdown. The filters used
            //IN the query are apply additively to a "column". As a result, we
            //cannot filter on enabled AND disabled because the filters are
            //mutually exclusive. Also we cannot filter on !Pending. So to get
            //all that we need for both uses we need to just get all devices up
            //to the Take value and filter manually in the loop. The map will
            //filter out unregistered devices by virtue of their not having
            //location data.
            queryResult = await _deviceLogic.GetDevices(query);

            if ((queryResult != null) &&
                (queryResult.Results != null))
            {
                string  enabledState = "";
                dynamic props        = null;
                foreach (dynamic devInfo in queryResult.Results)
                {
                    try
                    {
                        deviceId     = DeviceSchemaHelper.GetDeviceID(devInfo);
                        props        = DeviceSchemaHelper.GetDeviceProperties(devInfo);
                        enabledState = props.HubEnabledState;
                    }
                    catch (DeviceRequiredPropertyNotFoundException)
                    {
                        continue;
                    }

                    if (!string.IsNullOrEmpty(deviceId) && !string.IsNullOrWhiteSpace(enabledState) && enabledState.ToLower() == "true")
                    {
                        model.DeviceIdsForDropdown.Add(new StringPair(deviceId, deviceId));
                    }
                }
            }

            model.DeviceLocations = _deviceLogic.ExtractLocationsData(queryResult.Results);
            model.MapApiQueryKey  = _configProvider.GetConfigurationSettingValue("MapApiQueryKey");

            return(View(model));
        }
        protected virtual void InitDeviceInfo(InitialDeviceConfig config)
        {
            dynamic initialDevice = SampleDeviceFactory.GetSampleSimulatedDevice(config.DeviceId, config.Key);

            DeviceProperties = DeviceSchemaHelper.GetDeviceProperties(initialDevice);
            Commands         = CommandSchemaHelper.GetSupportedCommands(initialDevice);
            HostName         = config.HostName;
            PrimaryAuthKey   = config.Key;
        }
Esempio n. 6
0
        public void GetDevicePropertiesShouldReturnDeviceProperties()
        {
            var d = GetValidDevice();

            var props = DeviceSchemaHelper.GetDeviceProperties(d);

            Assert.NotNull(props);
            Assert.AreEqual("test", props.DeviceID.ToString());
        }
        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);
        }
        private static void AssignDeviceProperties(string deviceId, dynamic device)
        {
            dynamic deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);

            deviceProperties.HubEnabledState = true;
            deviceProperties.Manufacturer    = "Fabrikam";
            deviceProperties.DeviceName      = string.Join(" Engine #", deviceId.Split('-'));
            deviceProperties.ModelNumber     = "FB-27b";
            deviceProperties.SerialNumber    = "FB" + GetIntBasedOnString(deviceId + "SerialNumber", 10000);
        }
        /// <summary>
        /// Used by the event processor to update the initial data for the device
        /// without deleting the CommandHistory and the original created date
        /// This assumes the device controls and has full knowledge of its metadata except for:
        /// - CreatedTime
        /// - CommandHistory
        /// </summary>
        /// <param name="device">Device information to save to the backend Device Registry</param>
        /// <returns>Combined device that was saved to registry</returns>
        public async Task <dynamic> UpdateDeviceFromDeviceInfoPacketAsync(dynamic device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            // Get original device document
            var     connectionDeviceId = DeviceSchemaHelper.GetConnectionDeviceId(device);
            dynamic existingDevice     = await GetDeviceAsync(connectionDeviceId);

            // Save the command history, original created date, and system properties (if any) of the existing device
            if (DeviceSchemaHelper.GetDeviceProperties(existingDevice) != null)
            {
                dynamic deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);
                deviceProperties.CreatedTime = DeviceSchemaHelper.GetCreatedTime(existingDevice);
            }

            device.CommandHistory = existingDevice.CommandHistory;

            // Copy the existing system properties, or initialize them if they do not exist
            if (existingDevice.SystemProperties != null)
            {
                device.SystemProperties = existingDevice.SystemProperties;
            }
            else
            {
                DeviceSchemaHelper.InitializeSystemProperties(device, null);
            }

            // Merge device back to existing so we don't drop missing data
            if (existingDevice is JObject)
            {
                //merge union of objects to avoid duplicates
                var MergeSetting = new JsonMergeSettings
                {
                    MergeArrayHandling = MergeArrayHandling.Union
                };

                existingDevice.Merge(device, MergeSetting);
            }

            // If there is Telemetry or Command objects from device, replace instead of merge
            if (device.Telemetry != null)
            {
                existingDevice.Telemetry = device.Telemetry;
            }
            if (device.Commands != null)
            {
                existingDevice.Commands = device.Commands;
            }


            return(await _deviceRegistryCrudRepository.UpdateDeviceAsync(existingDevice));
        }
        /// <summary>
        /// Generates a DeviceInfo packet for a simulated device to send over the wire
        /// </summary>
        /// <returns></returns>
        public virtual dynamic GetDeviceInfo()
        {
            dynamic device = DeviceSchemaHelper.BuildDeviceStructure(DeviceID, true);

            device.DeviceProperties = DeviceSchemaHelper.GetDeviceProperties(this);
            device.Commands         = CommandSchemaHelper.GetSupportedCommands(this);
            device.Version          = SampleDeviceFactory.VERSION_1_0;
            device.ObjectType       = SampleDeviceFactory.OBJECT_TYPE_DEVICE_INFO;

            return(device);
        }
Esempio n. 11
0
        /// <summary>
        /// Generates a DeviceInfo packet for a simulated device to send over the wire
        /// </summary>
        /// <returns></returns>
        public virtual dynamic GetDeviceInfo()
        {
            dynamic device = DeviceSchemaHelper.BuildDeviceStructure(DeviceID, true, null);

            device.DeviceProperties = DeviceSchemaHelper.GetDeviceProperties(this);
            device.Commands         = CommandSchemaHelper.GetSupportedCommands(this);
            device.Version          = SampleDeviceFactory.VERSION_1_0;
            device.ObjectType       = SampleDeviceFactory.OBJECT_TYPE_DEVICE_INFO;

            // Remove the system properties from a device, to better emulate the behavior of real devices when sending device info messages.
            DeviceSchemaHelper.RemoveSystemPropertiesForSimulatedDeviceInfo(device);

            return(device);
        }
Esempio n. 12
0
        /// <summary>
        /// Modified a Device using a list of
        /// <see cref="DevicePropertyValueModel" />.
        /// </summary>
        /// <param name="device">
        /// The Device to modify.
        /// </param>
        /// <param name="devicePropertyValueModels">
        /// The list of <see cref="DevicePropertyValueModel" />s for modifying
        /// <paramref name="device" />.
        /// </param>
        public void ApplyDevicePropertyValueModels(
            dynamic device,
            IEnumerable <DevicePropertyValueModel> devicePropertyValueModels)
        {
            dynamic deviceProperties;
            IDynamicMetaObjectProvider dynamicMetaObjectProvider;
            ICustomTypeDescriptor      typeDescriptor;

            if (object.ReferenceEquals(device, null))
            {
                throw new ArgumentNullException("device");
            }

            if (devicePropertyValueModels == null)
            {
                throw new ArgumentNullException("devicePropertyValueModels");
            }

            deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);
            if (object.ReferenceEquals(deviceProperties, null))
            {
                throw new ArgumentException(
                          "device.DeviceProperties is a null reference.",
                          "device");
            }

            if ((dynamicMetaObjectProvider =
                     deviceProperties as IDynamicMetaObjectProvider) != null)
            {
                ApplyPropertyValueModels(
                    dynamicMetaObjectProvider,
                    devicePropertyValueModels);
            }
            else if ((typeDescriptor =
                          deviceProperties as ICustomTypeDescriptor) != null)
            {
                ApplyPropertyValueModels(
                    typeDescriptor,
                    devicePropertyValueModels);
            }
            else
            {
                ApplyPropertyValueModels(
                    (object)deviceProperties,
                    devicePropertyValueModels);
            }
        }
        private static void AssignDeviceProperties(string deviceId, dynamic device)
        {
            int     randomId         = rand.Next(0, _possibleDeviceLocations.Count - 1);
            dynamic deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);

            deviceProperties.HubEnabledState = true;
            deviceProperties.Manufacturer    = "Contoso Inc.";
            deviceProperties.ModelNumber     = "MD-" + randomId;
            deviceProperties.SerialNumber    = "SER" + randomId;
            deviceProperties.FirmwareVersion = "1." + randomId;
            deviceProperties.Platform        = "Plat-" + randomId;
            deviceProperties.Processor       = "i3-" + randomId;
            deviceProperties.InstalledRAM    = randomId + " MB";

            // Choose a location among the 8 above and set Lat and Long for device properties
            deviceProperties.Latitude  = _possibleDeviceLocations[randomId].Latitude;
            deviceProperties.Longitude = _possibleDeviceLocations[randomId].Longitude;
        }
Esempio n. 14
0
        public async Task <dynamic> UpdateDeviceEnabledStatusAsync(string deviceId, bool isEnabled)
        {
            dynamic existingDevice = await GetDeviceAsync(deviceId);

            if (existingDevice == null)
            {
                throw new DeviceNotRegisteredException(deviceId);
            }

            dynamic deviceProps = DeviceSchemaHelper.GetDeviceProperties(existingDevice);

            deviceProps.HubEnabledState = isEnabled;
            DeviceSchemaHelper.UpdateUpdatedTime(existingDevice);

            existingDevice = await _docDbRestUtil.UpdateDocumentAsync(existingDevice);

            return(existingDevice);
        }
Esempio n. 15
0
        private static void AssignDeviceProperties(string deviceId, dynamic device)
        {
            dynamic deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);

            deviceProperties.HubEnabledState = true;
            deviceProperties.Manufacturer    = "Contoso Inc.";
            deviceProperties.ModelNumber     = "MD-" + GetIntBasedOnString(deviceId + "ModelNumber", 1000);
            deviceProperties.SerialNumber    = "SER" + GetIntBasedOnString(deviceId + "SerialNumber", 10000);
            deviceProperties.FirmwareVersion = "1." + GetIntBasedOnString(deviceId + "FirmwareVersion", 100);
            deviceProperties.Platform        = "Plat-" + GetIntBasedOnString(deviceId + "Platform", 100);
            deviceProperties.Processor       = "i3-" + GetIntBasedOnString(deviceId + "Processor", 10000);
            deviceProperties.InstalledRAM    = GetIntBasedOnString(deviceId + "InstalledRAM", 100) + " MB";

            // Choose a location between the 3 above and set Lat and Long for device properties
            int chosenLocation = GetIntBasedOnString(deviceId + "Location", _possibleDeviceLocations.Count);

            deviceProperties.Latitude  = _possibleDeviceLocations[chosenLocation].Latitude;
            deviceProperties.Longitude = _possibleDeviceLocations[chosenLocation].Longitude;
        }
        /// <summary>
        /// Used by the event processor to update the initial data for the device
        /// without deleting the CommandHistory and the original created date
        /// This assumes the device controls and has full knowledge of its metadata except for:
        /// - CreatedTime
        /// - CommandHistory
        /// </summary>
        /// <param name="device">Device information to save to the backend Device Registry</param>
        /// <returns>Combined device that was saved to registry</returns>
        public async Task <dynamic> UpdateDeviceFromDeviceInfoPacketAsync(dynamic device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            dynamic existingDevice = await GetDeviceAsync(DeviceSchemaHelper.GetDeviceID(device));

            // Save the command history and the original created date of the existing device
            if (DeviceSchemaHelper.GetDeviceProperties(existingDevice) != null)
            {
                dynamic deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);
                deviceProperties.CreatedTime = DeviceSchemaHelper.GetCreatedTime(existingDevice);
            }

            device.CommandHistory = existingDevice.CommandHistory;

            return(await _deviceRegistryCrudRepository.UpdateDeviceAsync(device));
        }
Esempio n. 17
0
        private async Task ValidateDevice(dynamic device)
        {
            List <string> validationErrors = new List <string>();

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

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

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

                throw validationException;
            }
        }
Esempio n. 18
0
        private async Task <List <dynamic> > LoadAllDevicesAsync()
        {
            var query = new DeviceListQuery()
            {
                Skip       = 0,
                Take       = MAX_DEVICES_TO_DISPLAY_ON_DASHBOARD,
                SortColumn = "DeviceID"
            };

            string deviceId;
            var    devices = new List <dynamic>();
            DeviceListQueryResult queryResult = await _deviceLogic.GetDevices(query);

            if ((queryResult != null) && (queryResult.Results != null))
            {
                string  enabledState = "";
                dynamic props        = null;
                foreach (dynamic devInfo in queryResult.Results)
                {
                    try
                    {
                        deviceId     = DeviceSchemaHelper.GetDeviceID(devInfo);
                        props        = DeviceSchemaHelper.GetDeviceProperties(devInfo);
                        enabledState = props.HubEnabledState;
                    }
                    catch (DeviceRequiredPropertyNotFoundException)
                    {
                        continue;
                    }

                    if (!string.IsNullOrWhiteSpace(deviceId))
                    {
                        devices.Add(devInfo);
                    }
                }
            }

            return(devices);
        }
Esempio n. 19
0
        public void Status_PendingShouldReturnBothNullTypes()
        {
            var list = GetListWithEnabledTestValues();

            var filters = new List <FilterInfo>()
            {
                new FilterInfo()
                {
                    ColumnName  = "StatuS", // intentionally use weird casing for test
                    FilterValue = "PendinG"
                }
            };

            var results = FilterHelper.FilterDeviceList(list, filters).ToList <dynamic>();

            Assert.AreEqual(2, results.Count());

            Assert.Throws <DeviceRequiredPropertyNotFoundException>(
                () => DeviceSchemaHelper.GetDeviceProperties(results[0]));

            Assert.AreEqual("EnabledNull", results[1].DeviceProperties.DeviceID.ToString());
        }
Esempio n. 20
0
        private static dynamic GetDefaultTestDevice()
        {
            dynamic device = DeviceSchemaHelper.BuildDeviceStructure("DeviceID-Test", true, null);
            dynamic props  = DeviceSchemaHelper.GetDeviceProperties(device);

            props.AvailablePowerSources = 123;
            props.BatteryLevel          = 12;
            props.CreatedTime           = new DateTime(2000, 01, 01);
            props.DeviceState           = "DeviceState-Test";
            props.HubEnabledState       = true;
            props.FirmwareVersion       = "FirmwareVersion-Test";
            props.InstalledRAM          = "InstalledRAM-Test";
            props.Manufacturer          = "Manufacturer-Test";
            props.MemoryFree            = 123;
            props.ModelNumber           = "ModelNumber-Test";
            props.Platform           = "Platform-Test";
            props.PowerSourceVoltage = 1234;
            props.Processor          = "Processor-Test";
            props.SerialNumber       = "SerialNumber-Test";
            props.UpdatedTime        = new DateTime(2000, 01, 01);

            return(device);
        }
Esempio n. 21
0
        private static void AssignDeviceProperties(string deviceId, dynamic device)
        {
            int     randomId         = rand.Next(0, _possibleDeviceLocations.Count - 1);
            dynamic deviceProperties = DeviceSchemaHelper.GetDeviceProperties(device);

            deviceProperties.HubEnabledState = true;
            deviceProperties.SerialNumber    = "SER" + randomId;
            deviceProperties.FirmwareVersion = "1." + randomId;

            /*deviceProperties.Manufacturer = "Contoso Inc.";
             * deviceProperties.ModelNumber = "MD-" + randomId;
             * deviceProperties.Platform = "Plat-" + randomId;
             * deviceProperties.Processor = "i3-" + randomId;
             * deviceProperties.InstalledRAM = randomId + " MB";*/
            deviceProperties.BatteryCapacity  = randomId * 2000 + " Ah";
            deviceProperties.OperatingVoltage = randomId * 20 + " V";
            deviceProperties.LoadingCapacity  = randomId * 100 + " Kg";
            deviceProperties.WheelBase        = randomId + 2000 + " mm";
            deviceProperties.MaxOperatingTemp = randomId + 100 + " °c";

            // Choose a location among the 16 above and set Lat and Long for device properties
            deviceProperties.Latitude  = _possibleDeviceLocations[randomId].Latitude;
            deviceProperties.Longitude = _possibleDeviceLocations[randomId].Longitude;
        }
Esempio n. 22
0
        private static IQueryable <dynamic> FilterItems(
            IQueryable <dynamic> list,
            FilterInfo filter)
        {
            Func <dynamic, bool>    applyFilter;
            Func <dynamic, dynamic> getValue;

            if (list == null)
            {
                throw new ArgumentNullException("item");
            }

            if (filter == null)
            {
                throw new ArgumentNullException("filter");
            }

            if (string.IsNullOrEmpty(filter.ColumnName))
            {
                throw new ArgumentException(
                          "filter.ColumnName is a null reference or empty string.",
                          "filter");
            }

            getValue =
                ReflectionHelper.ProducePropertyValueExtractor(
                    filter.ColumnName,
                    false,
                    false);

            applyFilter =
                (item) =>
            {
                dynamic columnValue;
                dynamic deviceProperties;

                if (item == null)
                {
                    throw new ArgumentNullException("item");
                }

                if ((filter.FilterType == FilterType.Status) ||
                    string.Equals(
                        filter.ColumnName,
                        "Status",
                        StringComparison.CurrentCultureIgnoreCase))
                {
                    return(GetValueMatchesStatus(item, filter.FilterValue));
                }

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

                columnValue = getValue(deviceProperties);
                return(GetValueSatisfiesFilter(columnValue, filter));
            };

            return(list.Where(applyFilter).AsQueryable());
        }
        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  = 47.6;
                maxLat  = 47.6;
                minLong = -122.3;
                maxLong = -122.3;
            }

            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);
        }
Esempio n. 24
0
        public DeviceListLocationsModel ExtractLocationsData(List <dynamic> devices)
        {
            var result = new DeviceListLocationsModel();

            //Initialize defaults around Seattle
            double minLat  = 47.6;
            double maxLat  = 47.6;
            double minLong = -122.3;
            double maxLong = -122.3;

            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;
                }
            }

            var offset = 0.05;

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

            return(result);
        }
Esempio n. 25
0
        /// <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());
            }
        }
Esempio n. 26
0
        public void GetDevicePropertiesShouldThrowIfMissingDeviceProperties()
        {
            var d = GetDeviceWithMissingDeviceProperties();

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