/* * Add / Update the elements */ public async Task <AddResponseModel> AddProductAsync(List <DeviceModel> Devices) { //perform preprocessing on the input list var DeviceObjList = _deviceServiceHelper.PreProcessList(Devices); if (DeviceObjList != null) { try { DeviceObjList.ForEach(async Device => { var allDevices = await _deviceRepo.GetAllDevices(); var DeviceObj = allDevices.Find(i => i.Id == Device.Id); if (DeviceObj != null) { await _deviceRepo.Update(Device); } else { int a = await _deviceRepo.Add(Device); } }); return(new AddResponseModel { operationStatus = CommonConstants.operationSuccess }); } catch (Exception e) { throw new AppException(ErrorSet.DuplicateItemFoundErrorId); } } return(null); }
public async Task <Queries.DeviceModel> Handle(CreateDeviceCommand request, CancellationToken cancellationToken) { var deviceTypeInfo = await _deviceTypeRepository.FindAsync(request.DeviceTypeCode, request.ModelCode); if (deviceTypeInfo == null) { throw new DeviceDomainException("不支持的设备类型"); } if (await _deviceRepository.ExistsByEquipNumAsync(request.EquipNum)) { throw new DeviceDomainException($"编号为{request.EquipNum}的设备已存在!"); } var entity = CreateDevice(request, deviceTypeInfo); _deviceRepository.Add(entity); var result = await _deviceRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); if (!result) { return(null); } return(_mapper.Map <TerminalDevice>(entity)); }
public async Task <IActionResult> AddDevice([FromBody] DeviceSaveResource deviceAddResource) { if (!_auth.IsValidUser(User)) { return(NoContent()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var device = _mapper.Map <MdaDevice>(deviceAddResource); device.CreatedBy = User.Identity.Name; _repo.Add(device); if (await _repo.SaveAll()) { return(Ok(device)); } return(BadRequest("Failed to add device")); }
public DeviceDetailDto Add(CreateDeviceInput input) { var entity = Mapper.Map <CreateDeviceInput, Device>(input); // Validation: Each gateway can have up to 10 devices. var devicesQty = _deviceRepo.FindAll().Count(w => w.GatewayId == input.GatewayId); if (devicesQty >= 10) { return(new DeviceDetailDto { StatusCode = HttpStatusCode.BadRequest, StatusMessage = "No more than 10 peripheral devices are allowed for a gateway.", }); } using (_uowFactory.Create()) { _deviceRepo.Add(entity); } var dto = Mapper.Map <Device, DeviceDetailDto>(entity); dto.StatusCode = HttpStatusCode.Created; dto.StatusMessage = "Device created sucessfully."; return(dto); }
private void UpdateDevices(IEnumerable <IDeviceState> sentDevices, IEnumerable <Persistence.Models.Device> registeredDevices, Persistence.Models.Network network) { // go through the devices from the client and update the entries in the database foreach (var sentDevice in sentDevices) { var registeredDevice = registeredDevices.FirstOrDefault(x => x.Address == sentDevice.Address && x.Network.Address == sentDevice.NetworkState.Address); if (registeredDevice == null) { var newDevice = Persistence.Models.Device.Create( address: sentDevice.Address, isConnected: sentDevice.IsConnected, name: sentDevice.Name, network: network, location: sentDevice.Location, type: sentDevice.Type ); newDevice.Update(sentDevice); _deviceRepository.Add(newDevice); } else { _deviceRepository.Update(registeredDevice.Id, sentDevice); } } }
public async Task <IActionResult> Create([FromBody] DeviceViewModel model) { if (model == null) { return(StatusCode(400, "Invalid parameter(s).")); } Device device = new Device { DeviceId = model.DeviceId, RoomCode = model.RoomCode }; //Insert device var result = await _deviceRepository.Add(device); if (result == null) { return(StatusCode(500, "A problem occured while saving the device. Please try again!")); } return(Ok(new DeviceViewModel { DeviceId = result.DeviceId, RoomCode = result.RoomCode })); }
public IActionResult Post([FromBody] CreateDeviceViewModel deviceViewModel) { try { deviceViewModel.Name = deviceViewModel.Name.Trim(); if (_deviceRepository.List(d => d.Name.Equals(deviceViewModel.Name, StringComparison.OrdinalIgnoreCase)).Any()) { return(BadRequest("Duplicate device name!")); } var device = _mapper.Map <Device>(deviceViewModel); device.IsDeleted = false; device.IsBorrowed = false; device.CreatedOn = DateTime.Now; device.CreatedBy = User.Identity.Name; _deviceRepository.Add(device); string qrCodeFileName = $"P{device.Id}_{Guid.NewGuid().ToString().Replace("-", "")}.png"; string qrCodeContent = "{\"objectType\":\"" + AssetClassifications.DEVICE + "\",\"objectId\":" + device.Id + "}"; device.QrCodeImageUrl = QRCodeHelper.GenerateQrCodeImage(qrCodeFileName, qrCodeContent); device.QrCodeContent = qrCodeContent; _deviceRepository.Update(device); return(Ok()); } catch (Exception EX) { return(StatusCode(500, EX.Message)); } }
public Task Connect(ConnectDeviceRequest request) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (string.IsNullOrWhiteSpace(request.Username)) { throw new ArgumentException("Username is required", nameof(request)); } if (string.IsNullOrWhiteSpace(request.Password)) { throw new ArgumentException("Password is required", nameof(request)); } var fifthplayDevices = GetFifthplayDevices(request); _credentialsRepository.SaveFifthplay(request.Username, request.Password); var knownFifthplayDevices = _deviceRepository.GetAll().Where(d => d.Type == DeviceType.Fifthplay); var devicesToAdd = fifthplayDevices.Where(d => !knownFifthplayDevices.Any(k => k.Identifier == d.Identifier)); var devicesToUpdate = fifthplayDevices.Where(d => knownFifthplayDevices.Any(k => k.Identifier == d.Identifier)); var devicesToDelete = knownFifthplayDevices.Where(d => !fifthplayDevices.Any(f => f.Identifier == d.Identifier)); _deviceRepository.Add(devicesToAdd); _deviceRepository.Update(devicesToUpdate); _deviceRepository.Delete(devicesToDelete); return(Task.FromResult(true)); }
public string Add(DeviceModel deviceModel) { var newDevice = mapper.map(deviceModel); deviceRepository.Add(newDevice); return("Device created"); }
public bool Add(DeviceDto device) { if (_deviceRepository.Add(device) != 0) { return(true); } return(false); }
public DeviceService() { if (_repoReference == null) { _repoReference = new DeviceRepository(); _repoReference.Add(new ExampleDevice() { Id = 0, Name = "Philips Hue Bluetooth White and Color Ambiance Bulb", Enabled = true }); _repoReference.Add(new ExampleDevice() { Id = 1, Name = "Yeelight Smart LED Bulb", Enabled = true }); _repoReference.Add(new ExampleDevice() { Id = 2, Name = "Mi Smart Motion Sensor", Enabled = false }); _repoReference.Add(new ExampleDevice() { Id = 3, Name = "Mi Smart Motion Sensor", Enabled = false }); _repoReference.Add(new ExampleDevice() { Id = 4, Name = "Dahua's Smart Motion Detection", Enabled = true }); _repoReference.Add(new ExampleDevice() { Id = 5, Name = "Gosund Smart Socket SP1-C", Enabled = true }); _repoReference.Add(new ExampleDevice() { Id = 6, Name = "Gosund Smart Socket SP1-C", Enabled = false }); } }
public ActionResult Add(Device device) { try{ _deviceRepository.Add(device); }catch (Exception ex) { ModelState.AddModelError("", ex.Message); } return(View()); }
public IActionResult CreateDevice([FromBody] Device device) { if (device == null) { return(BadRequest()); } _deviceRepository.Add(device); return(StatusCode(201)); }
public void CreateDevice(Device device) { bool diviceExists = deviceRepository.IsDeviceExists(device.DeviceCode); if (diviceExists) { throw new InvalidOperationException("Device already exists"); } deviceRepository.Add(device); }
public IActionResult OnPost() { if (ModelState.IsValid == false) { return(Page()); } deviceInfo.STAKEHOLDER_ID = User.Identity.Name; _DeviceData.Add(deviceInfo); return(RedirectToPage("/Stakeholders/DevicesList", new { deviceInfo.Device_ID })); }
public DeviceModule(ILogger logger, IDeviceRepository deviceRepository, IDocumentSession documentSession) : base("/devices") { Get["/"] = p => { var registeredDevices = deviceRepository.GetAll(); var registeredDeviceDtos = Mapper.Map<IEnumerable<RegisteredDeviceDto>>(registeredDevices); return Response.AsJson(registeredDeviceDtos); }; Post["/"] = p => { var newDeviceRequest = this.Bind<DeviceSetupRequest>(); var registeredDevice = new RegisteredDevice(newDeviceRequest.DeviceName, newDeviceRequest.DeviceType, newDeviceRequest.IpAddress); deviceRepository.Add(registeredDevice); documentSession.SaveChanges(); documentSession.Dispose(); return HttpStatusCode.OK; }; Post["/{name}/{commandRoute}"] = p => { Response response = HttpStatusCode.NotFound; //Lookup IP address and device type from device //TODO: Implement singleton DeviceMap object to cache and return this data var device = deviceRepository.FindByName(p.name); if (device != null) { var commandRoute = String.Format("/{0}/{1}", device.Type, p.commandRoute); response = new Response(); response.Headers.Add("cmd-route", commandRoute); response.Headers.Add("cmd-ip", device.IpAddress); response.StatusCode = HttpStatusCode.OK; logger.Info(String.Format("Recievied the {0} command for the {1}. Routing it to {2}", p.commandRoute, p.device, commandRoute)); } return response; }; Delete["/{name}"] = p => { Response response = HttpStatusCode.NotFound; return response; }; }
public async Task Handle(CreateDeviceRequest request) { Device device = request.Device; if (device.Id == Guid.Empty) { device.Id = Guid.NewGuid(); } deviceRepository.Add(device); await Task.FromResult(0); }
private async Task SaveOrUpdateDevice(DeviceRequest device, IDeviceRepository deviceRepository) { if (await deviceRepository.GetById(device.Id) == null) { await deviceRepository.Add(device.Adapt <Device>()); await notificationService.SendDevicesUpdateNotify(); } else { await deviceRepository.Update(device.Adapt <Device>()); } }
public HttpResponseMessage PostDevice(Device item) { Claim objectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"); if (String.Compare(objectId.Value, ConfigurationManager.AppSettings["ClientObjectId1"], StringComparison.OrdinalIgnoreCase) == 0) { item = repository.Add(item); var response = Request.CreateResponse(HttpStatusCode.Created, item); string uri = Url.Link("DefaultApi", new { id = item.Id }); response.Headers.Location = new Uri(uri); return(response); } var res = this.ControllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized); return(res); }
public IActionResult Create(DeviceCreateViewModel model) { if (ModelState.IsValid) { Device newDevice = new Device { GUID = Guid.NewGuid().ToString(), Name = model.Name, ClassName = model.ClassName, City = model.City, PhotoPath = ProcessUploadedFile(model), }; _deviceRepository.Add(newDevice); return(RedirectToAction("Details", new { id = newDevice.Id })); } return(View()); }
public Device CreateNewDevice(string version = null) { Device device = new Device { DeviceId = Guid.NewGuid().ToString(), Version = string.IsNullOrEmpty(version) ? defaultVersion : version, Configuration = new DeviceConfiguration { IsPublished = false, Version = $"{DateTime.Now.Year}.0", SleepModeStart = DateTime.Now, PublicationDelay = TimeSpan.FromMinutes(15), ConfigurationUpdateCheckDelay = TimeSpan.FromDays(1) } }; deviceRepository.Add(device); deviceRepository.SaveChanges(); return(device); }
public async Task<IActionResult> AddDevice(DeviceDto deviceDto) { try { if (string.IsNullOrEmpty(deviceDto.AddressLabel)) return StatusCode((int)HttpStatusCode.BadRequest, "The Address field is required."); var address = await _repo.GetAddress(deviceDto.AddressLabel); if (address == null) address = await _repo.AddAddress(deviceDto.AddressLabel); else if (address.IsConfirmed == false) address.IsConfirmed = true; else return StatusCode((int)HttpStatusCode.BadRequest, "Address exists!"); var newDevice = new Database.Entities.Device() { Name = deviceDto.Name, AddressId = address.Id, Created = DateTime.Now, KindId = deviceDto.KindId, ComponentId = deviceDto.ComponentId, CategoryId = deviceDto.CategoryId, Icon = deviceDto.Icon, IsAutoUpdate = deviceDto.IsAutoUpdate, VersionId = deviceDto.VersionId, }; await _repo.Add(newDevice); return Ok(newDevice); } catch (Exception ex) { _logger.LogError(ex, ex.Message); return StatusCode((int)HttpStatusCode.InternalServerError, "Error!"); } }
public ActionResult Create(DeviceModel deviceModel) { if (!ModelState.IsValid) { ViewBag.Areas = GetAreaSelectItems(); ViewBag.Plans = GetPlanSelectItems(); ViewBag.DeviceTypes = GetDeviceTypeItems(); return(View(deviceModel)); } var device = new Device(); UpdateDeviceFromModel(device, deviceModel); deviceRepository.Add(device); if (device.TransportPlanId != null) { devicePlanRepository.Add(new DevicePlanRecord { DeviceId = device.Id, PlanId = device.TransportPlanId, startTime = DateTime.Now }); } dtuGpsRepository.Add(new DtuGPS { IMEI = deviceModel.IMEI, RecvTime = DateTime.Now, Longitude = deviceModel.longitude, Latitude = deviceModel.latitude }); auditLogRepository.Add(AuditLogBuilder.Builder() .User(HttpContext.User.Identity.Name) .Added(typeof(Device), device.Name) .With(new ChangeInfo().AddChange(() => device.Name).ToJson()) .Build()); logger.Info("User '{0}' created device '{1}'.", Identity.Name, device.Name); return(RedirectToAction("TableMode")); }
public bool AddDevice(DeviceDTO newDevice) { DeviceField invalidFields = DeviceField.None; if (newDevice.Id < 0) { invalidFields |= DeviceField.Id; } if (newDevice.Name == "") { invalidFields |= DeviceField.Name; } if (invalidFields != DeviceField.None) { throw new InvalidDeviceDataException(invalidFields); } _deviceRepo.Add(Mapper.Map(newDevice)); DevicesChange?.Invoke(); return(true); }
public IActionResult OnPost() { //if (ModelState.IsValid == false) //{ // return Page(); //} if (ModelState.IsValid == true) { //deviceInfo.STAKEHOLDER_ID = User.Identity.Name; if (deviceInfo.Device_ID > 0) { deviceInfo = _DeviceData.Update(deviceInfo); } else { deviceInfo = _DeviceData.Add(deviceInfo); } return(RedirectToPage("/Stackholders/DevicesList", new { deviceInfo.Device_ID })); } return(Page()); }
public void Connect(string key) { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } _credentialsRepository.SaveIfttt(key); if (_deviceRepository.Exists("IFTTT", DeviceCapability.WebService)) { return; } var iftttService = new Device { Identifier = Guid.NewGuid(), Name = "IFTTT", Capability = DeviceCapability.WebService, Type = DeviceType.Ifttt }; _deviceRepository.Add(iftttService); }
public void Insert(Device entity) => _deviceRepository.Add(entity);
public void AddDevice(Device device) { deviceRepository.Add(device); }
public void Handle(AddDeviceCommand command) { Device device = repository.Add(command.NodeAddress, command.Name, command.Appliance); eventServer.SendToAll(EventTypes.DeviceCreated, device); }
public void Add(Device device) { _devices.Add(device); }
public async Task <bool> AddDevice(ExampleDeviceDTO newDevice) { return(await Task.FromResult(_repoReference.Add(Mapper.Map(newDevice)))); }