Пример #1
0
        /// <summary>
        /// 请求 所有设备的 信息
        /// </summary>
        /// <param name="documents"></param>
        /// <returns></returns>
        public Status getAll(out List <Device> devices)
        {
            devices = new List <Device>();
            try
            {
                DeviceDAO       deviceDao    = Factory.getInstance <DeviceDAO>();
                List <DeviceVO> deviceVolist = deviceDao.getAll <DeviceVO>();
                foreach (DeviceVO deviceVo in deviceVolist)
                {
                    devices.Add(
                        new Device
                    {
                        deviceID          = deviceVo.deviceID,
                        IMEI              = deviceVo.IMEI,
                        deviceIndex       = deviceVo.deviceIndex,
                        deviceFreezeState = deviceVo.deviceState
                    });
                }

                return(Status.SUCCESS);
            }
            catch (Exception e)
            {
                Log.ErrorInfo(e.StackTrace);
                return(Status.SERVER_EXCEPTION);
            }
        }
Пример #2
0
        /// <summary>
        /// 创建设备
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public Status create(CreateDevice device)
        {
            try
            {
                DeviceDAO deviceDao = Factory.getInstance <DeviceDAO>();
                Dictionary <string, object> wherelist = new Dictionary <string, object>();

                Log.DebugInfo(device.ToString());
                //创建设备ID
                int deviceID = DeviceDAO.getID();

                //插入数据
                if (deviceDao.insert <DeviceVO>(
                        new DeviceVO
                {
                    deviceID = deviceID,
                    deviceIndex = device.deviceIndex,
                    IMEI = device.IMEI,
                    deviceState = 0
                }) < 0)
                {
                    return(Status.NAME_EXIST);
                }

                return(Status.SUCCESS);
            }
            catch (Exception e)
            {
                Log.ErrorInfo(e.StackTrace);
                return(Status.SERVER_EXCEPTION);
            }
        }
Пример #3
0
        public void GivenDeviceNameShouldReturnDevice()
        {
            var data = new List <Device>
            {
                new Device()
                {
                    Id = 0, Name = "A", UserId = 0
                },
                new Device()
                {
                    Id = 1, Name = "B", UserId = 1
                },
                new Device()
                {
                    Id = 2, Name = "C", UserId = 0
                }
            }.AsQueryable();

            var mockContext = new Mock <UserDataContext>();
            var mockSet     = SetupDbSet(data);

            mockContext.Setup(c => c.Device).Returns(mockSet.Object);

            var dao    = new DeviceDAO(mockContext.Object);
            var result = dao.GetByName("A");

            Assert.AreEqual("A", result.Name);
        }
Пример #4
0
        /// <summary>
        /// 更新时,请求 指定设备的 信息
        /// </summary>
        /// <param name="device"></param>
        /// <param name="deviceID"></param>
        /// <returns></returns>
        public Status getOneForUpdate(out UpdateDevice device, int deviceID)
        {
            device = new UpdateDevice();

            try
            {
                DeviceDAO deviceDao = Factory.getInstance <DeviceDAO>();
                DeviceVO  deviceVo  = deviceDao.getOne <DeviceVO>(deviceID);
                if (deviceVo == null)
                {
                    return(Status.NONFOUND);
                }

                device.deviceID    = deviceVo.deviceID;
                device.IMEI        = deviceVo.IMEI;
                device.deviceIndex = deviceVo.deviceIndex;

                return(Status.SUCCESS);
            }
            catch (Exception e)
            {
                Log.ErrorInfo(e.StackTrace);
                return(Status.SERVER_EXCEPTION);
            }
        }
Пример #5
0
        /// <summary>
        /// 更新时,提交 更新设备的 信息
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public Status update(UpdateDevice device)
        {
            Log.DebugInfo(device.ToString());
            try
            {
                DeviceDAO deviceDao = Factory.getInstance <DeviceDAO>();
                var       deviceVo  = deviceDao.getOne <DeviceVO>(device.deviceID);
                if (deviceVo == null)
                {
                    return(Status.NONFOUND);
                }


                Dictionary <string, object> setlist = new Dictionary <string, object>();
                setlist.Add("IMEI", device.IMEI);
                setlist.Add("deviceIndex", device.deviceIndex);
                if (deviceDao.update(
                        setlist, device.deviceID) < 0)
                {
                    return(Status.NAME_EXIST);
                }

                return(Status.SUCCESS);
            }
            catch (Exception e)
            {
                Log.ErrorInfo(e.StackTrace);
                return(Status.FAILURE);
            }
        }
