public void AddDuplicateName()
        {
            var repo = new DeviceRepository();
            //add old one
            var oldDevice = DeviceFactory.CreateDevice("OldCamera", "old camera");

            repo.Add(oldDevice);
            //make a new one with duplicate name should replace the old one
            var newDevice = DeviceFactory.CreateDevice("NewCamera", "old camera");

            Assert.Equal(newDevice, repo.Add(newDevice));
        }
Exemple #2
0
        public async Task <bool> InitDevice(Device newSlave)
        {
            if (newSlave != null)
            {
                var success = Devices.TryAdd(newSlave.MAC, new HouseSlaveDeviceClient {
                    Slave = newSlave, ConnectionId = Context.ConnectionId
                });
                if (success)
                {
                    _logger.Info($"Device with MAC: {newSlave.MAC}  has been added to current list");

                    var containsEntity =
                        await DeviceRepository.ContainsEntityWithMAC(newSlave.MAC, CancellationToken.None);

                    if (!containsEntity)
                    {
                        await DeviceRepository.Add(newSlave, Token);

                        _logger.Info($"Device with MAC: {newSlave.MAC} has been added to repository.");
                    }
                    else
                    {
                        await DeviceRepository.Update(newSlave, Token);

                        _logger.Info($"Device with MAC: {newSlave.MAC} has been updated.");
                    }
                }
            }

            return(false);
        }
        public void Add()
        {
            var repo   = new DeviceRepository();
            var device = DeviceFactory.CreateDevice("OldCamera", "old camera");

            Assert.Equal(device, repo.Add(device));
        }
Exemple #4
0
 public void Setup()
 {
     DataContext.Instance.Devices.Clear();
     _deviceRepo = new DeviceRepository();
     _deviceRepo.Add(new ExampleDevice {
         Id = 0, Name = "Light Bulb", Enabled = true
     });
     _deviceRepo.Add(new ExampleDevice {
         Id = 1, Name = "Wall Socket", Enabled = false
     });
     _deviceRepo.Add(new ExampleDevice {
         Id = 2, Name = "Light Bulb", Enabled = false
     });
     _deviceRepo.Add(new ExampleDevice {
         Id = 3, Name = "Motion Detector", Enabled = true
     });
 }
Exemple #5
0
 public IHttpActionResult Post(Device item)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest(ModelState));
     }
     _DeviceRepository.Add(item);
     return(Ok(item));
 }
        public void GetAll()
        {
            var repo = new DeviceRepository();
            //add two
            var oldDevice = DeviceFactory.CreateDevice("OldCamera", "old camera");
            var newDevice = DeviceFactory.CreateDevice("NewCamera", "new camera");

            repo.Add(oldDevice);
            repo.Add(newDevice);

            List <Device> devices = new List <Device>
            {
                oldDevice,
                newDevice
            };

            Assert.Equal(devices, repo.GetAll().ToList());
        }
        public RedirectToActionResult AddDevice(Device device)
        {
            Device newDevice = new Device {
                UserId = userManager.GetUserId(HttpContext.User), Nickname = device.Nickname, Longitude = device.Longitude, Latitude = device.Latitude
            };

            _deviceRepository.Add(newDevice);
            return(RedirectToAction("mydevices", "device"));
        }
Exemple #8
0
        public void AddTest()
        {
            Assert.AreEqual(true, _deviceRepo.Add(new ExampleDevice {
                Id = 4, Name = "Motion Detector", Enabled = false
            }));
            Assert.AreEqual("Motion Detector", _deviceRepo.Get(4).Name);
            var allDevices = (List <IDevice>)_deviceRepo.Get();

            Assert.AreEqual(5, allDevices.Count);
        }
        public void GetNotExistedDevice()
        {
            var repo = new DeviceRepository();
            //add one
            var oldDevice = DeviceFactory.CreateDevice("OldCamera", "old camera");

            repo.Add(oldDevice);

            Assert.Null(repo.Get("somethingNotExisted"));
        }
        public void Get(string type, string name)
        {
            //add one first
            var repo   = new DeviceRepository();
            var device = DeviceFactory.CreateDevice(type, name);

            repo.Add(device);

            //get it
            Assert.Equal(device, repo.Get(name));
        }
        public async Task <IHttpActionResult> PostDevice(Device device)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await deviceRepository.Add(device);

            return(CreatedAtRoute("DefaultApi", new { id = device.Id }, device));
        }
        public void SendToDevice()
        {
            connectDone.Reset();
            sendDone.Reset();
            receiveDone.Reset();

            Socket client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            client.ReceiveTimeout = 20000;
            client.SendTimeout    = 20000;

            try
            {
                IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
                client.BeginConnect(endPoint, ConnectCallback, client);
                connectDone.WaitOne();

                if (!client.Connected)
                {
                    return;
                }

                Send(client, "ping");
                sendDone.WaitOne();

                Receive(client);
                receiveDone.WaitOne();

                // Add the new device in repo
                if (!string.IsNullOrEmpty(response))
                {
                    DeviceRepository repository = new DeviceRepository();

                    Device device = new Device
                    {
                        Name = response
                    };

                    repository.Add(device);

                    OnDevicesChanged();
                }

                client.Shutdown(SocketShutdown.Both);
            }
            catch { }
            finally
            {
                client.Close();
                client.Dispose();
            }
        }
        public void Remove(string type, string name)
        {
            var repo = new DeviceRepository();
            //add one
            var device = DeviceFactory
                         .CreateDevice(type, name);

            repo.Add(device);

            //remove
            repo.Remove(name);

            Assert.Empty(repo.GetAll());
        }
