public async Task <CourseRunDetailResponse> CourseGetAsync(CourseGetRequest courseGetRequest) { var responseContent = string.Empty; try { var url = $"{courseSearchClientSettings.CourseSearchSvcSettings.ServiceEndpoint}courserundetail?CourseId={courseGetRequest.CourseId}&CourseRunId={courseGetRequest.RunId}"; logger.LogDebug($"Get course called using url : {url}"); var response = await httpClient.GetAsync(url).ConfigureAwait(false); responseContent = await(response?.Content?.ReadAsStringAsync()).ConfigureAwait(false); logger.LogDebug($"Received response {response?.StatusCode} for url : {url}"); if (!(response?.IsSuccessStatusCode).GetValueOrDefault()) { logger?.LogError($"Error status {response?.StatusCode}, Getting API data for request :'{courseGetRequest}' \nResponse : {responseContent}"); response?.EnsureSuccessStatusCode(); } return(JsonConvert.DeserializeObject <CourseRunDetailResponse>(responseContent, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })); } finally { auditService.CreateAudit(courseGetRequest, responseContent, correlationId); } }
public async Task GetAsyncTestAsync() { //arrange const string expectedResponse = "ExpectedResponse"; var httpResponse = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(expectedResponse) }; var fakeHttpRequestSender = A.Fake <IFakeHttpRequestSender>(); var fakeHttpMessageHandler = new FakeHttpMessageHandler(fakeHttpRequestSender); var httpClient = new HttpClient(fakeHttpMessageHandler); var apprenticeshipVacancyApi = new ApprenticeshipVacancyApi(fakeLogger, auditService, aVAPIServiceSettings, httpClient); A.CallTo(() => fakeHttpRequestSender.Send(A <HttpRequestMessage> .Ignored)).Returns(httpResponse); //Act var result = await apprenticeshipVacancyApi.GetAsync("fakeRequest", RequestType.Search).ConfigureAwait(false); //Asserts A.CallTo(() => auditService.CreateAudit(A <object> .Ignored, A <object> .Ignored, A <Guid?> .Ignored)).MustHaveHappenedOnceExactly(); Assert.Equal(expectedResponse, result); httpResponse.Dispose(); httpClient.Dispose(); fakeHttpMessageHandler.Dispose(); }
public async Task <IActionResult> Index(int page = 1, int pageSize = 1000) { var usersWithRoles = (from user in _userManager.Users select new { UserId = user.Id, Username = user.UserName, Email = user.Email, FirstName = user.FirstName, OtherName = user.OtherName, LastName = user.LastName, // Zone = user.Zone, PhoneNumber = user.PhoneNumber, // IsActive = user.IsActive, // IsDeleted = user.IsDeleted, FullName = $"{user.FirstName} {user.OtherName} {user.LastName}", RoleNames = (from userRole in user.Roles join role in _roleManager.Roles on userRole.RoleId equals role.Id select role.Name).ToList() }).Select(p => new UserViewModel() { UserId = p.UserId, UserName = p.Username, FirstName = p.FirstName, OtherName = p.OtherName, LastName = p.LastName, FullName = p.FullName, Email = p.Email, PhoneNumber = p.PhoneNumber, // IsActive = p.IsActive, // IsDeleted = p.IsDeleted, Role = string.Join(",", p.RoleNames) }); await _audit.CreateAudit("View Users", "Viewed list of users"); var currentUsers = await PaginatedList <UserViewModel> .CreateAsync( usersWithRoles.Where(u => u.UserName != "Owners" && u.UserName != "Admins"), page, pageSize); ViewBag.NumberOfPages = Utils.GetPages(usersWithRoles, pageSize); return(View(currentUsers)); }
public async Task <IActionResult> JoinTeam([FromBody] JoinTeam joinTeam) { var team = await _timelineContext.Teams.Where(x => x.InviteToken == joinTeam.InviteToken) .Include(x => x.TeamMembers).FirstOrDefaultAsync(); var user = await _timelineContext.Users.Where(x => x.Id == joinTeam.UserId).FirstOrDefaultAsync(); if (team == null || user == null) { return(BadRequest()); } var affiliation = new Affiliation { UserId = joinTeam.UserId, TeamId = team.Id }; team.TeamMembers.Add(affiliation); Audit audit = new Audit { Action = AuditAction.UserJoinedTeam, Log = ($"{affiliation.UserId} joined {affiliation.TeamId}"), Origin = AuditOrigin.TeamsController, Team = team, TimeStamp = DateTime.Now, User = user }; await _auditService.CreateAudit(audit); await _timelineContext.SaveChangesAsync(); Console.WriteLine($"affiliation {affiliation.UserId} : {affiliation.TeamId}"); _log.LogInformation("Creating affiliation {userId} : {TeamId}", affiliation.UserId, affiliation.TeamId); return(Ok(team)); }
public async Task GetCoursesAsyncWritesToAuditLogWhenExceptionIsThrown() { // Arrange var findACourseClient = A.Fake <IFindACourseClient>(); A.CallTo(() => findACourseClient.CourseSearchAsync(A <CourseSearchRequest> .Ignored)).Throws <Exception>(); var courseSearchService = new CourseSearchApiService(findACourseClient, defaultAuditService, defaultMapper); // Act var result = await courseSearchService.GetCoursesAsync("SomeKeyword").ConfigureAwait(false); // Assert A.CallTo(() => defaultAuditService.CreateAudit(null, null, null)).WithAnyArguments().MustHaveHappenedOnceExactly(); Assert.Empty(result); }
public async Task <BasicResponse> ChangePassword(string Username, string OldPassword, string NewPassword, string ConfirmPassword) { if (!string.IsNullOrEmpty(Username)) { var user = await _userManager.FindByNameAsync(Username); if (user != null) { if (string.IsNullOrEmpty(NewPassword)) { return(BasicResponse.FailureResult("Password change failed, New password is required!")); } if (NewPassword != ConfirmPassword) { return(BasicResponse.FailureResult("The new password and confirmation password do not match.")); } var result = await _userManager.ChangePasswordAsync(user, OldPassword, NewPassword); if (result.Succeeded) { user.LastLogin = DateTime.Now; var response = await _userManager.UpdateAsync(user); await _audit.CreateAudit("Change Password", "Password change successful"); if (_perm.IsSignedIn) { await _signInManager.SignOutAsync(); } return(BasicResponse.SuccessResult("/Home/Login")); } await _audit.CreateAudit("Change Password", "Password change failed"); return(BasicResponse.FailureResult("Password change failed!")); } await _audit.CreateAudit("Change Password", "Password change failed"); return(BasicResponse.FailureResult("Password change failed, User does not exist!")); } await _audit.CreateAudit("Change Password", "Password change failed"); return(BasicResponse.FailureResult("Password change failed, Username is required!")); }
public async Task <IEnumerable <Course> > GetCoursesAsync(string jobProfileKeywords, bool shouldThrowException = false) { if (string.IsNullOrWhiteSpace(jobProfileKeywords)) { return(await Task.FromResult <IEnumerable <Course> >(null)); } var request = BuildCourseListRequest(jobProfileKeywords); //if the the call to the courses API fails for anyreason we should log and continue as if there are no courses available. try { var apiResult = await findACourseClient.CourseSearchAsync(request); var response = new CourseSearchResult { ResultProperties = { TotalPages = GetTotalPages((apiResult?.Total).GetValueOrDefault(), (apiResult?.Limit).GetValueOrDefault()), TotalResultCount = (apiResult?.Total).GetValueOrDefault(), Page = GetCurrentPageNumber((apiResult?.Start).GetValueOrDefault(), (apiResult?.Limit).GetValueOrDefault()), OrderedBy = (CourseSearchOrderBy)Enum.Parse(typeof(CourseSearchOrderBy), request.SortBy.ToString()), }, Courses = mapper.Map <List <Course> >(apiResult?.Results), }; return(response.Courses.SelectCoursesForJobProfile()); } catch (Exception ex) { auditService.CreateAudit(request, ex); if (shouldThrowException) { throw ex; } return(Enumerable.Empty <Course>()); } }
public async Task <IActionResult> JoinBoard([FromBody] JoinBoard joinBoard) { var board = await _timelineContext.Board.Where(x => x.InviteToken == joinBoard.InviteToken) .Include(x => x.BoardMembers).FirstOrDefaultAsync(); var user = await _timelineContext.Users.Where(x => x.Id == joinBoard.UserId).FirstOrDefaultAsync(); if (board == null || user == null) { return(BadRequest()); } var boardAffiliation = new BoardAffiliation() { UserId = joinBoard.UserId, BoardId = board.Id }; board.BoardMembers.Add(boardAffiliation); Audit audit = new Audit { Action = AuditAction.UserJoinedBoard, Log = ($"{boardAffiliation.UserId} joined board {boardAffiliation.BoardId}"), Origin = AuditOrigin.BoardController, Team = null, TimeStamp = DateTime.Now, User = user }; await _auditService.CreateAudit(audit); await _timelineContext.SaveChangesAsync(); Console.WriteLine($"board affiliation {boardAffiliation.UserId} : {boardAffiliation.BoardId}"); _log.LogInformation("Creating board affiliation {userId} : {TeamId}", boardAffiliation.UserId, boardAffiliation.BoardId); return(Ok(board)); }
public async Task <string> GetAsync(string requestQueryString, RequestType requestType) { var requestRoute = requestType == RequestType.Search ? $"{requestType.ToString()}?" : string.Empty; var fullRequest = $"{aVAPIServiceSettings.FAAEndPoint}/{requestRoute}{requestQueryString}"; logger.LogInformation($"Getting API data for request :'{fullRequest}'"); var response = await httpClient.GetAsync(new Uri(fullRequest)).ConfigureAwait(false); //Even if there is a bad response code still read and write the resposne into the audit as it may have information about the cause. var responseContent = await(response?.Content?.ReadAsStringAsync()).ConfigureAwait(false); auditService.CreateAudit(fullRequest, responseContent, correlationId); if (response != null && !response.IsSuccessStatusCode) { logger.LogError($"Error status {response.StatusCode}, Getting API data for request :'{fullRequest}' \nResponse : {responseContent}"); //this will throw an exception as is not a success code response.EnsureSuccessStatusCode(); } return(responseContent); }