Пример #6
0
        /// <summary>
        /// Create an Event Cluster
        /// </summary>
        /// <param name="eventObj">EventClusterCreationModel</param>
        /// <returns>EventClusterModel</returns>
        public async Task <EventClusterModel> CreateEventCluster(EventClusterCreationModel eventObj)
        {
            //If device doesn't exist, throw exception
            DeviceDAO deviceEntity = await _repoDevices.GetItemAsync(eventObj.DeviceId);

            if (deviceEntity == null)
            {
                throw new Exception($"No device found that matches DeviceId: {eventObj.DeviceId}");
            }

            EventClusterDAO eventCluster = new EventClusterDAO()
            {
                Id         = eventObj.EventClusterId.ToString(),
                Device     = _mapper.Map <EventClusterDeviceDAOObject>(deviceEntity),
                EventType  = eventObj.EventType.ToLower(),
                EventCount = 1,
                Events     = new EventDAOObject[] { _mapper.Map <EventDAOObject>(eventObj) },
                StartDate  = eventObj.Date
            };

            eventCluster.Id = await _repoEventClusters.CreateItemAsync(eventCluster);

            if (_repoEventClusters.IsDocumentKeyNull(eventCluster))
            {
                throw new Exception($"An error occured when creating a new cluster id for DeviceId: {eventObj.DeviceId}");
            }

            return(_mapper.Map <EventClusterModel>(eventCluster));
        }
Пример #7
0
        public void GivenValidObjectWithUserIdShouldAddObject()
        {
            var data = new List <Device>().AsQueryable();

            var mockContext = new Mock <UserDataContext>();
            var mockSet     = SetupDbSet(data);

            mockContext.Setup(c => c.Device).Returns(mockSet.Object);
            mockContext.Setup(c => c.DeviceType.Find(0)).Returns(new DeviceType()
            {
                Id = 1, Type = "Temperature"
            });
            mockContext.Setup(c => c.User.Find(0)).Returns(new User()
            {
                Id = 0, UserId = "ABCDEF"
            });
            mockSet.Setup(c => c.Add(It.IsAny <Device>())).Returns(new Device()
            {
                Id = 1, DeviceTypeId = 1, UserId = 1
            });

            var dao         = new DeviceDAO(mockContext.Object);
            var newUserType = dao.Add(new Device()
            {
                DeviceTypeId = 1, UserId = 1
            });

            mockSet.Verify(m => m.Add(It.IsAny <Device>()), Times.Once());
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
        }
        /// <summary>
        /// Update the LastAccessTime of a device
        /// </summary>
        /// <param name="deviceId">Device Id</param>
        /// <returns>DeviceHeartbeatUpdatedModel</returns>
        public async Task <DeviceHeartbeatUpdatedModel> UpdateHeartbeat(Guid deviceId)
        {
            if (deviceId == Guid.Empty)
            {
                throw new Exception($"No device found that matches DeviceId: {deviceId}");
            }

            DeviceDAO deviceDAO = await _repoDevices.GetItemAsync(deviceId);

            string etag = deviceDAO.ETag;

            deviceDAO.LastAccessTime = DateTime.UtcNow;

            try
            {
                await _repoDevices.UpdateItemAsync(deviceDAO);

                return(new DeviceHeartbeatUpdatedModel()
                {
                    Device = _mapper.Map <DeviceModel>(deviceDAO),
                    NeedsUpdate = deviceDAO.Enabled
                });
            }
            catch (DocumentClientException e)
            {
                //Update concurrency issue, retrying
                if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    return(await UpdateHeartbeat(deviceId));
                }
                throw e;
            }
        }
        public DeviceModel RegisterDevice(string deviceType)
        {
            try
            {
                DeviceType type = DeviceTypeDAO.GetByTypeName(deviceType);

                if (type == null)
                {
                    throw new Exception("Invalid Device Type");
                }

                UserData.DAL.Device device = new UserData.DAL.Device()
                {
                    DeviceType   = type,
                    DeviceTypeId = type.Id
                };

                var insertedDevice = DeviceDAO.Add(device);

                return(new DeviceModel()
                {
                    Id = insertedDevice.Id,
                    DeviceType = insertedDevice.DeviceType.Type
                });
            }
            catch (Exception ex)
            {
                throw new WebFaultException <string>(ex.Message, HttpStatusCode.MethodNotAllowed);
            }
        }
