/// <summary> /// Create or update Device /// </summary> /// <param name="input"></param> //[AbpAuthorize(PermissionNames.GlobalConfiguration_Users_Create)] //[AbpAuthorize(PermissionNames.GlobalConfiguration_Users_Update)] public void CreateOrUpdateDevice(NewDeviceDto input) { if (input.Id == 0) { var newDevice = new Device { Name = input.DeviceName, Description = input.Description }; var propertyValuesList = new List <DevicePropertyValue>(); var maxDeviceTypeId = input.DeviceTypes.Max(x => x.Id); foreach (var deviceType in input.DeviceTypes) { foreach (var propertyValue in deviceType.PropValues) { propertyValuesList.Add(new DevicePropertyValue { Value = propertyValue.Value, DeviceTypePropertyId = _deviceTypePropertyRepository.FirstOrDefault(x => x.DeviceTypeId == deviceType.Id && x.Name == propertyValue.PropName).Id, DeviceId = newDevice.Id }); } } newDevice.DeviceTypeValues = propertyValuesList; newDevice.DeviceTypeId = maxDeviceTypeId; _deviceRepository.Insert(newDevice); return; } var foundDevice = _deviceRepository.GetAll().Include(x => x.DeviceTypeValues) .First(x => x.Id == input.Id); foundDevice.Name = input.DeviceName; foundDevice.Description = input.Description; foreach (var deviceType in input.DeviceTypes) { foreach (var propertyValue in deviceType.PropValues) { var propertyValues = _devicePropertyValueRepository.GetAll() .Include(x => x.Device) .Include(x => x.DeviceTypeProperty); var foundValue = propertyValues .First(x => x.DeviceId == foundDevice.Id && x.DeviceTypeProperty.Name == propertyValue.PropName); foundValue.Value = propertyValue.Value; } } }
public async Task <IActionResult> PostNew([FromBody] NewDeviceDto newDeviceDto) { _logger.LogDebug("PostNewDevice"); try { using (var context = new DynamoDBContext(_dynamoDb)) { var now = DateTime.UtcNow; // First create user if it doesn't exist var user = await context.LoadAsync <DbUser>(newDeviceDto.User); if (user == null) { user = new DbUser { Id = newDeviceDto.User, RegisterDate = now, Email = "", Name = "" }; await context.SaveAsync(user); } // Try to load device var existingDevice = await context.LoadAsync <DbDevice>(newDeviceDto.Id); if (existingDevice == null) { // Create new device var newDevice = new DbDevice { Id = newDeviceDto.Id, User = newDeviceDto.User, Description = newDeviceDto.Description, Enabled = newDeviceDto.Enabled, RegisterDate = now, UpdateDate = now, }; await context.SaveAsync(newDevice); return(Ok(new { result = "ok", message = "Created device.", device = newDevice })); } else { // Update device existingDevice.Enabled = newDeviceDto.Enabled; existingDevice.UpdateDate = now; existingDevice.Description = newDeviceDto.Description; await context.SaveAsync(existingDevice); return(Ok(new { result = "ok", message = "Updated device.", device = existingDevice })); } } } catch (Exception ex) { _logger.LogError(ex, ex.Message); throw; } }