/// <inheritdoc /> public async Task CreateDevice(UserDevice device) { GuardDevice(device); _dbContext.UserDevices.Add(device); await _dbContext.SaveChangesAsync(); var user = device.User; if (user == null) { user = await _dbContext.Users.SingleOrDefaultAsync(x => x.Id == device.UserId); } var @event = new DeviceCreatedEvent(DeviceInfo.FromUserDevice(device), SingleUserInfo.FromUser(user)); await _eventService.Publish(@event); }
public async Task <IActionResult> CreateDevice([FromBody] RegisterDeviceRequest request) { var user = await UserManager.GetUserAsync(User); if (user == null) { return(NotFound()); } var device = await DbContext.UserDevices.SingleOrDefaultAsync(x => x.UserId == user.Id && x.DeviceId == request.DeviceId); if (device is not null) { ModelState.AddModelError(nameof(request.DeviceId), $"A device with id {request.DeviceId} already exists."); return(BadRequest(new ValidationProblemDetails(ModelState))); } var shouldEnablePushNotifications = !string.IsNullOrWhiteSpace(request.PnsHandle); if (shouldEnablePushNotifications) { try { await PushNotificationService.Register(request.DeviceId, request.PnsHandle, request.Platform, user.Id, request.Tags?.ToArray()); } catch (Exception exception) { Logger.LogError("An exception occurred when connection to Azure Notification Hubs. Exception is '{Exception}'. Inner Exception is '{InnerException}'.", exception.Message, exception.InnerException?.Message ?? "N/A"); throw; } } device = new UserDevice { DeviceId = request.DeviceId, Name = request.Name, Platform = request.Platform, IsPushNotificationsEnabled = shouldEnablePushNotifications, UserId = user.Id, DateCreated = DateTimeOffset.UtcNow, Model = request.Model, OsVersion = request.OsVersion, Data = request.Data }; DbContext.UserDevices.Add(device); await DbContext.SaveChangesAsync(); var response = DeviceInfo.FromUserDevice(device); var @event = new DeviceCreatedEvent(response, SingleUserInfo.FromUser(user)); await EventService.Publish(@event); return(CreatedAtAction(nameof(GetDeviceById), new { deviceId = device.DeviceId }, response)); }