Пример #10
0
        public void GivenDeviceTypeShouldReturnAllDeviceOfType()
        {
            var data = new List <Device>
            {
                new Device()
                {
                    Id = 0, Name = "A", DeviceTypeId = 0
                },
                new Device()
                {
                    Id = 1, Name = "B", DeviceTypeId = 1
                },
                new Device()
                {
                    Id = 2, Name = "C", DeviceTypeId = 0
                }
            }.AsQueryable();

            var mockContext = new Mock <UserDataContext>();
            var mockSet     = SetupDbSet(data);

            mockContext.Setup(c => c.Device).Returns(mockSet.Object);

            var dao     = new DeviceDAO(mockContext.Object);
            var results = dao.GetAllDevicesOfType(new DeviceType()
            {
                Id = 0
            });

            Assert.AreEqual(2, results.Count);
            Assert.AreEqual("A", results[0].Name);
            Assert.AreEqual("C", results[1].Name);
        }
        /// <summary>
        /// Delete a mobile device
        /// </summary>
        /// <param name="registrationId">RegistrationId</param>
        /// <returns>True if the device was successfully deleted</returns>
        public async Task <bool> DeleteMobileDevice(string registrationId)
        {
            DeviceDAO device = await _repoDevices.GetItemAsync(d => (string)d.Custom["RegistrationId"] == registrationId);

            if (device != null)
            {
                return(await _repoDevices.DeleteItemAsync(device.Id));
            }
            return(true);
        }
        /// <summary>
        /// Create or update a device
        /// </summary>
        /// <param name="deviceTwinObj">DeviceTwinModel</param>
        /// <returns>DeviceModel</returns>
        public async Task <DeviceModel> CreateOrUpdateDevice(DeviceTwinModel deviceTwinObj)
        {
            if (deviceTwinObj.DeviceId == Guid.Empty)
            {
                throw new Exception($"No device found that matches DeviceId: {deviceTwinObj.DeviceId}");
            }

            DeviceDAO deviceDAO = await _repoDevices.GetItemAsync(deviceTwinObj.DeviceId);

            //Create
            if (deviceDAO == null)
            {
                return(await CreateDevice(deviceTwinObj));
            }

            //Update
            deviceDAO.IoTDevice = true;
            if (deviceTwinObj.Properties?.Desired != null)
            {
                deviceDAO.Desired = deviceTwinObj.Properties.Desired;
            }
            if (deviceTwinObj.Properties?.Reported != null)
            {
                deviceDAO.Reported = deviceTwinObj.Properties.Reported;
            }
            if (deviceTwinObj.Tags != null)
            {
                deviceDAO.DeviceType  = deviceTwinObj.Tags.DeviceType;
                deviceDAO.Enabled     = deviceTwinObj.Tags.Enabled;
                deviceDAO.Custom      = deviceTwinObj.Tags.Custom;
                deviceDAO.Name        = deviceTwinObj.Tags.Name;
                deviceDAO.Location1   = deviceTwinObj.Tags.Location1;
                deviceDAO.Location2   = deviceTwinObj.Tags.Location2;
                deviceDAO.Location3   = deviceTwinObj.Tags.Location3;
                deviceDAO.SSID        = deviceTwinObj.Tags.SSID;
                deviceDAO.Sensor      = deviceTwinObj.Tags.Sensor;
                deviceDAO.Geolocation = _mapper.Map <GeolocationDAOObject>(deviceTwinObj.Tags.Geolocation);
            }

            try
            {
                await _repoDevices.UpdateItemAsync(deviceDAO);
            }
            catch (DocumentClientException e)
            {
                //Update concurrency issue, retrying
                if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                    return(await CreateOrUpdateDevice(deviceTwinObj));
                }
                throw e;
            }

            return(_mapper.Map <DeviceModel>(deviceDAO));
        }
        /// <summary>
        /// Get a mobile device from a user id
        /// </summary>
        /// <param name="userId">User Id</param>
        /// <returns>DeviceModel</returns>
        public async Task <DeviceModel> GetMobileDeviceFromUserId(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                throw new Exception($"UserId not found");
            }

            DeviceDAO deviceEntity = await _repoDevices.GetItemAsync(p => p.DeviceType == "Mobile" && p.Custom != null &&
                                                                     p.Custom["Email"] != null && (string)p.Custom["Email"] == userId);

            return(_mapper.Map <DeviceModel>(deviceEntity));
        }
        /// <summary>
        /// Create a device
        /// </summary>
        /// <param name="deviceTwinObj">DeviceTwinModel</param>
        /// <returns>DeviceModel</returns>
        public async Task <DeviceModel> CreateDevice(DeviceTwinModel deviceTwinObj)
        {
            //If device doesn't exist, throw exception
            DeviceDAO deviceEntity = _mapper.Map <DeviceDAO>(deviceTwinObj);

            deviceEntity.Id = await _repoDevices.CreateItemAsync(deviceEntity);

            if (_repoDevices.IsDocumentKeyNull(deviceEntity))
            {
                throw new Exception($"An error occured when creating a new device: {deviceTwinObj.DeviceId}");
            }

            return(_mapper.Map <DeviceModel>(deviceEntity));
        }
        public void AddRawMetric(string id, string date, string value)
        {
            IDictionary <string, Object> paramMap = new Dictionary <string, Object>();

            paramMap[Constants.Context.PROVIDER_URL] = ConfigurationManager.AppSettings["jmsProviderUrl"].ToString();

            IContext           jmsContext = ContextFactory.CreateContext(paramMap);
            IConnectionFactory cf         = jmsContext.LookupConnectionFactory(ConfigurationManager.AppSettings["jmsConnectionFactory"].ToString());
            IQueue             queue      = (IQueue)jmsContext.LookupDestination(ConfigurationManager.AppSettings["jmsQueue"].ToString());

            IConnection connection;

            try
            {
                if (date == null || date.Length == 0 || value == null || value.Length == 0)
                {
                    throw new Exception("Missing raw metrics parameters.");
                }

                var device = DeviceDAO.Get(int.Parse(id));

                if (device == null)
                {
                    throw new Exception("Device doesn't exist.");
                }

                connection = cf.CreateConnection();
                connection.Start();

                ISession         producerSession = connection.CreateSession(Constants.SessionMode.AUTO_ACKNOWLEDGE);
                IMessageProducer producer        = producerSession.CreateProducer(queue);

                producer.DeliveryMode = Constants.DeliveryMode.PERSISTENT;

                MetricModel model = new MetricModel()
                {
                    DeviceId = int.Parse(id), Date = date, Value = value
                };

                ITextMessage jmsMessage = producerSession.CreateTextMessage(JsonConvert.SerializeObject(model));
                producer.Send(jmsMessage);
            }
            catch (Exception ex)
            {
                throw new WebFaultException <string>(ex.Message, HttpStatusCode.MethodNotAllowed);
            }

            connection.Close();
        }
