示例#1
0
        public void ListenForNewMessages_Should_Succeed()
        {
            var mockSqsClient = _fixture.Freeze <Mock <IAmazonSQS> >();
            var pocMessage    = _fixture.Create <POCMessage>();
            var sqsMessage    = new SQSEvent.SQSMessage {
                Body = JsonConvert.SerializeObject(pocMessage)
            };
            var sqsEvent = new SQSEvent {
                Records = new List <SQSEvent.SQSMessage>()
                {
                    sqsMessage
                }
            };
            var context = _fixture.Freeze <Mock <ILambdaContext> >();

            var sut = new IncomingRequest(mockSqsClient.Object);

            var response = sut.ListenForNewMessages(sqsEvent, context.Object);

            Assert.IsType <POCMessage>(response);
            Assert.Equal(pocMessage.Status, response.Status);
            Assert.Equal(pocMessage.EmailAddress, response.EmailAddress);
            Assert.Equal(pocMessage.EventName, response.EventName);

            context.Verify(x => x.Logger.LogLine(It.IsAny <string>()), Times.Once);
        }
示例#2
0
        /// <summary>
        /// Insert IncomingRequest to db.
        /// </summary>
        /// <param name="incomingRequest"></param>
        /// <returns>IncomingRequestId</returns>
        public async Task <string> AddIncomingRequest(IncomingRequest incomingRequest)
        {
            var insertIncomingRequest = _mapper.Map <Infrastructure.DataAccess.DBModel.IncomingRequest>(incomingRequest);
            await _incomingRequestRepository.InsertAsync(insertIncomingRequest);

            return(insertIncomingRequest.Id);
        }
        public async Task ProcessIncomingRequest_ValidModelNullResponse_ShouldReturnBadRequestResponse(string expectedResponse)
        {
            IncomingRequest incomingRequest = new IncomingRequest();

            requestManager.Setup(x => x.InsertIncomingRequest(incomingRequest)).Returns(Task.FromResult("5c8a01a5efe48745ac3c98c6"));
            var mockResponse = expectedResponse;

            requestManager.Setup(x => x.ProcessIncomingRequest(It.IsAny <IncomingRequest>(), It.IsAny <string>(), It.IsAny <Dictionary <string, string> >())).Returns(Task.FromResult(mockResponse));

            var request = new Mock <HttpRequest>();

            request.SetupGet(x => x.Headers["X-Requested-With"]).Returns("XMLHttpRequest");

            var context = new Mock <HttpContext>();

            context.SetupGet(x => x.Request).Returns(request.Object);

            controller.ControllerContext = new ControllerContext(new ActionContext(context.Object, new RouteData(), new ControllerActionDescriptor()));

            //Act
            var response = await controller.ProcessIncomingRequest(incomingRequest) as BadRequestObjectResult;

            //Assert
            Assert.Equal(mockResponse, response.Value);
        }
        public async Task AddIncommingAsync <TSupplierType>(string incomingPrefix, TSupplierType supplierType, CancellationToken cancellationToken = default)
        {
            try
            {
                incomingPrefix.NotNullOrWhiteSpace(nameof(incomingPrefix));
                supplierType.NotNull(nameof(supplierType));

                var strSupplierType = supplierType.ConvertTo <string>();
                var hashCode        = incomingPrefix.GetInvariantHashCode();

                Logger.SetProperty(LogConstants.IncomingRequestHashCode, hashCode);
                Logger.SetProperty(LogConstants.SupplierType, strSupplierType);

                var incomingRequest = new IncomingRequest
                {
                    CreatedAt = SystemClock.DateTimeNow,
                    HashCode  = hashCode
                };

                using (await AsyncLock.LockAsync())
                    await IncomingRequestStore.AddAsync(incomingRequest, cancellationToken);
            }
            catch (Exception ex)
                when(Logger.LogErrorIfNotBefore(ex, "Exception ocurred in {MethodName}", nameof(AddIncommingAsync)))
                {
                    throw;
                }
        }
        protected GoodIdEndpoint(
            IncomingRequest incomingRequest,
            string clientId,
            RsaPrivateKey signingKey,
            RsaPrivateKey encryptionKey,
            OpenIdRequestSource requestSource,
            string redirectUri,
            Acr acr,
            int?maxAge,
            ServiceLocator serviceLocator)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new GoodIdException($"{nameof(clientId)} can not be empty");
            }

            if (maxAge.HasValue && (maxAge.Value < MAX_AGE_MIN_VALUE || maxAge.Value > MAX_AGE_MAX_VALUE))
            {
                throw new GoodIdException($"{nameof(maxAge)} must be null or an int in the range [{MAX_AGE_MIN_VALUE}, {MAX_AGE_MAX_VALUE}]");
            }

            mIncomingRequest = incomingRequest;
            mClientId        = clientId;
            mSigningKey      = signingKey;
            mEncryptionKey   = encryptionKey;
            mRequestSource   = requestSource;
            mRedirectUri     = redirectUri;
            mAcr             = acr;
            mMaxAge          = maxAge;
            mServiceLocator  = serviceLocator;
        }
