public async Task RequestServicesCommandHandler_Handle_RecordsProcessed() { var availabilityService = new Mock <IAvailabilityService>(); availabilityService.Setup(e => e.Request(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new AvailabilityResponseModel(HttpStatusCode.OK, 22, "{}")); var availabilityProcessor = new AvailabilityProcessor(_availabilityRecordRepository, availabilityService.Object); var requestServicesCommandHandler = new RequestServicesCommandHandler(_availabilityContext, availabilityProcessor); var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, null, 2); await _availabilityRecordRepository.AddAsync(availabilityRecord, CancellationToken.None); await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(CancellationToken.None); await requestServicesCommandHandler.Handle(new RequestServicesCommand(), CancellationToken.None); availabilityRecord = await _availabilityRecordRepository .GetById(availabilityRecord.Id, CancellationToken.None) .ConfigureAwait(false); Assert.Single(availabilityRecord.AvailabilityLogs); Assert.Equal(200, availabilityRecord.AvailabilityLogs.First().StatusCode); Assert.Equal(22, availabilityRecord.AvailabilityLogs.First().ResponseTime); Assert.Equal("{}", availabilityRecord.AvailabilityLogs.First().Body); }
public async Task DeleteAvailabilityRecordCommandHandler_Handle_AvailabilityRecordDeleteIsNotAllowedFail() { var accountId = Guid.NewGuid(); var availabilityRecord = new AvailabilityRecord(accountId, "test", "http://google.com/", 200, "{}", 2); await _availabilityRecordRepository.AddAsync(availabilityRecord, CancellationToken.None); await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(CancellationToken.None); var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Guid.Empty.ToString())); var claimsPrincipal = new ClaimsPrincipal(); claimsPrincipal.AddIdentity(claimsIdentity); var deleteAvailabilityRecordCommandHandler = new DeleteAvailabilityRecordCommandHandler(_availabilityRecordRepository, _claimConverter); await Assert.ThrowsAsync <InvalidOperationException>(async() => { await deleteAvailabilityRecordCommandHandler .Handle(new DeleteAvailabilityRecordCommand(availabilityRecord.Id, claimsPrincipal), CancellationToken.None).ConfigureAwait(false); }); }
public async Task AvailabilityProcessor_ProcessAvailabilityRecord_RecordProcessed() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com/", 200, null, 2); await _availabilityRecordRepository.AddAsync(availabilityRecord, CancellationToken.None); await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(CancellationToken.None); var availabilityService = new Mock <IAvailabilityService>(); availabilityService.Setup(e => e.Request(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new AvailabilityResponseModel(HttpStatusCode.OK, 65, "{}")); var availabilityProcessor = new AvailabilityProcessor(_availabilityRecordRepository, availabilityService.Object); await availabilityProcessor.ProcessAvailabilityRecord(availabilityRecord.Id, CancellationToken.None); availabilityRecord = await _availabilityRecordRepository.GetById(availabilityRecord.Id, CancellationToken.None); Assert.Single(availabilityRecord.AvailabilityLogs); Assert.Equal(200, availabilityRecord.AvailabilityLogs.First().StatusCode); Assert.Equal("{}", availabilityRecord.AvailabilityLogs.First().Body); Assert.Equal(65, availabilityRecord.AvailabilityLogs.First().ResponseTime); }
public async Task <AvailabilityRecord> AddAsync(AvailabilityRecord availabilityRecord, CancellationToken cancellationToken) { await _availabilityContext.Database.EnsureCreatedAsync(cancellationToken); await _availabilityContext.AvailabilityRecords.AddAsync(availabilityRecord, cancellationToken) .ConfigureAwait(false); return(availabilityRecord); }
public void Availability_HasExpectedResponse_HasExpectedResponseIsTrue() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, "{}", 1); Assert.True(availabilityRecord.HasExpectedResponse); }
public void Availability_UpdateExpectedStatus_ExpectedStatusChanged() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, "{}", 1); availabilityRecord.UpdateExpectedStatusCode(500); Assert.Equal(500, availabilityRecord.ExpectedStatusCode); }
public void Availability_UpdateUrl_UrlChanged() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, "{}", 1); availabilityRecord.UpdateUrl("http://github.com/"); Assert.Equal("http://github.com/", availabilityRecord.Url); }
public void Availability_UpdateLogLifetimeThresholdInHours_LogLifetimeThresholdInHoursChanged() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, "{}", 1); availabilityRecord.UpdateLogLifetimeThresholdInHours(1); Assert.Equal(1, availabilityRecord.LogLifetimeThresholdInHours); }
public void Availability_UpdateName_NameChanged() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, "{}", 1); availabilityRecord.UpdateName("new name"); Assert.Equal("new name", availabilityRecord.Name); }
public void Availability_UpdateExpectedResponse_ExpectedResponseChanged() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, "{}", 1); availabilityRecord.UpdateExpectedResponse("test"); Assert.Equal("test", availabilityRecord.ExpectedResponse); }
public void Availability_ClearOutdatedLogs_LogsNotRemoved() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 200, null, 1); availabilityRecord.AppendLog(200, "{}", 100); availabilityRecord.ClearOutdatedLogs(); Assert.Single(availabilityRecord.AvailabilityLogs); }
public void Availability_AppendLog_LogCreatedInvalidResponseCodeFail() { var availabilityRecord = new AvailabilityRecord(Guid.NewGuid(), "test name", "http://google.com", 204, "{}", 1); availabilityRecord.AppendLog(200, "{}", 100); Assert.Single(availabilityRecord.AvailabilityLogs); Assert.Equal("ST_ERROR", availabilityRecord.Status); }
public async Task Handle(CreateAvailabilityRecordCommand notification, CancellationToken cancellationToken) { var accountId = _claimConverter.GetAccountId(notification.ClaimsPrincipal); var availabilityRecord = new AvailabilityRecord(accountId, notification.Name, notification.Url, notification.ExpectedStatusCode, notification.ExpectedResponse, notification.LogLifetimeThresholdInHours); await _availabilityRecordRepository.AddAsync(availabilityRecord, cancellationToken) .ConfigureAwait(false); await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); }
public async Task GetAvailabilityRecordsCommandHandler_Handle_AvailabilityRecordsReturned() { var accountId = Guid.NewGuid(); var availabilityRecord = new AvailabilityRecord(accountId, "test name", "http://google.com/", 200, "{}", 2); availabilityRecord.AppendLog(200, "{}", 66); await _availabilityRecordRepository.AddAsync(availabilityRecord, CancellationToken.None) .ConfigureAwait(false); await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(CancellationToken.None); var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accountId.ToString())); var claimsPrincipal = new ClaimsPrincipal(); claimsPrincipal.AddIdentity(claimsIdentity); var configuration = new MapperConfiguration(cfg => { cfg.AddProfile <DefaultDomainMapping>(); }); var mapper = configuration.CreateMapper(); var getAvailabilityRecordsCommandHandler = new GetAvailabilityListItemsCommandHandler(_availabilityRecordRepository, _claimConverter, mapper); var availabilityListItemDtos = await getAvailabilityRecordsCommandHandler .Handle(new GetAvailabilityListItemsCommand(claimsPrincipal), CancellationToken.None) .ConfigureAwait(false); Assert.Equal(availabilityRecord.Id, availabilityListItemDtos.First().Id); Assert.Equal("http://google.com/", availabilityListItemDtos.First().Url); Assert.Equal("test name", availabilityListItemDtos.First().Name); Assert.Equal("ST_OK", availabilityListItemDtos.First().Status); }
public void Availability_Constructor_AvailabilityRecordCreated() { var accountId = Guid.NewGuid(); var availabilityRecord = new AvailabilityRecord(accountId, "test name", "http://google.com", 200, "{}", 1); Assert.True(IsValidGuid(availabilityRecord.Id)); Assert.Equal(accountId, availabilityRecord.AccountId); Assert.Equal("test name", availabilityRecord.Name); Assert.Equal("http://google.com", availabilityRecord.Url); Assert.Equal(200, availabilityRecord.ExpectedStatusCode); Assert.Equal("{}", availabilityRecord.ExpectedResponse); Assert.Equal(1, availabilityRecord.LogLifetimeThresholdInHours); Assert.Equal("ST_OK", availabilityRecord.Status); }
public async Task UpdateAvailabilityRecordCommandHandler_Handle_AvailabilityRecordUpdated() { var accountId = Guid.NewGuid(); var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accountId.ToString())); var claimsPrincipal = new ClaimsPrincipal(); claimsPrincipal.AddIdentity(claimsIdentity); var createAvailabilityRecordCommandHandler = new UpdateAvailabilityRecordCommandHandler(_availabilityRecordRepository, _claimConverter); var record = new AvailabilityRecord(accountId, "name", "url", 200, "{}", 1); await _availabilityRecordRepository.AddAsync(record, CancellationToken.None); await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(CancellationToken.None); await createAvailabilityRecordCommandHandler.Handle(new UpdateAvailabilityRecordCommand(claimsPrincipal, record.Id, "test name", "http://google.com/", 200, "{}", 12), CancellationToken.None).ConfigureAwait(false); Assert.Equal(accountId, record.AccountId); Assert.Equal("test name", record.Name); Assert.Equal("http://google.com/", record.Url); Assert.Equal(200, record.ExpectedStatusCode); Assert.Equal("{}", record.ExpectedResponse); Assert.Equal(12, record.LogLifetimeThresholdInHours); }
public async Task UpdateAvailabilityRecordCommandHandler_Handle_DifferentAccountIdFail() { var accountId = Guid.NewGuid(); var claimsIdentity = new ClaimsIdentity(); claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accountId.ToString())); var claimsPrincipal = new ClaimsPrincipal(); claimsPrincipal.AddIdentity(claimsIdentity); var createAvailabilityRecordCommandHandler = new UpdateAvailabilityRecordCommandHandler(_availabilityRecordRepository, _claimConverter); var record = new AvailabilityRecord(Guid.NewGuid(), "name", "url", 200, "{}", 1); await _availabilityRecordRepository.AddAsync(record, CancellationToken.None); await _availabilityRecordRepository.UnitOfWork.SaveEntitiesAsync(CancellationToken.None); await Assert.ThrowsAsync <InvalidOperationException>(async() => { await createAvailabilityRecordCommandHandler.Handle(new UpdateAvailabilityRecordCommand(claimsPrincipal, record.Id, "test name", "http://google.com/", 200, "{}", 12), CancellationToken.None).ConfigureAwait(false); }); }
public AvailabilitySet GetCalenderInormation(IConfiguration configuration, ILogger logger, RequestParameters requestparams) { var EnvironmentVariable = configuration.GetSection("EnvironmentVariable"); var availabilitySet = new AvailabilitySet { AvailabilityRecord = new List <AvailabilityRecord>() }; try { var clientURL = EnvironmentVariable.GetValue <string>("GraphAPIEndpointUri"); String bearerToken = "Bearer " + EnvironmentVariable.GetValue <string>("AccessToken"); var parameters = new CalenderScheduleParameters { availabilityViewInterval = EnvironmentVariable.GetValue <string>("availabilityViewInterval") }; //var batchSize = 1; //int numberOfBatches = (int)Math.Ceiling((double)requestparams.EmailId.Count() / batchSize); //for (int i = 0; i < numberOfBatches; i++) //{ // var currentIds = requestparams.EmailId.Skip(i * batchSize).Take(batchSize); // var tasks = currentIds.Select(id => client.GetUser(id)); // users.AddRange(await Task.WhenAll(tasks)); //} parameters.Schedules = new List <string>(requestparams.EmailId); parameters.StartTime = new StartTime { dateTime = requestparams.StartDate.Value.Date, timeZone = requestparams.TimeZone }; parameters.EndTime = new EndTime { dateTime = requestparams.EndDate.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59), timeZone = requestparams.TimeZone }; var client = new HttpClient { BaseAddress = new Uri(clientURL) }; string postBody = JsonConvert.SerializeObject(parameters); client.DefaultRequestHeaders.Add("Authorization", bearerToken); var content = new StringContent(postBody.ToString(), Encoding.UTF8, "application/json"); //Call Graph API var response = client.PostAsync(clientURL, content).Result; var contents = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); JObject jsonObject = JObject.Parse(contents); //Check if result contains value key if (jsonObject.ContainsKey("value")) { //Iterate through Users foreach (var userSchedule in jsonObject["value"]) { var record = new AvailabilityRecord { AvailabilityInformation = new List <AvailabilityInformation>() }; logger.LogInformation($"User: {userSchedule["scheduleId"]}"); record.EmailId = userSchedule["scheduleId"].ToString(); record.TimeZone = "UTC"; //Check if there any Calender schedule if (JObject.Parse(userSchedule.ToString()).ContainsKey("scheduleItems")) { //Iterate through User Calender schedule foreach (var scheduleItems in userSchedule["scheduleItems"].Where(x => x["status"].ToString() == "oof")) { logger.LogInformation($"User: {scheduleItems["status"]}"); logger.LogInformation($"Start Date: {scheduleItems["start"]["dateTime"]}"); logger.LogInformation($"End Date: {scheduleItems["end"]["dateTime"]}"); var availabilityinfo = new AvailabilityInformation { Date = Convert.ToDateTime(scheduleItems["start"]["dateTime"]), StartDate = Convert.ToDateTime(scheduleItems["start"]["dateTime"]), EndDate = Convert.ToDateTime(scheduleItems["end"]["dateTime"]), FullDayIndicator = (Convert.ToDateTime(scheduleItems["end"]["dateTime"]) - Convert.ToDateTime(scheduleItems["start"]["dateTime"])).TotalHours > 12 }; record.AvailabilityInformation.Add(availabilityinfo); } } availabilitySet.AvailabilityRecord.Add(record); } } else { if (jsonObject.ContainsKey("error")) { logger.LogError($"Error in GRAPH API Call {jsonObject["error"]}"); } } } catch (Exception ex) { logger.LogError($"Error in GRAPH API Call {ex.Message}"); } return(availabilitySet); }
public void Remove(AvailabilityRecord availabilityRecord) { _availabilityContext.AvailabilityRecords.Remove(availabilityRecord); }
public void Update(AvailabilityRecord availabilityRecord) { _availabilityContext.AvailabilityRecords.Update(availabilityRecord); }
public async Task <List <AvailabilityRecord> > GetAvailability(CalenderScheduleParameters parameters, IEnumerable <string> EmailId, String bearerToken) { List <AvailabilityRecord> result = new List <AvailabilityRecord>(); parameters.Schedules = new List <string>(EmailId); var client = new HttpClient { BaseAddress = new Uri(clientURL) }; string postBody = JsonConvert.SerializeObject(parameters); client.DefaultRequestHeaders.Add("Authorization", bearerToken); var content = new StringContent(postBody.ToString(), Encoding.UTF8, "application/json"); //Call Graph API var response = client.PostAsync(clientURL, content).Result; var contents = await response.Content.ReadAsStringAsync(); JObject jsonObject = JObject.Parse(contents); //Check if result contains value key if (jsonObject.ContainsKey("value")) { //Iterate through Users foreach (var userSchedule in jsonObject["value"]) { var record = new AvailabilityRecord { AvailabilityInformation = new List <AvailabilityInformation>() }; logger.LogInformation($"User: {userSchedule["scheduleId"]}"); record.EmailId = userSchedule["scheduleId"].ToString(); record.TimeZone = "UTC"; //Check if there any Calender schedule if (JObject.Parse(userSchedule.ToString()).ContainsKey("scheduleItems")) { //Iterate through User Calender schedule foreach (var scheduleItems in userSchedule["scheduleItems"].Where(x => x["status"].ToString() == "oof")) { logger.LogInformation($"User: {scheduleItems["status"]}"); logger.LogInformation($"Start Date: {scheduleItems["start"]["dateTime"]}"); logger.LogInformation($"End Date: {scheduleItems["end"]["dateTime"]}"); var availabilityinfo = new AvailabilityInformation { Date = Convert.ToDateTime(scheduleItems["start"]["dateTime"]), StartDate = Convert.ToDateTime(scheduleItems["start"]["dateTime"]), EndDate = Convert.ToDateTime(scheduleItems["end"]["dateTime"]), FullDayIndicator = (Convert.ToDateTime(scheduleItems["end"]["dateTime"]) - Convert.ToDateTime(scheduleItems["start"]["dateTime"])).TotalHours > 12 }; record.AvailabilityInformation.Add(availabilityinfo); } } result.Add(record); } } else { if (jsonObject.ContainsKey("error")) { logger.LogError($"Error in GRAPH API Call {jsonObject["error"]}"); } } return(result); }