Пример #16
0
 private void SetInstance(string deviceType)
 {
     _device    = null;
     _deviceDAO = null;
     if (deviceType.CompareTo(DeviceType.HH.ToString()) == 0)
     {
         _deviceDAO = new HandheldDAO();
         _device    = new IHF.BusinessLayer.BusinessClasses.Handheld();
     }
     else
     {
         _deviceDAO = new DeviceDAO();
         _device    = new Device();
     }
 }
Пример #17
0
        /// <summary>
        /// 获取指定会议的参会人员
        /// </summary>
        /// <param name="meetingID"></param>
        /// <param name="delegates"></param>
        /// <returns></returns>
        public Status getAll(int meetingID, out List <DelegateInfo> delegates)
        {
            delegates = new List <DelegateInfo>();

            DelegateDAO delegateDao = Factory.getInstance <DelegateDAO>();

            DeviceDAO deviceDao = Factory.getInstance <DeviceDAO>();

            PersonDAO personDao = Factory.getInstance <PersonDAO>();

            Dictionary <string, object> wherelist = new Dictionary <string, object>();

            wherelist.Add("meetingID", meetingID);
            List <DelegateVO> delegateVos = delegateDao.getAll <DelegateVO>(wherelist);

            if (delegateVos == null)
            {
                return(Status.NONFOUND);
            }
            foreach (DelegateVO delegateVo in delegateVos)
            {
                //获取设备信息
                DeviceVO deviceVo = deviceDao.getOne <DeviceVO>(delegateVo.deviceID);
                //获取用户信息
                PersonVO personVo = personDao.getOne <PersonVO>(delegateVo.personID);

                if (deviceVo == null || personVo == null)
                {
                    return(Status.FAILURE);
                }

                delegates.Add(
                    new DelegateInfo
                {
                    delegateID      = delegateVo.delegateID,
                    userDepartment  = personVo.personDepartment,
                    meetingID       = meetingID,
                    userName        = personVo.personName,
                    userJob         = personVo.personJob,
                    userMeetingRole = delegateVo.personMeetingRole,
                    deviceID        = deviceVo.deviceID,
                    deviceIndex     = deviceVo.deviceIndex
                });
            }

            return(Status.SUCCESS);
        }
        /// <summary>
        /// Create or update a mobile device
        /// </summary>
        /// <param name="deviceMobile">DeviceMobileModel</param>
        /// <returns>DeviceMobileModel</returns>
        public async Task <DeviceMobileModel> CreateOrUpdateDevice(DeviceMobileModel deviceMobile)
        {
            if (deviceMobile.DeviceId == Guid.Empty && string.IsNullOrEmpty(deviceMobile.MobileId))
            {
                throw new Exception($"Invalid DeviceId and/or MobileId");
            }

            DeviceDAO deviceDAO = null;

            if (deviceMobile.DeviceId != Guid.Empty)
            {
                deviceDAO = await _repoDevices.GetItemAsync(deviceMobile.DeviceId);
            }
            else if (!string.IsNullOrEmpty(deviceMobile.MobileId))
            {
                deviceDAO = await _repoDevices.GetItemAsync(
                    d => (string)d.Custom["MobileId"] == deviceMobile.MobileId);
            }


            if (deviceDAO == null)
            //Create
            {
                deviceDAO = await CreateMobileDevice(deviceMobile);
            }
            else
            //Update
            {
                deviceDAO.Custom = deviceMobile.Custom;
                try
                {
                    await _repoDevices.UpdateItemAsync(deviceDAO);
                }
                catch (DocumentClientException e)
                {
                    //Update concurrency issue, retrying
                    if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                    {
                        return(await CreateOrUpdateDevice(deviceMobile));
                    }
                    throw e;
                }
            }

            return(_mapper.Map <DeviceMobileModel>(deviceDAO));
        }
