public async Task GetPatientCareContext(DiscoveryRequest request, string correlationId)
        {
            try
            {
                var(response, error) = await patientDiscovery.PatientFor(request);

                var patientId = request.Patient.Id;
                var cmSuffix  = patientId.Substring(
                    patientId.LastIndexOf("@", StringComparison.Ordinal) + 1);
                var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                    response?.Patient,
                    Guid.NewGuid(),
                    DateTime.Now.ToUniversalTime(),
                    request.TransactionId, //TODO: should be reading transactionId from contract
                    error?.Error,
                    new Resp(request.RequestId));
                logger.LogInformation(LogEvents.Discovery,
                                      "Response about to be send for {RequestId} with {@Patient}",
                                      request.RequestId,
                                      response?.Patient);
                await gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, cmSuffix, correlationId);
            }
            catch (Exception exception)
            {
                logger.LogError(LogEvents.Discovery, exception, "Error happened for {RequestId}", request.RequestId);
            }
        }
 private static void AndTheResponseShouldContainTheExpectedStatus(GatewayDiscoveryRepresentation actualResponse,
                                                                  DiscoveryRequest discoveryRequest, HttpStatusCode expectedStatusCode, string expectedMessage)
 {
     actualResponse.Resp.RequestId.Should().Be(discoveryRequest.RequestId);
     // actualResponse.Resp.StatusCode.Should().Be(expectedStatusCode);
     // actualResponse.Resp.Message.Should().Be(expectedMessage);
 }
        public async Task GetPatientCareContext(DiscoveryRequest request)
        {
            var patientId = request.Patient.Id;
            var cmSuffix  = patientId.Substring(patientId.LastIndexOf("@", StringComparison.Ordinal) + 1);

            try {
                var(response, error) = await patientDiscovery.PatientFor(request);

                var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                    response?.Patient,
                    Guid.NewGuid(),
                    DateTime.Now.ToUniversalTime(),
                    request.TransactionId, //TODO: should be reading transactionId from contract
                    error?.Error,
                    new DiscoveryResponse(request.RequestId, error == null ? HttpStatusCode.OK : HttpStatusCode.NotFound, error == null ? SuccessMessage : ErrorMessage));
                logger.LogInformation(LogEvents.Discovery,
                                      "Response about to be send for {RequestId} with {@Patient}",
                                      request.RequestId,
                                      response?.Patient);
                await gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, cmSuffix);
            }
            catch (Exception exception)
            {
                var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                    null,
                    Guid.NewGuid(),
                    DateTime.Now.ToUniversalTime(),
                    request.TransactionId, //TODO: should be reading transactionId from contract
                    new Error(ErrorCode.ServerInternalError, "Unreachable external service"),
                    new DiscoveryResponse(request.RequestId, HttpStatusCode.InternalServerError, "Unreachable external service"));
                await gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, cmSuffix);

                logger.LogError(LogEvents.Discovery, exception, "Error happened for {RequestId}", request.RequestId);
            }
        }
        private void ThenAResponseToThisTransactionShouldHaveBeenSentToTheGateway(
            DiscoveryRequest discoveryRequest,
            out GatewayDiscoveryRepresentation actualResponse)
        {
            responsesSentToGateway.Should().ContainKey(discoveryRequest.TransactionId);

            actualResponse = responsesSentToGateway[discoveryRequest.TransactionId];
        }
 private static void AndTheResponseShouldContainTheMatchFields(GatewayDiscoveryRepresentation actualResponse,
                                                               ICollection <string> matchedFields)
 {
     actualResponse.Patient.MatchedBy.Count().Should().Be(matchedFields.Count);
     foreach (var matchedFieldName in matchedFields)
     {
         actualResponse.Patient.MatchedBy.Should().ContainEquivalentOf(matchedFieldName);
     }
 }
        private void ShouldReturnDataToGateway()
        {
            var handlerMock          = new Mock <HttpMessageHandler>(MockBehavior.Strict);
            var httpClient           = new HttpClient(handlerMock.Object);
            var gatewayConfiguration = new GatewayConfiguration {
                Url = "http://someUrl"
            };
            var authenticationUri            = new Uri($"{gatewayConfiguration.Url}/{PATH_SESSIONS}");
            var expectedUri                  = new Uri($"{gatewayConfiguration.Url}{PATH_ON_DISCOVER}");
            var patientEnquiryRepresentation = new PatientEnquiryRepresentation(
                "123",
                "Jack",
                new List <CareContextRepresentation>(),
                new List <string>());
            var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                patientEnquiryRepresentation,
                Guid.NewGuid(),
                DateTime.Now,
                "transactionId",
                null,
                new Resp("requestId"));
            var gatewayClient = new GatewayClient(httpClient, gatewayConfiguration);
            var definition    = new { accessToken = "Whatever", tokenType = "Bearer" };
            var result        = JsonConvert.SerializeObject(definition);
            var correlationId = Uuid.Generate().ToString();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsInOrder(() => Task.FromResult(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(result)
            }), () => Task.FromResult(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK
            }));

            gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, "ncg", correlationId);

            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post &&
                                               message.RequestUri == expectedUri),
                ItExpr.IsAny <CancellationToken>());
            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post &&
                                               message.RequestUri == authenticationUri),
                ItExpr.IsAny <CancellationToken>());
        }
 private static void AndTheSentResponseShouldContainTheFoundPatient(GatewayDiscoveryRepresentation actualResponse,
                                                                    PatientEnquiryRepresentation patientEnquiry)
 {
     actualResponse.Patient.ReferenceNumber.Should().Be(patientEnquiry.ReferenceNumber);
     actualResponse.Patient.Display.Should().Be(patientEnquiry.Display);
     actualResponse.Patient.CareContexts.Count().Should().Be(patientEnquiry.CareContexts.Count());
     foreach (CareContextRepresentation careContext in patientEnquiry.CareContexts)
     {
         actualResponse.Patient.CareContexts.Should().ContainEquivalentOf(careContext);
     }
 }
        private void ShouldNotPostDataIfAuthenticationWithGatewayFailed()
        {
            var handlerMock          = new Mock <HttpMessageHandler>(MockBehavior.Strict);
            var httpClient           = new HttpClient(handlerMock.Object);
            var gatewayConfiguration = new GatewayConfiguration {
                Url = "http://someUrl"
            };
            var authenticationUri            = new Uri($"{gatewayConfiguration.Url}/{PATH_SESSIONS}");
            var patientEnquiryRepresentation = new PatientEnquiryRepresentation(
                "123",
                "Jack",
                new List <CareContextRepresentation>(),
                new List <string>());
            var gatewayDiscoveryRepresentation = new GatewayDiscoveryRepresentation(
                patientEnquiryRepresentation,
                Guid.NewGuid(),
                DateTime.Now,
                "transactionId",
                null,
                new Resp("requestId"));
            var gatewayClient = new GatewayClient(httpClient, gatewayConfiguration);
            var correlationId = Uuid.Generate().ToString();

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadGateway
            })
            .Verifiable();

            gatewayClient.SendDataToGateway(PATH_ON_DISCOVER, gatewayDiscoveryRepresentation, "ncg", correlationId);

            handlerMock.Protected().Verify(
                "SendAsync",
                Times.Exactly(1),
                ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Post &&
                                               message.RequestUri == authenticationUri),
                ItExpr.IsAny <CancellationToken>());
        }
 private static void AndTheResponseShouldNotContainAnyError(GatewayDiscoveryRepresentation actualResponse)
 {
     actualResponse.Error.Should().BeNull();
 }
 private static void AndTheResponseShouldContainTheErrorDetails(GatewayDiscoveryRepresentation actualResponse,
                                                                ErrorRepresentation errorRepresentation)
 {
     actualResponse.Error.Code.Should().Be(errorRepresentation.Error.Code);
     actualResponse.Error.Message.Should().Be(errorRepresentation.Error.Message);
 }
 private static void AndTheResponseShouldContainTheTransactionId(GatewayDiscoveryRepresentation actualResponse,
                                                                 DiscoveryRequest discoveryRequest)
 {
     actualResponse.TransactionId.Should().Be(discoveryRequest.TransactionId);
 }
 private static void AndTheResponseShouldNotContainAyMatchFields(GatewayDiscoveryRepresentation actualResponse)
 {
     actualResponse.Patient.Should().BeNull();
 }