Exemple #14
0
        public async Task <JsonResult> AddOrUpdate([FromBody] Device input)
        {
            await CheckPermission();

            using (var rep = new DeviceRepository(_logger))
            {
                if (input.Id == 0)
                {
                    return(Json(await rep.Add(input)));
                }

                return(Json(await rep.Update(input)));
            }
        }
        public void RemoveNotExisted()
        {
            var repo = new DeviceRepository();
            //add one
            var device = DeviceFactory
                         .CreateDevice("OldCamera", "old camera");

            repo.Add(device);

            //remove
            repo.Remove("nameNotExisted");

            Assert.Single(repo.GetAll());
        }
        public JObject PostDevice([FromBody] JObject body, string accessKey = null)
        {
            if (!AccessKeyHelper.CanAccessDevices(accessKey))
            {
                Response.StatusCode = StatusCodes.Status401Unauthorized;
                return(null);
            }

            IDevice deviceObj = new Device(body);

            DeviceRepository.Add(deviceObj);

            deviceObj = DeviceRepository.Get(deviceObj.Id);
            return(deviceObj.ToJObject());
        }
Exemple #17
0
        public async Task <bool> AddDevice(DTODevice device)
        {
            Device mapDevice = _mapper.Map <Device>(device);

            _deviceRepository.Add(mapDevice);
            bool success = true;

            try
            {
                await _deviceRepository.SaveChanges();
            }
            catch
            {
                success = false;
            }

            return(success);
        }
 private async void Btnadddevice_Click(object sender, RoutedEventArgs e)
 {
     if (txtamval.Text != "" && txtmodel.Text != "" && txtserial.Text != "")
     {
         if (await _device.Add(new Device()
         {
             AmvalNumber = txtamval.Text,
             Model = txtmodel.Text,
             Serial = txtserial.Text
         }))
         {
             MessageBox.Show("با موفقیت درج شد ");
             this.Close();
         }
     }
     else
     {
         MessageBox.Show("همه فیلد ها باید مقدار داشته باشد");
     }
 }
        public ActionResult Create(Device entry)
        {
            bool hasPermissions = sectionRpstry.GetPermission(sectionName, loggedUser.UserId, canCreate);

            if (hasPermissions)
            {
                try
                {
                    entry.Latitude  = Convert.ToDouble(Request["googleMapLat"]);
                    entry.Longitude = Convert.ToDouble(Request["googleMapLong"]);
                    rpstry.Add(entry);
                    rpstry.Save();
                    var customerServicesArray = !string.IsNullOrEmpty(Request["Device_Groups"]) ? Request["Device_Groups"].ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries) : new string[0];
                    //rpstry.ManageGroups(entry, customerServicesArray);
                    return(RedirectToAction("Index", new { thisid = entry.id }));
                }
                catch (Exception e)
                {
                    var resultsToSearchFrom = rpstryService.GetAll();
                    ViewBag.LoggedUser = loggedUser;
                    var currentRoles = Roles.GetRolesForUser(loggedUser.UserName);
                    if (!currentRoles.Contains(ConfigurationManager.AppSettings["SuperAdminRoleName"]) && !currentRoles.Contains(ConfigurationManager.AppSettings["AdminRoleName"]))
                    {
                        resultsToSearchFrom = loggedUser.customerId != null?db.CustomerServices.Where(d => d.customerId == loggedUser.customerId).Select(d => d.Service).AsQueryable() : new List <Service>().AsQueryable();
                    }
                    else
                    {
                        ViewBag.Customers = new SelectList(rpstryCustomer.GetAll(), "id", "fullName");
                    }
                    ViewBag.Services = new SelectList(resultsToSearchFrom, "id", "title");
                    var resultsToGroupFrom = db.DeviceGroups.AsQueryable();
                    ViewBag.DeviceGroups = new SelectList(resultsToGroupFrom, "id", "title");
                    ModelState.AddModelError("", "");
                    return(View("details", entry));
                }
            }
            else
            {
                return(View("Error", "You do not have Orders to access this section."));
            }
        }
        public DeviceMutation(DeviceRepository deviceRepository)
        {
            Name = "Mutation";

            FieldAsync <DeviceType>(
                "createDevice",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <DeviceInputType> > {
                Name = "device"
            }
                    ),
                resolve: async context =>
            {
                var device = context.GetArgument <Data.Device>("device");
                device     = deviceRepository.Add(device);
                await deviceRepository.SaveChangesAsync();
                return(device);
            });

            FieldAsync <DeviceType>(
                "updateDevice",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> >
            {
                Name = "id", Description = "id of the device"
            },
                    new QueryArgument <NonNullGraphType <DeviceInputType> > {
                Name = "device"
            }
                    ),
                resolve: async context =>
            {
                var device = context.GetArgument <Data.Device>("device");
                device.Id  = context.GetArgument <int>("id");
                device     = deviceRepository.Update(device);
                await deviceRepository.SaveChangesAsync();
                return(device);
            });
        }