Пример #19
0
        public void GivenIdShouldRemoveFromDb()
        {
            Device d = new Device()
            {
                Id = 0, Name = "A"
            };

            var mockContext = new Mock <UserDataContext>();

            mockContext.Setup(c => c.Device.Find(0)).Returns(d);

            var dao = new DeviceDAO(mockContext.Object);

            dao.Remove(0);

            mockContext.Verify(m => m.Device.Remove(It.IsAny <Device>()), Times.Once());
        }
Пример #20
0
        public void GivenObjectWithInvalidTypeIdShouldThrowException()
        {
            var data = new List <Device>().AsQueryable();

            var mockContext = new Mock <UserDataContext>();
            var mockSet     = SetupDbSet(data);

            mockContext.Setup(c => c.Device).Returns(mockSet.Object);
            mockContext.Setup(c => c.DeviceType.Find(0)).Returns((DeviceType)null);

            var dao = new DeviceDAO(mockContext.Object);

            var ex = Assert.Throws <Exception>(() => dao.Add(new Device()
            {
                DeviceTypeId = 0
            }));

            Assert.AreEqual("Device.TypeId doesn't exist.", ex.Message);
        }
Пример #21
0
        public void GivenIdShouldReturnObject()
        {
            Device d1 = new Device()
            {
                Id = 0, Name = "A"
            };
            Device d2 = new Device()
            {
                Id = 1, Name = "B"
            };

            var mockContext = new Mock <UserDataContext>();

            mockContext.Setup(c => c.Device.Find(0)).Returns(d1);

            var dao    = new DeviceDAO(mockContext.Object);
            var result = dao.Get(0);

            Assert.AreEqual(d1, result);
        }
Пример #22
0
        public void LinkDeviceToUser(string userId, string deviceId)
        {
            try
            {
                if (userId == null || userId.Length == 0 || deviceId.Length == 0)
                {
                    throw new WebFaultException <string>("LinkDeviceToUser missing parameter.", HttpStatusCode.BadRequest);
                }

                DeviceDAO.AddDeviceOwner(int.Parse(deviceId), userId);
            }
            catch (WebFaultException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new WebFaultException <string>(ex.Message, HttpStatusCode.InternalServerError);
            }
        }