示例#6
0
        private OutgoingResponse GenerateResponse()
        {
            using (var connection = new SqlConnection(CONN))
            {
                var command = new SqlCommand("SELECT * FROM shopping WHERE AddedOn > DATEADD(s,-2,GETUTCDATE())", connection);
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var record = new IncomingRequest();

                        record.AddedOn      = Convert.ToDateTime(reader["AddedOn"]);
                        record.ConnectionID = reader["ConnectionID"].ToString();
                        record.IP           = reader["IP"].ToString();
                        record.CartItem     = reader["CartItem"].ToString();

                        ConnectedIPs.Add(record);
                    }
                }
            }

            var latestCartItems = ConnectedIPs.GroupBy(x => x.IP).Select(t => t.OrderByDescending(c => c.AddedOn).First()).ToDictionary(x => x.IP, x => x.CartItem);

            return(new OutgoingResponse {
                NewCartItem = GenerateRandomCartItem(), CartItemsOfOthers = latestCartItems
            });
        }
        // Determines if the incoming message is a request or a response.
        private void ProcessMessage(JsonElement?element)
        {
            if (element == null || element.Value.ValueKind != JsonValueKind.Object)
            {
                return;
            }

            var properties = element.Value.EnumerateObject().Select(p => (JsonProperty?)p).ToArray();
            var id         = properties.GetPropertyOrNull("id")?.Value.ToString();
            var method     = properties.GetPropertyOrNull("method")?.Value.GetString();

            if (!method.IsNullOrEmpty())
            {
                var parameters = properties.GetPropertyOrNull("params")?.Value;
                var request    = new IncomingRequest {
                    Id = id, Method = method, Params = parameters
                };
                _requestProcess(request);
                return;
            }

            var result = properties.GetPropertyOrNull("result")?.Value.GetRawText();

            if (!result.IsNullOrEmpty())
            {
                var response = new IncomingResponse {
                    Id = id, Result = result
                };
                _responseProcess(response);
            }
        }
        private IncomingRequest GetDropOffLocaction(IncomingRequest request)
        {
            var address = $"Here is your nearest drop off location. \n Norwich - Big YellowCanary Way, Norwich, NR1 1WY ,\n Eurofins Water Hygiene Testing UK -Wolverhampton , \n 4937.8 miles from search";

            request.body = address;

            return(request);
        }
 /// <summary>Queues a request for the multi handle to process.</summary>
 public void Queue(IncomingRequest request)
 {
     lock (_incomingRequests)
     {
         // Add the request, then initiate processing.
         _incomingRequests.Enqueue(request);
         EnsureWorkerIsRunning();
     }
 }
示例#10
0
        public Task Handle(IncomingRequest request, CancellationToken cancellationToken = default)
        {
            if (!_started)
            {
                throw new InvalidOperationException("Messenger was not started.");
            }

            HttpRequest httpRequest = request.HttpRequest;

            if (httpRequest.Method != HttpMethods.Post || _webhookUri.Host != httpRequest.Host.Value ||
                _webhookUri.AbsolutePath != httpRequest.Path.Value)
            {
                _logger.LogWarning("Invalid request headers: {Method}, {Host}, {Path}", httpRequest.Method,
                                   httpRequest.IsHttps, httpRequest.Host.Value, httpRequest.Path.Value);

                return(Task.CompletedTask);
            }

            return(HandleAsync());

            async Task HandleAsync()
            {
                using var reader = new StreamReader(request.HttpRequest.Body);
                string payload = await reader.ReadToEndAsync();

                Update update;

                try
                {
                    update = JsonConvert.DeserializeObject <Update>(payload);
                }
                catch (JsonException exception)
                {
                    _logger.LogError(exception, "Failed to deserialize payload");

                    return;
                }

                request.Handled = true;

                switch (update.Type)
                {
                case UpdateType.CallbackQuery:
                    OnCallbackQuery(update.CallbackQuery, cancellationToken);
                    return;

                case UpdateType.Message:
                    await OnMessage(update.Message, cancellationToken);

                    return;

                default:
                    _logger.LogWarning("Ignored update with type {UpdateType}", update.Type);
                    return;
                }
            }
        }
        public IHttpActionResult Index(IncomingRequest request)
        {
            Authentication();

            var eolMiniService = new EolMiniService();
            var result         = eolMiniService.GetIncomingRequest(request);

            return(Ok(result));
        }
