public async Task <Group> CreateGroupAsync(Group model, Guid tenantId, Guid currentUserId, CancellationToken cancellationToken) { var isBuiltInGroup = model.Type != GroupType.Custom; var validationResult = _validatorLocator.Validate <CreateGroupRequestValidator>(model); if (!validationResult.IsValid) { throw new ValidationFailedException(validationResult.Errors); } // Locked groups can only be created by SuperAdmins (unless we're internally creating a // built-in group) if (model.IsLocked && !isBuiltInGroup && (currentUserId != Guid.Empty || !await _superAdminService.IsSuperAdminAsync(currentUserId))) { model.IsLocked = false; } // Replace any fields in the DTO that shouldn't be changed here model.TenantId = tenantId; var result = await CreateGroupInDbAsync(model, cancellationToken); _eventService.Publish(EventNames.GroupCreated, result); return(result); }
/// <inheritdoc /> public async Task CreateProjectLobbyStateAsync(Guid projectId) { var validationResult = _validatorLocator.Validate <ProjectIdValidator>(projectId); if (!validationResult.IsValid) { throw new ValidationFailedException(validationResult.Errors); } var state = new ProjectLobbyState { ProjectId = projectId, LobbyState = LobbyState.Normal }; await _cacheSelector[CacheConnection.General].ItemSetAsync(LobbyStateKeyResolver.GetProjectLobbyStateKey(projectId), state, _expirationTime); }
public async Task <Machine> CreateMachineAsync(Machine machine, Guid tenantId, CancellationToken cancellationToken) { var validationResult = _validatorLocator.Validate <CreateMachineRequestValidator>(machine); if (!validationResult.IsValid) { throw new ValidationFailedException(validationResult.Errors); } machine.TenantId = tenantId; machine.DateCreated = DateTime.UtcNow; machine.DateModified = DateTime.UtcNow; machine.Id = Guid.NewGuid(); machine.NormalizedLocation = machine.Location.ToUpperInvariant(); machine.MachineKey = machine.MachineKey.ToUpperInvariant(); var result = await CreateMachineInDbAsync(machine, cancellationToken); _eventService.Publish(EventNames.MachineCreated, result); await _cloudShim.CopyMachineSettings(result.Id); return(result); }
public async Task <GuestInvite> CreateGuestInviteAsync(GuestInvite model) { var validationResult = _validatorLocator.Validate <GuestInviteValidator>(model); if (!validationResult.IsValid) { throw new ValidationFailedException(validationResult.Errors); } // Get dependent resources var projectTask = GetProjectAsync(model.ProjectId); var invitedByUserTask = GetUserAsync(model.InvitedBy); await Task.WhenAll(projectTask, invitedByUserTask); var project = projectTask.Result; var invitedByUser = invitedByUserTask.Result; var accessCode = await GetGuestAccessCodeAsync(project); model.Id = model.Id == Guid.Empty ? Guid.NewGuid() : model.Id; model.CreatedDateTime = DateTime.UtcNow; model.ProjectAccessCode = accessCode; model.ProjectTenantId = project.TenantId; var result = await _guestInviteRepository.CreateItemAsync(model); // Delete all prior guest invites with the same email and ProjectId as the session just created. await _guestInviteRepository.DeleteItemsAsync(x => x.ProjectId == model.ProjectId && x.GuestEmail == model.GuestEmail && x.Id != result.Id); _eventService.Publish(EventNames.GuestInviteCreated, result); // Send an invite email to the guest var emailResult = await _emailSendingService.SendGuestInviteEmailAsync(project.Name, project.ProjectUri, model.GuestEmail, invitedByUser.FirstName); if (!emailResult.IsSuccess()) { _logger.Error($"Sending guest invite email failed. Reason={emailResult.ReasonPhrase} Error={_serializer.SerializeToString(emailResult.ErrorResponse)}"); await _guestInviteRepository.DeleteItemAsync(result.Id); } return(result); }
public async Task <InProductTrainingViewResponse> CreateInProductTrainingViewAsync(InProductTrainingViewRequest inProductTrainingViewRequest, Guid userId) { var validationResult = _validatorLocator.Validate <InProductTrainingViewRequestValidator>(inProductTrainingViewRequest); if (!validationResult.IsValid) { _logger.Error("Validation failed while attempting to create an InProductTrainingView resource."); throw new ValidationFailedException(validationResult.Errors); } var returnPayload = new InProductTrainingViewResponse(); var returnMessage = ""; var returnResultCode = ResultCode.Failed; var userApiResult = await _userApi.GetUserAsync(userId); string createdByUserName; if (userApiResult != null) { createdByUserName = !userApiResult.Payload.Username.IsNullOrEmpty() ? userApiResult.Payload.Username : userApiResult.Payload.Email; } else { createdByUserName = "******"; } try { var key = KeyResolver.InProductTrainingViews(userId, inProductTrainingViewRequest.ClientApplicationId); var dtoForTrace = _serializer.SerializeToString(inProductTrainingViewRequest); var cachedData = await _cache.SetMembersAsync <InProductTrainingViewResponse>(key); // ReSharper disable once UseNullPropagation if (cachedData != null) { var trainingOfType = cachedData?.Where(t => t.InProductTrainingSubjectId == inProductTrainingViewRequest.InProductTrainingSubjectId && t.Title == inProductTrainingViewRequest.Title && t.UserId == userId) .FirstOrDefault(); if (trainingOfType != null) { returnPayload = trainingOfType; returnMessage = CreateInProductTrainingViewReturnCode.RecordAlreadyExists.BuildResponseMessage(inProductTrainingViewRequest, userId); returnResultCode = ResultCode.RecordAlreadyExists; _logger.Info($"Record not created because it already exists in cache. {dtoForTrace}"); } } var populateCache = false; InProductTrainingViewResponse queryResult = null; if (returnResultCode != ResultCode.RecordAlreadyExists) { var returnCode = CreateInProductTrainingViewReturnCode.CreateFailed; queryResult = _dbService.CreateInProductTrainingView( inProductTrainingViewRequest.InProductTrainingSubjectId, userId, inProductTrainingViewRequest.Title, inProductTrainingViewRequest.UserTypeId, createdByUserName, ref returnCode); returnPayload = queryResult; returnMessage = returnCode.BuildResponseMessage(inProductTrainingViewRequest, userId); returnResultCode = returnCode.ToResultCode(); if (returnCode == CreateInProductTrainingViewReturnCode.CreateSucceeded) { populateCache = true; _logger.Info($"Created InProductTrainingView record. {dtoForTrace}"); } else { if (returnCode == CreateInProductTrainingViewReturnCode.RecordAlreadyExists) { populateCache = true; _logger.Info($"Record not created because it already exists in dB. {dtoForTrace}"); } else if (returnCode == CreateInProductTrainingViewReturnCode.CreateFailed) { _logger.Error($"{returnMessage} {dtoForTrace}"); } else { _logger.Warning($"{returnMessage} {dtoForTrace}"); } } } if (populateCache && queryResult != null) { var queryResultAsList = new List <InProductTrainingViewResponse> { queryResult }; if (await _cache.SetAddAsync(key, queryResultAsList) > 0 || await _cache.KeyExistsAsync(key)) { _logger.Info($"Succesfully cached an item in the set for key '{key}' {dtoForTrace}"); if (!await _cache.KeyExpireAsync(key, _expirationTime, CacheCommandOptions.None)) { _logger.Error($"Could not set cache expiration for the key '{key}' or the key does not exist. {dtoForTrace}"); } } else { _logger.Error($"Could not cache an item in the set for '{key}'. {dtoForTrace}"); } } } catch (Exception ex) { returnPayload.ResultCode = ResultCode.Failed; returnPayload.ReturnMessage = ex.ToString(); _logger.Error("Create InProductTrainingView failed due to an unknown exception", ex); } returnPayload.ReturnMessage = returnMessage; returnPayload.ResultCode = returnResultCode; return(returnPayload); }
public async Task <GuestSession> CreateGuestSessionAsync(GuestSession model, Guid principalId, Guid tenantId) { var validationResult = _validatorLocator.Validate <GuestSessionValidator>(model); if (!validationResult.IsValid) { _logger.Error("Validation failed while attempting to create a GuestSession resource."); throw new ValidationFailedException(validationResult.Errors); } Task <MicroserviceResponse <Project> > getProjectTask = null; var isTenantUnknown = tenantId == Guid.Empty; if (isTenantUnknown) { getProjectTask = _serviceToServiceProjectApi.GetProjectByIdAsync(model.ProjectId); } await EndGuestSessionsForUser(model.UserId, principalId); if (isTenantUnknown) { var projectResponse = await getProjectTask; if (!projectResponse.IsSuccess()) { throw new InvalidOperationException($"Error fetching tenantid for project {model.ProjectId}: {projectResponse.ResponseCode} - {projectResponse.ReasonPhrase} "); } model.ProjectTenantId = projectResponse.Payload.TenantId; } else { model.ProjectTenantId = tenantId; } model.Id = model.Id == Guid.Empty ? Guid.NewGuid() : model.Id; model.CreatedDateTime = DateTime.UtcNow; if (_requestHeaders.Keys.Contains("SessionIdString")) { model.SessionId = _requestHeaders["SessionIdString"].FirstOrDefault(); } else if (_requestHeaders.Keys.Contains("SessionId")) { model.SessionId = _requestHeaders["SessionId"].FirstOrDefault(); } else { throw new BadRequestException("Request headers do not contain a SessionId"); } var result = await _guestSessionRepository.CreateItemAsync(model); // Delete all prior guest sessions with the same UserId and ProjectId as the session just created. await _guestSessionRepository.DeleteItemsAsync(x => x.UserId == model.UserId && x.ProjectId == model.ProjectId && x.Id != result.Id); await _projectLobbyStateController.RecalculateProjectLobbyStateAsync(model.ProjectId); _eventService.Publish(EventNames.GuestSessionCreated, result); return(result); }