Exemple #21
0
        public DeviceViewModel DeviceAdd(DeviceViewModel dvm)
        {
            #region 验证用户是否有权限添加设备
            bool bRet = new UserService().IsAuthProject(dvm.Account, dvm.Token, dvm.ProjectId.Value, 3);
            if (!bRet)
            {
                dvm.Success = false;
                dvm.Message = "用户没有权限进行添加设备";
                return(dvm);
            }
            #endregion

            #region 验证节点是否为叶子节点
            ProjectService ms = new ProjectService();
            bRet = ms.IsLeafProject(dvm.ProjectId.Value, dvm.Token);
            if (!bRet)
            {
                dvm.Success = false;
                dvm.Message = "非叶子节点不能添加设备";
                return(dvm);
            }
            #endregion

            #region 验证在此节点下是否有此设备(同一个叶子节点下不允许设备重名)
            DeviceModel dm = _dr.Find(dvm.Token, dvm.DeviceName, dvm.ProjectId.Value);
            if (dm != null)
            {
                dvm.Success = false;
                dvm.Message = "此设备名称已存在";
                return(dvm);
            }

            //验证设备编号是否重复(设备编号全局)
            dm = _dr.Find(dvm.DeviceSn, dvm.Token);
            if (dm != null)
            {
                dvm.Success = false;
                dvm.Message = "此设备已存在系统中";
                return(dvm);
            }
            #endregion
            //获取项目的顶级编号
            int pid = new ProjectService().GetRootId(dvm.ProjectId.Value);
            #region 添加设备
            try
            {
                DeviceModel dmm = new DeviceModel();
                dmm.ProjectId         = dvm.ProjectId;
                dmm.DeviceName        = dvm.DeviceName;
                dmm.DeviceSn          = Guid.NewGuid().ToString("N");
                dmm.DeviceNo          = dvm.DeviceNo;
                dmm.TypeId            = dvm.TypeId;
                dmm.Token             = dvm.Token;
                dmm.ProductTime       = DateTime.Now;
                dmm.UseTime           = DateTime.Now;
                dmm.PId               = pid;
                dmm.DeviceDescription = dvm.DeviceDescription;
                _dr.Add(dmm);
                dvm.Success = true;
                dvm.Message = "添加设备成功";
            }
            catch (Exception ex)
            {
                dvm.Success = false;
                dvm.Message = "添加设备失败 " + ex.Message;
                return(dvm);
            }
            #endregion
            return(dvm);
        }
Exemple #22
0
        public void Add()
        {
            User user = new User
            {
                FirstName   = "Test",
                LastName    = "User",
                Username    = "******",
                DateCreated = DateTime.UtcNow,
                Id          = Guid.Parse("270e02a4-baf6-11e9-a2a3-2a2ae2dbcce4")
            };

            Devices retrieveDevice = new Devices
            {
                Id           = retrieveId,
                Name         = "TestRetrieveDevice",
                Manufacturer = "RetrieveDevice",
                Model        = "#1-InitialCreation",
                User         = user
            };
            Devices updateDevice = new Devices
            {
                Id           = updateId,
                Name         = "TestUpdateDevice",
                Manufacturer = "UpdateMethod",
                Model        = "#1-InitialCreation",
                User         = user
            };
            Devices deleteDevice = new Devices
            {
                Id           = deleteId,
                Name         = "TestDeleteDevice",
                Manufacturer = "DeleteMethod",
                Model        = "#1-InitialCreation",
                User         = user
            };
            List <Tasks> tasksList = new List <Tasks>();

            tasksList.Add(new Tasks
            {
                Id       = taskId,
                Status   = Enums.Status.Waiting,
                TaskType = Enums.TaskType.GetDeviceInfo
            });
            Devices deviceWithTask = new Devices
            {
                Id           = deviceWithTaskId,
                Name         = "TestDeviceWithTask",
                Manufacturer = "AddMetehod",
                Model        = "#1-InitialCreation",
                Tasks        = tasksList,
                User         = user
            };

            UserRepository.Add(user, "test");
            DeviceRepository.Add(updateDevice);
            DeviceRepository.Add(retrieveDevice);
            DeviceRepository.Add(deleteDevice);
            DeviceRepository.Add(deviceWithTask);

            int changes = DeviceRepository.SaveChanges();

            Assert.Greater(changes, 0);
        }