示例#12
0
 /// <summary>Queues a request for the multi handle to process.</summary>
 public void Queue(IncomingRequest request)
 {
     lock (_incomingRequests)
     {
         // Add the request, then initiate processing.
         _incomingRequests.Enqueue(request);
         EnsureWorkerIsRunning();
     }
 }
示例#13
0
        protected virtual bool RequestHandler(IncomingRequest req, OutgoingResponse res)
        {
            if (!CheckHeaders(req, res))
            {
                return(false);
            }
            IPAddress remote = res.Connection.Base.RemoteAddress;

            if (!SubprotocolNegotiation.TryParse(req["Sec-WebSocket-Protocol"] ?? "", out string[] subprotocols))
        public string StartStopTracker(bool start)
        {
            string body = string.Empty;
            Stream s    = this.Request.Content.ReadAsStreamAsync().Result;

            s.Seek(0, SeekOrigin.Begin);
            using (var stream = new StreamReader(s))
            {
                //stream.Seek(0, SeekOrigin.Begin);
                body = stream.ReadToEnd(); //Newtonsoft.Json.JsonConvert.SerializeObject(re);;
            }
            try
            {
                if (!string.IsNullOrEmpty(body))
                {
                    IncomingRequest req = Newtonsoft.Json.JsonConvert.DeserializeObject <IncomingRequest>(body); //MailItem.FromJson(body);

                    if (req != null && req.MailItem != null)
                    {
                        MailItem usItem = req.MailItem;
                        using (MailTrackerProvider prov = new MailTrackerProvider())
                        {
                            prov.OpenConnection();
                            if (start)
                            {
                                if (prov.StartTracker(body, usItem.DataP0.DataP0.ConversationId, usItem.DisplayName) > 0)
                                {
                                    return("Started");
                                }
                            }
                            else
                            {
                                if (prov.StopTracker(body, usItem.DataP0.DataP0.ConversationId, usItem.DisplayName) > 0)
                                {
                                    return("Stopped");
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidCastException("Error: Mail JSON string arrived with wrong format");
                    }
                }
                else
                {
                    throw new InvalidCastException("Error: Mail JSON string arrived empty or with wrong format");
                }
                return("no.");
            }
            catch (Exception ex)
            {
                //MailItem usItem = Newtonsoft.Json.JsonConvert.DeserializeObject<MailItem>(body);
                //return "Error: " + ex.Message + "\r\n\r\n" + Newtonsoft.Json.JsonConvert.SerializeObject(usItem) + "\r\n\r\n" + ex.StackTrace;
                throw ex;
            }
        }
示例#15
0
        /// <summary>
        /// Insert the incoming request data with the incoming status and status Message
        /// </summary>
        public async Task <string> InsertIncomingRequest(IncomingRequest incomingRequest)
        {
            #region Insert record in db

            string incomingRequestId = await _requestRepository.AddIncomingRequest(incomingRequest);

            #endregion Insert record in db

            return(incomingRequestId);
        }
        public IEnumerator <RequestCommand> GetEnumerator()
        {
            yield return(new DefaultRequestCommand(IncomingRequest.is_for <ViewTheMainDepartmentsInTheStore>(),
                                                   Container.resolve.an <ViewTheMainDepartmentsInTheStore>()));

            yield return(new DefaultRequestCommand(IncomingRequest.is_for <ViewTheDepartmentsInADepartment>(),
                                                   Container.resolve.an <ViewTheDepartmentsInADepartment>()));

            yield return(new DefaultRequestCommand(IncomingRequest.is_for <ViewTheProductsInADepartment>(),
                                                   Container.resolve.an <ViewTheProductsInADepartment>()));
        }
        public async Task ProcessIncomingRequest_Exception_ShouldReturnInternalServerError()
        {
            //Arrange
            requestManager.Setup(x => x.InsertIncomingRequest(It.IsAny <IncomingRequest>())).Throws(new System.Exception());
            IncomingRequest incomingRequest = new IncomingRequest();

            //Act
            var response = await controller.ProcessIncomingRequest(incomingRequest) as StatusCodeResult;

            //Assert
            Assert.Equal(500, response.StatusCode);
        }
示例#18
0
        /// <summary>
        /// Publishing the incoming request data
        /// </summary>
        private void PublishIncomingRequestData(IncomingRequest incomingRequest, Dictionary <string, string> headers)
        {
            var eventMessage = new TransactionQueueAddedIntegrationEvent
            {
                Message = incomingRequest,
                Headers = headers
            };

            _eventBus.Publish(_configuration.KafkaCCEProxyTopic, eventMessage, headers);

            _logger.LogInformation(String.Format(LoggingMessage.DataPublished, JsonConvert.SerializeObject(eventMessage)));
        }
        public async Task ProcessIncomingRequest_InvalidModel_ShouldReturnBadRequest()
        {
            //Arrange
            controller.ModelState.AddModelError("invalid", "model is not valid");
            IncomingRequest incomingRequest = new IncomingRequest();

            //Act
            var mockResponse = await controller.ProcessIncomingRequest(incomingRequest) as BadRequestObjectResult;

            //Assert
            Assert.Equal(400, mockResponse.StatusCode);
        }
示例#20
0
        public async Task <IActionResult> ProcessIncomingRequest(IncomingRequest incomingRequest)
        {
            try
            {
                _logger.LogInformation(string.Format(LoggingMessage.RequestReceived, JsonConvert.SerializeObject(incomingRequest)));

                if (ModelState.IsValid)
                {
                    _logger.LogDebug(LoggingMessage.ModelStateValid);

                    incomingRequest.Status = IncomingRequestStatus.Received;

                    string incomingRequestId = await _requestManager.InsertIncomingRequest(incomingRequest);

                    var headers = Request.Headers.ToDictionary <KeyValuePair <string, StringValues>, string, string>(item => item.Key, item => item.Value);

                    var response = await _requestManager.ProcessIncomingRequest(incomingRequest, incomingRequestId, headers);

                    if (string.IsNullOrEmpty(response))
                    {
                        return(Accepted());
                    }
                    return(BadRequest(response));
                }
                else
                {
                    _logger.LogDebug(LoggingMessage.ModelStateInvalid);

                    incomingRequest.Status = IncomingRequestStatus.Rejected;

                    if (string.IsNullOrEmpty(incomingRequest.Priority) ||
                        string.IsNullOrEmpty(incomingRequest.Facility.FacilityCode) ||
                        incomingRequest.Items == null)
                    {
                        incomingRequest.StatusMessage = string.Join("; ", ModelState.Values
                                                                    .SelectMany(x => x.Errors)
                                                                    .Select(x => x.ErrorMessage));
                    }

                    string incomingRequestId = await _requestManager.InsertIncomingRequest(incomingRequest);

                    _logger.LogInformation($"{incomingRequestId}" + IncomingRequestStatus.Rejected);

                    return(BadRequest(incomingRequest.StatusMessage));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
示例#21
0
        private void RaiseIncomingRequest(HttpListenerContext context)
        {
            HttpRequestEventArgs e = new HttpRequestEventArgs(context);

            try
            {
                if (IncomingRequest != null)
                {
                    IncomingRequest.BeginInvoke(this, e, null, null);
                }
            }
            catch {}
        }
示例#22
0
 private void HandleIncomingRequest(IncomingRequest request)
 {
     Task.Factory.StartNew(() =>
     {
         if (_incomingRequestActions.TryGetValue(request.Method ?? String.Empty, out var requestAction))
         {
             var result = requestAction(this, request);
             if (!request.Id.IsNullOrEmpty())
             {
                 _outgoingMessageHandler.Respond(request.Id !, result).GetAwaiter().GetResult();
             }
         }
     }, _cancellationToken);
 }
示例#23
0
        public IActionResult Post([FromBody] IncomingRequest value)
        {
            var client   = new HttpClient();
            var response = client.PostAsync(@"https://api.vk.com/method/messages.send?message=" +
                                            "Ты сказал " +
                                            value.RequestObject.Body +
                                            "&user_id=" +
                                            value.RequestObject.UserId +
                                            "&access_token=39ce2d2a6c3a8881f2ee610404213b2f560582cd8add52fa3e8ba7dd7770a942f191ac45b7d24b5bf6d37" +
                                            "&v=5.0", null);

            var responseString = response.Result.Content.ReadAsStringAsync();

            return(new OkObjectResult("ok"));
        }
示例#24
0
 public GoodIdResponseCollector(
     ServiceLocator serviceLocator,
     IncomingRequest incomingRequest,
     string clientId,
     string clientSecret,
     RsaPrivateKey signingKey,
     RsaPrivateKey[] encryptionKeys,
     bool matchingResponseValidation = true)
 {
     mServiceLocator             = serviceLocator;
     mIncomingRequest            = incomingRequest;
     mClientId                   = clientId;
     mClientSecret               = clientSecret;
     mSigningKey                 = signingKey;
     mEncryptionKeys             = encryptionKeys;
     mMatchingResponseValidation = matchingResponseValidation;
 }
        public ActionResult <HadithBlocks> GetManyByAccurateRequest([FromBody] IncomingRequest request)
        {
            var queryable = db.HadithBlocks.Select(
                block => new HadithBlocks()
            {
                content   = block.content,
                id        = block.id,
                Refrences = block.Refrences,
                sources   = block.sources,
                src       = block.src,
                number    = block.number
            }
                );
            List <HadithBlocks> list = new List <HadithBlocks>();

            if (request.Method == 6)
            {
                list = queryable.Where(
                    b =>
                    b.src == request.src
                    &&
                    b.Refrences.Any(
                        refr =>
                        refr.Refrencetype == request.Refrencetype &&
                        refr.name == request.name &&
                        refr.value1 == request.value1 &&
                        refr.value2 == request.value2 &&
                        refr.value3 == request.value3 &&
                        refr.value4 == request.value4 &&
                        refr.tag1 == request.tag1 &&
                        refr.tag2 == request.tag2
                        )
                    )
                       .OrderBy(o => o.number)
                       .ToList()
                ;
            }

            if (isNullOr0(list) || isNullOr0(list.Count))
            {
                return(NotFound());
            }

            return(Ok(list));
        }
            private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request)
            {
                Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue");
                VerboseTrace("Type: " + request.Type, easy: request.Easy);

                EasyRequest easy = request.Easy;

                switch (request.Type)
                {
                case IncomingRequestType.New:
                    ActivateNewRequest(multiHandle, easy);
                    break;

                case IncomingRequestType.Cancel:
                    Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests");
                    Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested");
                    FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken));
                    break;

                case IncomingRequestType.Unpause:
                    Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests");
                    if (!easy._easyHandle.IsClosed)
                    {
                        IntPtr        gcHandlePtr;
                        ActiveRequest ar;
                        Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause");

                        CURLcode unpauseResult = Interop.Http.EasyUnpause(easy._easyHandle);
                        try
                        {
                            ThrowIfCURLEError(unpauseResult);
                        }
                        catch (Exception exc)
                        {
                            FindAndFailActiveRequest(multiHandle, easy, exc);
                        }
                    }
                    break;

                default:
                    Debug.Fail("Invalid request type: " + request.Type);
                    break;
                }
            }
        public string Get(string id)
        {
            string body = string.Empty;
            Stream s    = this.Request.Content.ReadAsStreamAsync().Result;

            s.Seek(0, SeekOrigin.Begin);
            using (var stream = new StreamReader(s))
            {
                //stream.Seek(0, SeekOrigin.Begin);
                body = stream.ReadToEnd(); //Newtonsoft.Json.JsonConvert.SerializeObject(re);;
            }
            try
            {
                using (MailTrackerProvider prov = new MailTrackerProvider())
                {
                    if (!string.IsNullOrEmpty(body))
                    {
                        if (prov.OpenConnection())
                        {
                            if (prov.IsTracked(System.Web.HttpUtility.UrlDecode(id)))
                            {
                                System.Data.DataTable tb = prov.FindByConversationId(id);
                                prov.SaveEmail(body, long.Parse(tb.Rows[0]["ID"].ToString()));
                                return(Newtonsoft.Json.JsonConvert.SerializeObject(new { IsTracked = true }));
                            }
                            return(Newtonsoft.Json.JsonConvert.SerializeObject(new { IsTracked = false }));
                        }
                        else
                        {
                            return(Newtonsoft.Json.JsonConvert.SerializeObject(new { IsTracked = false }));
                        }
                    }
                    else
                    {
                        throw new InvalidCastException("Mail JSON string arrived empty or with wrong format");
                    }
                }
            }
            catch (Exception ex)
            {
                IncomingRequest usItem = Newtonsoft.Json.JsonConvert.DeserializeObject <IncomingRequest>(body);
                return("Error: " + ex.Message + "\r\n\r\n" + Newtonsoft.Json.JsonConvert.SerializeObject(usItem) + "\r\n\r\n" + ex.StackTrace);
            }
        }
        public ActionResult <HadithBlocks> GetByRequestjson([FromBody] IncomingRequest request, [FromQuery] string jsonapi = "wrong")
        {
            if (jsonapi != JsonApi)
            {
                return(Unauthorized());
            }

            var Blocks = ReadJsonObject <List <HadithBlocks> >("Json/Hadiths/fulldb/bukhari_musli_fulldb.json");


            var model = blockService.SearchHadithsList(Blocks, request);

            if (isNull(model))
            {
                return(NotFound());
            }

            return(Ok(model));
        }
        public TwiMLResult Index(IncomingRequest request)
        {
            Authentication();

            var eolMiniService = new EolMiniService();

            var result = eolMiniService.GetIncomingRequest(request);

            var response = new MessagingResponse();

            response.Message(
                result.body,
                result.to,
                result.from,
                null,
                null,
                null);

            return(TwiML(response));
        }
示例#30
0
        public void PostIncomingRequest_Should_Fail()
        {
            var mockSqsClient       = _fixture.Freeze <Mock <IAmazonSQS> >();
            var sendMessageResponse = _fixture.Create <SendMessageResponse>();

            sendMessageResponse.HttpStatusCode = HttpStatusCode.InternalServerError;
            mockSqsClient.Setup(x => x.SendMessageAsync(It.IsAny <SendMessageRequest>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(sendMessageResponse));

            var request = _fixture.Create <APIGatewayProxyRequest>();
            var context = _fixture.Freeze <Mock <ILambdaContext> >();

            var sut = new IncomingRequest(mockSqsClient.Object);

            var response = sut.Post(request, context.Object).Result;

            Assert.Equal((int)HttpStatusCode.InternalServerError, response.StatusCode);
            Assert.Equal(sut.AnErrorOccured, response.Body);
            context.Verify(x => x.Logger.LogLine(It.IsAny <string>()), Times.Exactly(2));
            mockSqsClient.Verify(x => x.SendMessageAsync(It.IsAny <SendMessageRequest>(), It.IsAny <CancellationToken>()), Times.Once);
        }
示例#31
0
        /// <summary>
        /// Apply validations on the incoming object.
        /// If validation passes, return aggregated object of incoming request
        /// </summary>
        /// <param name="incomingRequest"></param>
        /// <param name="incomingRequestId"></param>
        /// <param name="headers"></param>
        public async Task <string> ProcessIncomingRequest(IncomingRequest incomingRequest, string incomingRequestId, Dictionary <string, string> headers)
        {
            string responseMessage = string.Empty;

            #region Step1. Get Facility based on Facility Code coming from Incoming Request
            var facility = await _requestRepository.GetFacility(incomingRequest.Facility.FacilityCode);

            string facilityResponse = CheckFacility(facility, incomingRequestId);
            if (!string.IsNullOrEmpty(facilityResponse))
            {
                await _requestRepository.UpdateIncomingRequest(incomingRequestId, IncomingRequestStatus.Rejected, LoggingMessage.FacilityInvalid);

                return(facilityResponse);
            }
            #endregion

            #region Step2. Get Transaction Priority based on Facility Id from Facility and PriorityCode from incoming request
            var transactionPriority = await _requestRepository.GetTransactionPriority(facility.Id, incomingRequest.Priority);

            string transactionResponse = CheckTransactionPriority(incomingRequestId, transactionPriority, incomingRequest.Priority);
            if (!string.IsNullOrEmpty(transactionResponse))
            {
                await _requestRepository.UpdateIncomingRequest(incomingRequestId, IncomingRequestStatus.Rejected, LoggingMessage.PriorityInvalid);

                return(transactionResponse);
            }
            #endregion

            #region Step3. Aggregate all the Data and update the status and status message

            incomingRequest.Facility.FacilityId = facility.Id;
            incomingRequest.RequestId           = incomingRequestId;
            incomingRequest.Items = incomingRequest.Items.Where(x => x.ItemId != null);
            await _requestRepository.UpdateIncomingRequest(incomingRequestId, IncomingRequestStatus.Accepted, LoggingMessage.DataValid);

            #endregion Step3

            PublishIncomingRequestData(incomingRequest, headers);
            return(responseMessage);
        }
 public void process(IncomingRequest request)
 {
     command_registry.get_command_that_can_handle(request).process(request);
 }
示例#33
0
            private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request)
            {
                Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue");
                VerboseTrace("Type: " + request.Type, easy: request.Easy);

                EasyRequest easy = request.Easy;
                switch (request.Type)
                {
                    case IncomingRequestType.New:
                        ActivateNewRequest(multiHandle, easy);
                        break;

                    case IncomingRequestType.Cancel:
                        Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests");
                        Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested");
                        FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken));
                        break;

                    case IncomingRequestType.Unpause:
                        Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests");
                        if (!easy._easyHandle.IsClosed)
                        {
                            IntPtr gcHandlePtr;
                            ActiveRequest ar;
                            Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause");

                            CURLcode unpauseResult = Interop.Http.EasyUnpause(easy._easyHandle);
                            try
                            {
                                ThrowIfCURLEError(unpauseResult);
                            }
                            catch (Exception exc)
                            {
                                FindAndFailActiveRequest(multiHandle, easy, exc);
                            }
                        }
                        break;

                    default:
                        Debug.Fail("Invalid request type: " + request.Type);
                        break;
                }
            }
 public RequestCommand get_command_that_can_handle(IncomingRequest request)
 {
     return commands.FirstOrDefault(command => command.can_handle(request)) ?? new MissingRequestCommand();
 }
 public void process(IncomingRequest request)
 {
     display_engine.display(catalog_tasks.get_all_main_departments());
 }
 public void process(IncomingRequest request)
 {
     raw_command.process(request);
 }
 public void process(IncomingRequest request)
 {
     display_engine.display(department_registry.get_main_departments());
 }
示例#38
0
            private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request)
            {
                Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue");
                VerboseTrace("Type: " + request.Type, easy: request.Easy);

                EasyRequest easy = request.Easy;
                switch (request.Type)
                {
                    case IncomingRequestType.New:
                        ActivateNewRequest(multiHandle, easy);
                        break;

                    case IncomingRequestType.Cancel:
                        Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests");
                        Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested");
                        FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken));
                        break;

                    case IncomingRequestType.Unpause:
                        Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests");
                        if (!easy._easyHandle.IsClosed)
                        {
                            IntPtr gcHandlePtr;
                            ActiveRequest ar;
                            Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause");
                            Debug.Assert(easy._paused == EasyRequest.PauseState.UnpauseRequestIssued, "Unpause requests only make sense when a request has been issued");

                            easy._paused = EasyRequest.PauseState.Unpaused;
                            int unpauseResult = Interop.libcurl.curl_easy_pause(easy._easyHandle, Interop.libcurl.CURLPAUSE_CONT);
                            if (unpauseResult != CURLcode.CURLE_OK)
                            {
                                FindAndFailActiveRequest(multiHandle, easy, new CurlException(unpauseResult, isMulti: false));
                            }
                        }
                        break;

                    default:
                        Debug.Fail("Invalid request type: " + request.Type);
                        break;
                }
            }
 public bool can_handle(IncomingRequest request)
 {
     return request_specification.is_satisfied_by(request);
 }
 public void process(IncomingRequest request)
 {
     shopping_tasks.add_to_shopping_cart(request.map<ItemToAddToCartDetails>());
 }
 public bool can_handle(IncomingRequest request)
 {
     throw new NotImplementedException();
 }
 public void process(IncomingRequest request)
 {
     display_engine.display(catalog_tasks.get_all_products_in(request.map<Id<long>>()));
 }
 public void process(IncomingRequest request)
 {
     throw new NotImplementedException();
 }