public DeviceMapQueryResponse GetDevicesTwinMapAsync(DeviceMapQueryConfiguration queryMapConfiguration)
        {
            DevicesDBCache deviceDB = _Cache.DevicesDB;

            if (!deviceDB.IsDevicesDBCacheInitialized)
            {
                return new DeviceMapQueryResponse()
                       {
                           Success = true
                       }
            }
            ;

            try
            {
                //Filtering search
                IEnumerable <DeviceTwinFlatModel> devices = deviceDB.Devices.Values;

                IEnumerable <DeviceTwinFlatModel> filteredQuery = InMemoryLinqDeviceQueryHelper.GetFilteredDevicesGroup(devices, new DeviceQueryRuleGroup(LogicalOperators.And)
                {
                    Rules = queryMapConfiguration.Filters
                });

                if (queryMapConfiguration.ViewId == "alerts")
                {
                    filteredQuery = filteredQuery.Where(p => p.StatusCode != 0);
                }

                List <DeviceMapEntity> mapDevicesAddresses = filteredQuery.Where(p => !string.IsNullOrEmpty(p.Location.CountryCode)).Select(p => new DeviceMapEntity()
                                                                                                                                            //{ Count = 1, Name = p.ProductName, GeoLatitude = p.GeoLatitude.ToString(), GeoLongitude = p.GeoLongitude.ToString() })
                {
                    GeoLatitude = p.Location.Latitude.ToString(), GeoLongitude = p.Location.Longitude.ToString()
                })
                                                             .ToList();
                return(new DeviceMapQueryResponse()
                {
                    Pushpins = mapDevicesAddresses,
                    IsDatabaseLoaded = deviceDB.IsDevicesDBCacheInitialized,
                    IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                    ErrorMessage = string.Empty,
                    Success = true,
                    LastUpdate = deviceDB.LastUpdate
                });
            }
            catch (Exception e)
            {
                Log.Error("Get IoTHub Devices Twin error {@error}", e.Message);
                return(new DeviceMapQueryResponse()
                {
                    Pushpins = new List <DeviceMapEntity>(),
                    IsDatabaseLoaded = true,
                    IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                    ErrorMessage = e.Message,
                    Success = true,
                    LastUpdate = deviceDB.LastUpdate
                });
            }
        }
        public IEnumerable <string> GetDevicesTwinIds(DeviceQueryRuleGroup where)
        {
            DevicesDBCache deviceDB = _Cache.DevicesDB;

            if (!deviceDB.IsDevicesDBCacheInitialized)
            {
                return(new List <string>());
            }

            try
            {
                //Get cached devices
                IEnumerable <DeviceTwinFlatModel> devices = deviceDB.Devices.Values;
                return(InMemoryLinqDeviceQueryHelper.GetFilteredDevicesIds(devices, where));
            }
            catch (Exception e)
            {
                Log.Error("Get IoTHub Devices Twin Ids error {@error}", e.Message);
                return(new List <string>());
            }
        }
        private DeviceQueryResponse GetGroupedDevicesResponse(DevicesDBCache deviceDB, IEnumerable <DeviceTwinFlatModel> filteredQuery, DeviceQueryConfiguration queryConfiguration)
        {
            try
            {
                IEnumerable <DeviceGroup> groups = InMemoryLinqDeviceQueryHelper.GetDevicesGroups(filteredQuery, queryConfiguration.GroupBy, queryConfiguration.OrderBySorting);

                int nbrGroups = groups.Count();
                groups = groups
                         .Skip(queryConfiguration.PageIndex * queryConfiguration.ItemsPerPage)
                         .Take(queryConfiguration.ItemsPerPage);

                return(new DeviceQueryResponse()
                {
                    Groups = groups,
                    GroupsCount = nbrGroups,
                    ItemsCount = filteredQuery.Count(),
                    IsDatabaseLoaded = deviceDB.IsDevicesDBCacheInitialized,
                    IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                    ErrorMessage = string.Empty,
                    Success = true,
                    LastUpdate = deviceDB.LastUpdate
                });
            }
            catch (Exception e)
            {
                Log.Error("Get IoTHub Devices Twin error {@error}", e.Message);
                return(new DeviceQueryResponse()
                {
                    Groups = new List <DeviceGroup>(),
                    GroupsCount = 0,
                    ItemsCount = 0,
                    IsDatabaseLoaded = deviceDB.IsDevicesDBCacheInitialized,
                    IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                    ErrorMessage = string.Empty,
                    Success = true,
                    LastUpdate = deviceDB.LastUpdate
                });
            }
        }
        public DeviceTwinSummaryAggregationsModel GetDevicesSummaryAggregationsAsync(string topActivatedGroupBy)
        {
            try
            {
                DevicesDBCache deviceDB = _Cache.DevicesDB;
                if (!deviceDB.IsDevicesDBCacheInitialized)
                {
                    return(new DeviceTwinSummaryAggregationsModel());
                }

                IEnumerable <DeviceTwinFlatModel>  devices          = deviceDB.Devices.Values;
                DeviceTwinSummaryAggregationsModel deviceSummaryAgg = new DeviceTwinSummaryAggregationsModel();

                //Device Summary
                deviceSummaryAgg.TotalDevicesCount        = deviceDB.Count;
                deviceSummaryAgg.ConnectedDevicesCount    = devices.Count(p => p.ConnectionStatus == DeviceConnectionStatus.Connected);
                deviceSummaryAgg.DisconnectedDevicesCount = devices.Count(p => p.ConnectionStatus == DeviceConnectionStatus.Disconnected);
                deviceSummaryAgg.ActivatedDevicesCount    = deviceSummaryAgg.ConnectedDevicesCount + deviceSummaryAgg.DisconnectedDevicesCount;
                deviceSummaryAgg.NotActivatedDevicesCount = deviceSummaryAgg.TotalDevicesCount - deviceSummaryAgg.ActivatedDevicesCount;

                //Alert
                deviceSummaryAgg.AlertCounts = devices.Where(p => p.StatusCode != 0).GroupBy(p => p.StatusCode).OrderByDescending(p => p.Count()).Select(p => new AlertCount()
                {
                    AlertCode = p.Key, Count = p.Count()
                }).ToList();

                IEnumerable <IGrouping <string, DeviceTwinFlatModel> > topActivatedDevices = InMemoryLinqDeviceQueryHelper.GetGroupByString(devices, topActivatedGroupBy);
                deviceSummaryAgg.DevicePerGroupActivated = topActivatedDevices
                                                           .Select(p => new DevicePerGroupActivated()
                {
                    GroupName = p.Key, PercentageActivated = 100 - (p.Where(x => x.ConnectionStatus == DeviceConnectionStatus.NotActivated).Count() * 100 / p.Count())
                })
                                                           .OrderByDescending(p => p.PercentageActivated)
                                                           .Take(10)
                                                           .ToList();

                return(deviceSummaryAgg);
            }
            catch (Exception e)
            {
                Log.Error("Get IoTHub Devices Twin error {@error}", e.Message);
                return(new DeviceTwinSummaryAggregationsModel());
            }
        }
        public DeviceMapAreaQueryResponse GetDevicesTwinMapAreaAsync(DeviceMapQueryConfiguration queryMapConfiguration)
        {
            DevicesDBCache deviceDB = _Cache.DevicesDB;

            if (!deviceDB.IsDevicesDBCacheInitialized)
            {
                return new DeviceMapAreaQueryResponse()
                       {
                           Success = true
                       }
            }
            ;

            try
            {
                //DeviceTwinSummaryAggregationsModel deviceSummaryAgg = new DeviceTwinSummaryAggregationsModel();
                Dictionary <string, int> devicesRetailer = new Dictionary <string, int>();

                IEnumerable <DeviceTwinFlatModel> devices = deviceDB.Devices.Values;

                IEnumerable <DeviceTwinFlatModel> filteredQuery = InMemoryLinqDeviceQueryHelper.GetFilteredDevicesGroup(devices, new DeviceQueryRuleGroup(LogicalOperators.And)
                {
                    Rules = queryMapConfiguration.Filters
                });

                IEnumerable <IGrouping <string, DeviceTwinFlatModel> > groups = null;

                if (queryMapConfiguration.ViewId == "count")
                {
                    groups = filteredQuery.Where(p => !string.IsNullOrEmpty(p.RetailerRegion)).GroupBy(p => p.RetailerRegion);
                    foreach (IGrouping <string, DeviceTwinFlatModel> group in groups)
                    {
                        devicesRetailer.Add(group.Key, group.Count());
                    }
                }
                else if (queryMapConfiguration.ViewId == "activated")
                {
                    groups = filteredQuery.Where(p => !string.IsNullOrEmpty(p.RetailerRegion)).GroupBy(p => p.RetailerRegion);
                    foreach (IGrouping <string, DeviceTwinFlatModel> group in groups)
                    {
                        devicesRetailer.Add(group.Key, 100 - (group.Where(x => x.ConnectionStatus == DeviceConnectionStatus.NotActivated).Count() * 100 / group.Count()));
                    }
                }
                else if (queryMapConfiguration.ViewId == "retailerName")
                {
                    string retailer = queryMapConfiguration.Filters.Find(p => p.Field == queryMapConfiguration.ViewId)?.Value;
                    if (!string.IsNullOrEmpty(retailer))
                    {
                        groups = devices.Where(p => !string.IsNullOrEmpty(p.RetailerRegion)).GroupBy(p => p.RetailerRegion);
                        foreach (IGrouping <string, DeviceTwinFlatModel> group in groups)
                        {
                            devicesRetailer.Add(group.Key, 100 - (group.Where(x => x.RetailerName != retailer).Count() * 100 / group.Count()));
                        }
                    }
                }
                else if (queryMapConfiguration.ViewId == "productFamily")
                {
                    string productFamily = queryMapConfiguration.Filters.Find(p => p.Field == queryMapConfiguration.ViewId)?.Value;
                    if (!string.IsNullOrEmpty(productFamily))
                    {
                        groups = devices.Where(p => !string.IsNullOrEmpty(p.RetailerRegion)).GroupBy(p => p.RetailerRegion);
                        foreach (IGrouping <string, DeviceTwinFlatModel> group in groups)
                        {
                            devicesRetailer.Add(group.Key, 100 - (group.Where(x => x.ProductFamily != productFamily).Count() * 100 / group.Count()));
                        }
                    }
                }

                return(new DeviceMapAreaQueryResponse()
                {
                    AreaItems = devicesRetailer,
                    IsDatabaseLoaded = deviceDB.IsDevicesDBCacheInitialized,
                    IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                    ErrorMessage = string.Empty,
                    Success = true,
                    LastUpdate = deviceDB.LastUpdate
                });
            }
            catch (Exception e)
            {
                Log.Error("Get IoTHub Devices Twin error {@error}", e.Message);
                return(new DeviceMapAreaQueryResponse()
                {
                    AreaItems = new Dictionary <string, int>(),
                    IsDatabaseLoaded = true,
                    IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                    ErrorMessage = e.Message,
                    Success = true,
                    LastUpdate = deviceDB.LastUpdate
                });
            }
        }
        public DeviceQueryResponse GetDevicesTwinInfoAsync(DeviceQueryConfiguration queryConfiguration)
        {
            DevicesDBCache deviceDB = _Cache.DevicesDB;

            if (!deviceDB.IsDevicesDBCacheInitialized)
            {
                return new DeviceQueryResponse()
                       {
                           Success = true
                       }
            }
            ;

            try
            {
                //Get cached devices
                IEnumerable <DeviceTwinFlatModel> devices = deviceDB.Devices.Values;

                //GroupBy Filter
                IEnumerable <DeviceTwinFlatModel> filteredQuery = InMemoryLinqDeviceQueryHelper.GetFilteredDevicesGroup(devices, queryConfiguration.Where);

                int nbrPages = filteredQuery.Count();
                if (string.IsNullOrEmpty(queryConfiguration.GroupBy))
                {
                    if (filteredQuery.Count() > 0)
                    {
                        filteredQuery = InMemoryLinqDeviceQueryHelper.GetOrderedDevices(filteredQuery, queryConfiguration.OrderBy, queryConfiguration.OrderBySorting)
                                        .Skip(queryConfiguration.PageIndex * queryConfiguration.ItemsPerPage)
                                        .Take(queryConfiguration.ItemsPerPage);
                    }
                    return(new DeviceQueryResponse()
                    {
                        Items = filteredQuery.Count() > 0 ? filteredQuery.Select(p => new DeviceInfoEntity(p)) : new List <DeviceInfoEntity>(),
                        ItemsCount = nbrPages,
                        IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                        IsDatabaseLoaded = deviceDB.IsDevicesDBCacheInitialized,
                        ErrorMessage = string.Empty,
                        Success = true,
                        LastUpdate = deviceDB.LastUpdate
                    });
                }
                else
                {
                    return(GetGroupedDevicesResponse(deviceDB, filteredQuery, queryConfiguration));
                }
            }
            catch (Exception e)
            {
                Log.Error("Get IoTHub Devices Twin error {@error}", e.Message);
                return(new DeviceQueryResponse()
                {
                    Items = new List <DeviceInfoEntity>(),
                    ItemsCount = 0,
                    IsDatabaseLoading = deviceDB.IsDevicesDBCacheLoading,
                    IsDatabaseLoaded = true,
                    ErrorMessage = e.Message,
                    Success = true,
                    LastUpdate = deviceDB.LastUpdate
                });
            }
        }