Пример #23
0
        public void GivenValidObjectShouldUpdateInDb()
        {
            Device d = new Device()
            {
                Id = 0, Name = "A"
            };
            Device dUpd = new Device()
            {
                Id = 0, Name = "A", UserId = 0
            };

            var mockContext = new Mock <UserDataContext>();

            mockContext.Setup(c => c.Device.Find(0)).Returns(d);

            var dao        = new DeviceDAO(mockContext.Object);
            var updatedObj = dao.Update(dUpd);

            Assert.AreEqual("A", updatedObj.Name);
            Assert.AreEqual(0, updatedObj.UserId);
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
        }
Пример #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="deviceID"></param>
        /// <param name="available"></param>
        /// <returns></returns>
        public Status UpdateDeviceAvailable(int deviceID, int available)
        {
            try
            {
                //数据库操作
                DeviceDAO deviceDao = Factory.getInstance <DeviceDAO>();

                Dictionary <string, object> setlist = new Dictionary <string, object>();

                setlist.Add("deviceState", available);
                if (deviceDao.update(setlist, deviceID) < 0)
                {
                    return(Status.FAILURE);
                }

                return(Status.SUCCESS);
            }
            catch (Exception e)
            {
                Log.ErrorInfo(e.StackTrace);
                return(Status.SERVER_EXCEPTION);
            }
        }
Пример #25
0
        public void ShouldReturnAllDevices()
        {
            var data = new List <Device>
            {
                new Device()
                {
                    Name = "A"
                },
                new Device()
                {
                    Name = "B"
                }
            }.AsQueryable();

            var mockContext = new Mock <UserDataContext>();

            mockContext.Setup(c => c.Device).Returns(SetupDbSet(data).Object);

            var dao     = new DeviceDAO(mockContext.Object);
            var results = dao.All();

            Assert.AreEqual(2, results.Count);
        }
Пример #26
0
 public List <DeviceModel> GetNoLinkedDevices()
 {
     try
     {
         var devices = DeviceDAO.GetNoLinkedDevices();
         if (devices != null)
         {
             List <DeviceModel> rDevices = new List <DeviceModel>();
             foreach (var d in devices)
             {
                 rDevices.Add(new DeviceModel()
                 {
                     Id = d.Id, Name = d.Name, DeviceType = d.DeviceType.Type
                 });
             }
             return(rDevices);
         }
         return(null);
     }
     catch (Exception)
     {
         throw;
     }
 }
Пример #27
0
        public List <DeviceModel> GetDevices()
        {
            try
            {
                var devices = DeviceDAO.All();
                var results = new List <DeviceModel>();

                foreach (var device in devices)
                {
                    results.Add(new DeviceModel()
                    {
                        Id         = device.Id,
                        Name       = device.Name,
                        DeviceType = device.DeviceType.Type
                    });
                }

                return(results);
            }
            catch (Exception ex)
            {
                throw new WebFaultException <string>(ex.Message, HttpStatusCode.InternalServerError);
            }
        }
Пример #28
0
        public Status getAllForDelegate(DateTime start, DateTime end, out List <DeviceForDelegate> list)
        {
            list = new List <DeviceForDelegate>();

            MeetingDAO  meetingDao  = Factory.getInstance <MeetingDAO>();
            DelegateDAO delegateDao = Factory.getInstance <DelegateDAO>();
            DeviceDAO   deviceDao   = Factory.getInstance <DeviceDAO>();
            Dictionary <string, object> wherelist = new Dictionary <string, object>();

            List <MeetingVO> meetingVolist = meetingDao.getAll <MeetingVO>();

            int dx;

            if (ConfigurationManager.AppSettings["DeviceOccupyTimeInterval"] == null)
            {
                dx = 30;
            }
            else
            {
                dx = Int32.Parse(ConfigurationManager.AppSettings["DeviceOccupyTimeInterval"]);
                if (dx < 1)
                {
                    dx = 30;
                }
            }

            var tempMeetings = meetingVolist
                               .Where( //包括与本次会议在几乎同一时间开启或结束的会议
                m => (Math.Abs((m.meetingToStartTime - start).TotalMinutes) < dx ||
                      Math.Abs((m.meetingToStartTime - end).TotalMinutes) < dx ||
                      Math.Abs((m.meetingStartedTime - start).TotalMinutes) < dx ||
                      Math.Abs((m.meetingStartedTime - end).TotalMinutes) < dx)
                )     //包括已开或正在开启的会议
                               .Where(m => m.meetingStatus == 1 || m.meetingStatus == 2);

            wherelist.Clear();
            //只允许未冻结的设备作为参会设备
            wherelist.Add("deviceState", 0);
            var deviceVolist = deviceDao.getAll <DeviceVO>(wherelist);

            if (tempMeetings != null && deviceVolist != null)
            {
                var meetinglist = tempMeetings.ToList();
                foreach (var meetingvo in meetinglist)
                {
                    wherelist.Clear();
                    wherelist.Add("meetingID", meetingvo.meetingID);
                    var delegateVolist = delegateDao.getAll <DelegateVO>(wherelist);

                    if (delegateVolist != null)
                    {
                        foreach (var delegateVo in delegateVolist)
                        {
                            for (int i = 0; i < deviceVolist.Count; i++)
                            {
                                if (deviceVolist[i].deviceID == delegateVo.deviceID)
                                {
                                    //去除已使用的设备
                                    deviceVolist.RemoveAt(i);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (deviceVolist != null)
            {
                foreach (var devicevo in deviceVolist)
                {
                    list.Add(new DeviceForDelegate
                    {
                        deviceID    = devicevo.deviceID,
                        deviceIndex = devicevo.deviceIndex
                    });
                }
            }

            return(Status.SUCCESS);
        }
        /// <summary>
        /// Update the geolocation of a mobile device
        /// </summary>
        /// <param name="geolocation">Geolocation of the device</param>
        /// <param name="userId">UserId</param>
        /// <returns>DeviceGeolocationUpdateResultModel</returns>
        public async Task <DeviceGeolocationUpdateResultModel> UpdateMobileGeolocation(Geolocation geolocation, string userId)
        {
            if (geolocation == null)
            {
                throw new Exception($"No Geolocation found: {geolocation}");
            }
            if (string.IsNullOrEmpty(userId))
            {
                throw new Exception($"UserId not found");
            }

            DeviceDAO deviceDAO = await _repoDevices.GetItemAsync(p => p.DeviceType == "Mobile" && p.Custom != null &&
                                                                  p.Custom["Email"] != null && (string)p.Custom["Email"] == userId);

            if (deviceDAO != null)
            {
                if (deviceDAO.Geolocation != null)
                {
                    if (geolocation.Latitude == deviceDAO.Geolocation.Latitude &&
                        geolocation.Longitude == deviceDAO.Geolocation.Longitude)
                    {
                        return new DeviceGeolocationUpdateResultModel()
                               {
                                   Success = true
                               }
                    }
                    ;
                }

                string etag = deviceDAO.ETag;
                deviceDAO.LastAccessTime = DateTime.UtcNow;
                deviceDAO.Geolocation    = _mapper.Map <GeolocationDAOObject>(geolocation);

                try
                {
                    var result = await _repoDevices.UpdateItemAsync(deviceDAO);

                    if (result)
                    {
                        return(new DeviceGeolocationUpdateResultModel()
                        {
                            Success = true,
                            Device = deviceDAO.Enabled ? _mapper.Map <DeviceModel>(deviceDAO) : null
                        });
                    }
                    throw new Exception($"Error while updating device geolocation: {userId}.");
                }
                catch (DocumentClientException e)
                {
                    //Update concurrency issue, retrying
                    if (e.StatusCode == HttpStatusCode.PreconditionFailed)
                    {
                        return(await UpdateMobileGeolocation(geolocation, userId));
                    }
                    throw e;
                }
            }
            return(new DeviceGeolocationUpdateResultModel()
            {
                Success = false
            });
        }
        /// <summary>
        /// Get a device from a device id
        /// </summary>
        /// <param name="deviceId">Device Id</param>
        /// <returns>DeviceModel</returns>
        public async Task <DeviceModel> GetDevice(Guid deviceId)
        {
            DeviceDAO deviceEntity = await _repoDevices.GetItemAsync(deviceId);

            return(_mapper.Map <DeviceModel>(deviceEntity));
        }