Beispiel #1
0
 public ConnectionControllerManager(Configuration configuration,
                                    ReceiveRequest<RequestPacket, ResponsePacket> connectionRequestDelegate,
                                    ReceiveRequest<RequestPacket, ResponsePacket> peerCoordinationDelegate)
 {
     _configuration = configuration;
     _connectionRequestPort = new OneShotServerPort<RequestPacket, ResponsePacket>(configuration.ServerAddress,
         configuration.ConnectionRequestLocalPort);
     _peerCoordinationPort = new OneShotServerPort<RequestPacket, ResponsePacket>(configuration.ServerAddress,
         configuration.PeerCoordinationLocalPort);
     _connectionRequestPort.RegisterReceiveRequestDelegate(connectionRequestDelegate);
     _peerCoordinationPort.RegisterReceiveRequestDelegate(peerCoordinationDelegate);
 }
        public async void DoesNotThrowExceptionIfReceiveRequestIsNull()
        {
            // Arrange
            var            handler     = new StreamingRequestHandler(new MockBot(), new BotFrameworkHttpAdapter(), Guid.NewGuid().ToString());
            ReceiveRequest testRequest = null;

            // Act
            var response = await handler.ProcessRequestAsync(testRequest);

            // Assert
            Assert.Equal(400, response.StatusCode);
        }
Beispiel #3
0
        private void ProcessRequest(Guid id, ReceiveRequest request)
        {
            _ = Task.Run(async() =>
            {
                var streamingResponse = await _receiver.ProcessRequestAsync(request, null).ConfigureAwait(false);
                await SendResponseAsync(new Header()
                {
                    Id = id, Type = PayloadTypes.Response
                }, streamingResponse, _connectionCancellationToken).ConfigureAwait(false);

                request.Streams.ForEach(s => _streamDefinitions.Remove(s.Id));
            });
        }
Beispiel #4
0
            protected override void Execute(CodeActivityContext context)
            {
                IOperationActivity receiveRequest = ReceiveRequest.Get(context);
                Type workflowInterfaceType        = WorkflowInterfaceType.Get(context);
                Type requestResultType            = RequestResultType.Get(context);
                Type responseParameterType        = ResponseParameterType.Get(context);

                if (receiveRequest != null && workflowInterfaceType != null && requestResultType != null && responseParameterType != null)
                {
                    receiveRequest.OperationNames.Set(
                        typeof(WorkflowInterfaceInfo <>).MakeGenericType(workflowInterfaceType)
                        .GetMethod(nameof(WorkflowInterfaceInfo <object> .GetOperationNames)).Invoke(null, new object[] { requestResultType, responseParameterType }) as IEnumerable <string>);
                }
            }
Beispiel #5
0
        private static async Task <T> ReadOptionalBodyAsJson <T>(ReceiveRequest request)
        {
            // The first stream attached to a ReceiveRequest is always the ReceiveRequest body.
            // Any additional streams must be defined within the body or they will not be
            // attached properly when processing activities.
            var contentStream = request.Streams.FirstOrDefault();

            if (contentStream != null)
            {
                var contentString = await ReadBuffer(contentStream).ConfigureAwait(false);

                return(JsonConvert.DeserializeObject <T>(contentString));
            }
            return(default(T));
        }
        public void SerializeToJson_ShouldReturnCorrectReceiveJson_IfSerializationIsCorrect()
        {
            // Arrange
            ReceiveRequest request = new ReceiveRequest()
            {
                MessageIndex = 2,
                UserId       = "maria"
            };

            // Act
            string serializedRequest = request.SerializeToJson();

            // Assert
            Assert.AreEqual(serializedRequest, "{\"cmd\":\"receber\",\"id\":\"maria\",\"msgNr\":2}");
        }
Beispiel #7
0
        //private MPI.Intercommunicator channel;

        private RequestList synchronize_action(object action_id)
        {
            Console.WriteLine("ActionDef.action_ids.Count = " + ActionDef.action_ids.Count);

            int         value        = ActionDef.action_ids[action_id];
            RequestList request_list = new RequestList();

            Trace.WriteLineIf(this.TraceFlag == true, this.ThisFacetInstance + "/" + this.Rank + ": synchronize_action " + action_id + " -1");

            Trace.WriteLineIf(this.TraceFlag == true, this.ThisFacetInstance + "/" + this.Rank + ": synchronize_action " + action_id + " 0");

            foreach (KeyValuePair <int, IDictionary <string, int> > facet in Channel.UnitSizeInFacet)
            {
                if (facet.Key != this.ThisFacetInstance)
                {
                    foreach (KeyValuePair <string, int> unit_team in facet.Value)
                    {
                        for (int i = 0; i < unit_team.Value; i++)
                        {
                            Trace.WriteLineIf(this.TraceFlag == true, "synchronize_action " + action_id + " LOOP SEND " + facet.Key + "/" + i);
                            Request req = Channel.ImmediateSend <object> (value, new Tuple <int, int> (facet.Key, i), value);
                            request_list.Add(req);
                        }
                    }
                }
            }

            Trace.WriteLineIf(this.TraceFlag == true, this.ThisFacetInstance + "/" + this.Rank + ": synchronize_action " + action_id + " 1");

            foreach (KeyValuePair <int, IDictionary <string, int> > facet in Channel.UnitSizeInFacet)
            {
                if (facet.Key != this.ThisFacetInstance)
                {
                    foreach (KeyValuePair <string, int> unit_team in facet.Value)
                    {
                        for (int i = 0; i < unit_team.Value; i++)
                        {
                            Trace.WriteLineIf(this.TraceFlag == true, "synchronize_action " + action_id + " LOOP RECV " + facet.Key + "/" + i);
                            ReceiveRequest req = Channel.ImmediateReceive <object> (new Tuple <int, int> (facet.Key, i), value);
                            request_list.Add(req);
                        }
                    }
                }
            }

            Trace.WriteLineIf(this.TraceFlag == true, this.ThisFacetInstance + "/" + this.Rank + ": synchronize_action " + action_id + " 2");
            return(request_list);
        }
Beispiel #8
0
 public RoutingControllerManager(Configuration configuration,
                                 ReceiveRequest <RequestPacket, ResponsePacket> routeTableQueryDelegate,
                                 ReceiveRequest <RequestPacket, ResponsePacket> localTopologyDelegate,
                                 ReceiveRequest <RequestPacket, ResponsePacket> networkTopologyDelegate)
 {
     _configuration       = configuration;
     _routeTableQueryPort = new OneShotServerPort <RequestPacket, ResponsePacket>(configuration.ServerAddress,
                                                                                  configuration.RouteTableQueryLocalPort);
     _localTopologyPort = new OneShotServerPort <RequestPacket, ResponsePacket>(configuration.ServerAddress,
                                                                                configuration.LocalTopologyLocalPort);
     _networkTopologyPort = new OneShotServerPort <RequestPacket, ResponsePacket>(configuration.ServerAddress,
                                                                                  configuration.NetworkTopologyLocalPort);
     _routeTableQueryPort.RegisterReceiveRequestDelegate(routeTableQueryDelegate);
     _localTopologyPort.RegisterReceiveRequestDelegate(localTopologyDelegate);
     _networkTopologyPort.RegisterReceiveRequestDelegate(networkTopologyDelegate);
 }
        /// <summary>
        ///     Implements transaction for Send
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns>Transaction result</returns>
        public override ITransactionResult Transaction(object parameters)
        {
            var sendParameters = (SendParameters)parameters;

            TestConfig.TestSettings = new IntegrationTestSettingsModel {
                AcEnvironment = sendParameters.Environment
            };

            var amtRangeParsed       = Enum.TryParse(sendParameters?.AmtRange, true, out AmountRange amtRange);
            var itemChoiceTypeParsed = Enum.TryParse(sendParameters?.FeeType, true, out ItemChoiceType1 itemChoiceType);
            var sendRequest          = new SendRequest
            {
                Environment         = sendParameters.Environment,
                AgentCountryIsoCode = sendParameters.AgentCountryIsoCode,
                AgentId             = sendParameters.AgentId,
                AgentPos            = sendParameters.AgentPos,
                AgentState          = sendParameters.GetAgentState(),
                Amount         = (double)sendParameters.CustomAmount,
                AmtRange       = amtRangeParsed ? amtRange : AmountRange.CustomAmount,
                Country        = sendParameters.Country,
                State          = sendParameters.State,
                FeeType        = itemChoiceTypeParsed ? itemChoiceType : ItemChoiceType1.amountExcludingFee,
                SendCurr       = sendParameters.SendCurr,
                ServiceOption  = sendParameters.ServiceOption,
                ThirdPartyType = sendParameters.ThirdPartyType
            };
            var receiveAgentState = sendParameters.State.Split('-')[1];
            var receiveRequest    = new ReceiveRequest
            {
                AgentState     = receiveAgentState,
                ThirdPartyType = sendParameters.ThirdPartyType
            };

            var sendData = new SendData(sendRequest);

            sendData = SendOperations.SendCompleteForNewCustomer(sendData);

            var receiveData = new ReceiveData(receiveRequest);

            receiveData.Set(sendData);
            receiveData = ReceiveOperations.ReceiveCompleteStaged(receiveData);

            return(new TransactionResult {
                Result = receiveData
            });
        }
Beispiel #10
0
        public static ReceiveResponse GetPendingMessages(ReceiveRequest request)
        {
            ReceiveResponse response = new ReceiveResponse();

            // Get pending messages for this user:
            response.Data          = new PendingMessages();
            response.Data.Messages = new List <PendingMessage>();
            response.Data.Messages.AddRange(AsyncListener.PendingMessages
                                            .Where(m => m.DestinationUserId == request.UserId)
                                            .ToPendingMessages());
            response.UserId = "0";

            // Remove pending messages from buffer:
            AsyncListener.PendingMessages.RemoveAll(m => m.DestinationUserId == request.UserId);

            return(response);
        }
        public void ReceiveReversalTransaction_ShouldFailForNonReceivingAgent()
        {
            var sendRequest = new SendRequest
            {
                AgentState    = AgentLocation.MN,
                Country       = Country.Usa,
                State         = State.Ny,
                SendCurr      = Currency.Usd,
                AmtRange      = AmountRange.NoIdsNoThirdParty,
                FeeType       = ItemChoiceType1.amountExcludingFee,
                ServiceOption = ServiceOptionType.WillCall
            };

            sendRequest.PopulateAgentData(sendRequest.AgentState);
            var sendData       = new SendData(sendRequest);
            var receiveRequest = new ReceiveRequest
            {
                AgentState     = AgentLocation.NY,
                ThirdPartyType = TestThirdPartyType.None
            };

            receiveRequest.PopulateAgentData(receiveRequest.AgentState);

            var receiveData = new ReceiveData(receiveRequest);

            sendData = _sendOperations.SendCompleteForExistingCustomer(sendData);
            receiveData.Set(sendData);
            _recvOperations.ReceiveComplete(receiveData);

            var request = new ReceiveReversalOperationRequest
            {
                AgentState      = AgentLocation.MN,
                ReferenceNumber = receiveData.SendData.CompleteSessionResp.Payload.ReferenceNumber
            };

            request.PopulateAgentData(request.AgentState);

            var receiveReversalData = receiveReversalOperations.SingleValidate(request);

            Assert.IsFalse(receiveReversalData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{receiveReversalData.Errors?.Log()}");

            var lastValidationResponse = receiveReversalData.ValidationResponses.LastOrDefault();

            Assert.IsTrue(lastValidationResponse.Errors.Any());
        }
        public void ReceiveReversalTransaction_Complete()
        {
            var sendRequest = new SendRequest
            {
                AgentState    = AgentLocation.MN,
                Country       = Country.Usa,
                State         = State.Ny,
                SendCurr      = Currency.Usd,
                AmtRange      = AmountRange.UnderOneHundred,
                FeeType       = ItemChoiceType1.amountExcludingFee,
                ServiceOption = ServiceOptionType.WillCall
            };

            sendRequest.PopulateAgentData(sendRequest.AgentState);
            var sendData       = new SendData(sendRequest);
            var receiveRequest = new ReceiveRequest
            {
                AgentState     = AgentLocation.NY,
                ThirdPartyType = TestThirdPartyType.None
            };

            receiveRequest.PopulateAgentData(receiveRequest.AgentState);

            var receiveData = new ReceiveData(receiveRequest);

            sendData = _sendOperations.SendCompleteForExistingCustomer(sendData);
            receiveData.Set(sendData);
            _recvOperations.ReceiveComplete(receiveData);

            //Get the transaction reference number

            var request = new ReceiveReversalOperationRequest
            {
                AgentState      = AgentLocation.NY,
                ReferenceNumber = receiveData.SendData.CompleteSessionResp.Payload.ReferenceNumber
            };

            request.PopulateAgentData(request.AgentState);

            var receiveReversalData = receiveReversalOperations.ReceiveReversalComplete(request);

            Assert.IsFalse(receiveReversalData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{receiveReversalData.Errors?.Log()}");
            //Commented out as CompleteSessionResponse does not contain reference number when performing Receive Reversal. The above check for errors is enough.
            //Assert.IsFalse(string.IsNullOrEmpty(receiveReversalData.CompleteSessionResp.Payload.ReferenceNumber), "there was no reference number on the receive reversal completion response");
        }
Beispiel #13
0
        public void DeserializeFromJson_ShouldReturnCorrectReceiveJson_IfSerializationIsCorrect()
        {
            // Arrange
            ReceiveRequest expectedRequest = new ReceiveRequest()
            {
                MessageIndex = 1,
                UserId       = "maria"
            };
            string json = expectedRequest.SerializeToJson();

            // Act
            ReceiveRequest deserializedRequest = json.DeserializeFromJson <ReceiveRequest>();

            // Assert
            Assert.AreEqual(deserializedRequest.CommandName, expectedRequest.CommandName);
            Assert.AreEqual(deserializedRequest.MessageIndex, expectedRequest.MessageIndex);
            Assert.AreEqual(deserializedRequest.UserId, expectedRequest.UserId);
        }
Beispiel #14
0
 public NetworkCallControllerManager(Configuration configuration,
                                     ReceiveRequest <RequestPacket, ResponsePacket> callCoordinationPortDelegate,
                                     ReceiveRequest <RequestPacket, ResponsePacket> callTeardownPortDelegate,
                                     ReceiveRequest <RequestPacket, ResponsePacket> connectionRequestPortDelegate)
 {
     _configuration        = configuration;
     _clientPortAliases    = _configuration.ClientPortAliases;
     _portDomains          = _configuration.PortDomains;
     _domain               = _configuration.Domain;
     _callCoordinationPort = new OneShotServerPort <RequestPacket, ResponsePacket>(_configuration.ServerAddress,
                                                                                   _configuration.CallCoordinationLocalPort);
     _callTeardownPort = new OneShotServerPort <RequestPacket, ResponsePacket>(_configuration.ServerAddress,
                                                                               _configuration.CallTeardownLocalPort);
     _connectionRequestPort = new OneShotServerPort <RequestPacket, ResponsePacket>(_configuration.ServerAddress,
                                                                                    _configuration.ConnectionRequestLocalPort);
     _callCoordinationPort.RegisterReceiveRequestDelegate(callCoordinationPortDelegate);
     _callTeardownPort.RegisterReceiveRequestDelegate(callTeardownPortDelegate);
     _connectionRequestPort.RegisterReceiveRequestDelegate(connectionRequestPortDelegate);
 }
Beispiel #15
0
        public override async Task <StreamingResponse> ProcessRequestAsync(ReceiveRequest request, ILogger <RequestHandler> logger, object context = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (request.Verb == "POST" && request.Path == _postActivitiesPath)
            {
                var activitySet = await ReadOptionalBodyAsJson <ActivitySet>(request).ConfigureAwait(false);

                if (request.Streams.Count > 1)
                {
                    var attachmentDictionary           = request.Streams.Skip(1).ToDictionary(a => a.Id);
                    int streamsMappedtoActivitiesCount = 0;
                    foreach (var activity in activitySet.Activities)
                    {
                        if (activity.Attachments == null || activity.Attachments.Count == 0)
                        {
                            continue;
                        }

                        for (int i = 0; i < activity.Attachments.Count(); i++)
                        {
                            if (string.Equals(activity.Attachments[i].ContentType, "bf-stream", StringComparison.InvariantCultureIgnoreCase))
                            {
                                var id     = Guid.Parse(activity.Attachments[i].Content.ToString());
                                var stream = attachmentDictionary[id];
                                activity.Attachments[i] = new Attachment()
                                {
                                    ContentType = stream.ContentType, Content = stream.Stream
                                };
                                streamsMappedtoActivitiesCount++;
                            }
                        }

                        if (streamsMappedtoActivitiesCount == request.Streams.Count - 1)
                        {
                            break;
                        }
                    }
                }

                _receiveActivities(activitySet);
                return(StreamingResponse.OK());
            }
            return(StreamingResponse.NotFound());
        }
Beispiel #16
0
        /// <summary>
        /// Method that receives messages
        /// </summary>
        private void ReceiveMessages()
        {
            while (ContinueExecution)
            {
                // Receive next message and handle it
                ReceiveRequest asyncReceive = null;
                lock (comm)
                {
                    // starts an asynchronous receive of the next message
                    // Note: Must be asynchronous otherwise the lock of the comm object may cause a dead lock (unable to send message because we are waiting for one)
                    asyncReceive = comm.ImmediateReceive <Message>(Communicator.anySource, 0);
                }

                // Creates a task that waits for the result to arrive.
                // Note : We must use a task because the Wait function of a task allows for a timeout parameter which we need to validate if the execution is still ongoing
                Task waitForMessage = new Task(() =>
                {
                    asyncReceive.Wait();
                });
                waitForMessage.Start();

                // waits for a message to be received, stops (within 200ms) if the execution stops
                while (ContinueExecution && !waitForMessage.Wait(200))
                {
                    ;
                }

                if (!ContinueExecution)
                {
                    asyncReceive.Cancel();
                    // We need to wait for the asyncReceive cancellation because the completion of this thread will close MPI but we need to make sure the cancel is over by then.
                    asyncReceive.Wait();

                    break; // if the execution is over, the message may not be valid and should be ignored.
                }

                messageQueue.Add((Message)asyncReceive.GetValue());
            }

            // Signal the main MapManager thread that this thread is correctly closed and we won't receive any other messages
            messageQueue.CompleteAdding();
        }
        public async void DoesNotThrowExceptionIfReceiveRequestHasNoActivity()
        {
            // Arrange
            var handler = new StreamingRequestHandler(new MockBot(), new BotFrameworkHttpAdapter(), Guid.NewGuid().ToString());

            var payload             = new MemoryStream();
            var fakeContentStreamId = Guid.NewGuid();
            var fakeContentStream   = new FakeContentStream(fakeContentStreamId, "application/json", payload);
            var testRequest         = new ReceiveRequest
            {
                Verb = "POST",
            };

            testRequest.Streams.Add(fakeContentStream);

            // Act
            var response = await handler.ProcessRequestAsync(testRequest);

            // Assert
            Assert.Equal(400, response.StatusCode);
        }
        private async Task ProcessRequest(Stream stream)
        {
            using (var textReader = new StreamReader(stream))
            {
                using (var jsonReader = new JsonTextReader(textReader))
                {
                    var requestPayload = Serializer.Deserialize <RequestPayload>(jsonReader);

                    var request = new ReceiveRequest()
                    {
                        Verb    = requestPayload.Verb,
                        Path    = requestPayload.Path,
                        Streams = new List <IContentStream>(),
                    };

                    if (requestPayload.Streams != null)
                    {
                        foreach (var streamDescription in requestPayload.Streams)
                        {
                            if (!Guid.TryParse(streamDescription.Id, out Guid id))
                            {
                                throw new InvalidDataException($"Stream description id '{streamDescription.Id}' is not a Guid");
                            }

                            var streamAssembler = _streamManager.GetPayloadAssembler(id);
                            streamAssembler.ContentType   = streamDescription.ContentType;
                            streamAssembler.ContentLength = streamDescription.Length;

                            request.Streams.Add(new ContentStream(id, streamAssembler)
                            {
                                Length      = streamDescription.Length,
                                ContentType = streamDescription.ContentType,
                            });
                        }
                    }

                    await _onCompleted(this.Id, request).ConfigureAwait(false);
                }
            }
        }
        public override async Task <Response> ProcessRequestAsync(ReceiveRequest request)
        {
            var response = new Response();

            var body = request.ReadBodyAsString().Result;

            if (string.IsNullOrEmpty(body))
            {
                response.StatusCode = 400;
                return(response);
            }

            try
            {
                var activity       = JsonConvert.DeserializeObject <Activity>(body, SerializationSettings.DefaultDeserializationSettings);
                var invokeResponse = await this.StreamingAdapter.ProcessActivityAsync(activity, new BotCallbackHandler(this.Bot.OnTurnAsync), CancellationToken.None).ConfigureAwait(false);

                if (invokeResponse == null)
                {
                    response.StatusCode = 200;
                }
                else
                {
                    response.StatusCode = invokeResponse.Status;
                    if (invokeResponse.Body != null)
                    {
                        response.SetBody(invokeResponse.Body);
                    }
                }

                invokeResponse = (InvokeResponse)null;
            }
            catch (Exception)
            {
                // TODO: Better exception handling.
                response.StatusCode = 403;
            }

            return(response);
        }
        private async Task <StreamingResponse> ProcessRequest(ReceiveRequest request)
        {
            StreamingResponse response = null;

            if (!_responses.TryGetValue(GetRequestKey(request), out PendingRequest pendingRequest))
            {
                response = new StreamingResponse()
                {
                    StatusCode = 500,
                };
            }
            else
            {
                response = pendingRequest.Response;
                if (pendingRequest.ValidateRequest != null)
                {
                    await pendingRequest.ValidateRequest(request);
                }
            }

            return(response);
        }
Beispiel #21
0
        public void Recv_ThirdParty_Org_Complete()
        {
            var sendRequest = new SendRequest
            {
                AgentState     = AgentLocation.MN,
                Country        = Country.Usa,
                State          = State.Ny,
                SendCurr       = Currency.Usd,
                AmtRange       = AmountRange.ThirdParty,
                FeeType        = ItemChoiceType1.amountExcludingFee,
                ServiceOption  = ServiceOptionType.WillCall,
                ThirdPartyType = TestThirdPartyType.Org
            };

            sendRequest.PopulateAgentData(sendRequest.AgentState);

            var sendData = new SendData(sendRequest);

            sendData = SendOperations.SendCompleteForThirdParty(sendData);
            var receiveRequest = new ReceiveRequest
            {
                AgentState     = AgentLocation.NY,
                ThirdPartyType = TestThirdPartyType.Org
            };

            receiveRequest.PopulateAgentData(receiveRequest.AgentState);

            var receiveData = new ReceiveData(receiveRequest);

            receiveData.Set(sendData);

            receiveData = ReceiveOperations.ReceiveComplete(receiveData);
            var transLookupResponse = TranLookupOperations.TransactionLookupForStatus(receiveRequest.AgentId, receiveRequest.AgentPos, receiveData.SendData.CompleteSessionResp.Payload.ReferenceNumber);

            // ASSERT ALL THE THINGS
            Assert.IsFalse(sendData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{sendData.Errors?.Log()}");
            Assert.IsFalse(receiveData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{sendData.Errors?.Log()}");
            Assert.IsTrue(transLookupResponse.TransactionLookupResp.Payload.TransactionStatus == TransactionStatusType.RECVD);
        }
        public override async Task <StreamingResponse> ProcessRequestAsync(ReceiveRequest request, ILogger <RequestHandler> logger = null, object context = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (request.Verb == "POST")
            {
                var firstActivity = request.ReadBodyAsJson <Activity>();

                if (request.Streams.Count > 1)
                {
                    if (firstActivity == null)
                    {
                        throw new InvalidOperationException("Attachment streams received with activity set, but no activities present in activity set.");
                    }

                    var streamAttachments = new List <Attachment>();
                    for (int i = 1; i < request.Streams.Count; i++)
                    {
                        var stream = request.Streams[i].Stream;
                        streamAttachments.Add(new Attachment()
                        {
                            ContentType = request.Streams[i].ContentType, Content = request.Streams[i].Stream
                        });
                    }

                    if (firstActivity.Attachments != null)
                    {
                        firstActivity.Attachments = firstActivity.Attachments.Concat(streamAttachments).ToArray();
                    }
                    else
                    {
                        firstActivity.Attachments = streamAttachments.ToArray();
                    }
                }

                _receiveActivities(firstActivity);

                return(StreamingResponse.OK());
            }
            return(StreamingResponse.NotFound());
        }
Beispiel #23
0
        public override async Task <Response> ProcessRequestAsync(ReceiveRequest request, object context = null, ILogger <RequestHandler> logger = null)
        {
            var routeContext = _router.Route(request);

            if (routeContext != null)
            {
                try
                {
                    var responseBody = await routeContext.Action.Action(request, routeContext.RouteData).ConfigureAwait(false);

                    return(Response.OK(new StringContent(JsonConvert.SerializeObject(responseBody, SerializationSettings.DefaultSerializationSettings), Encoding.UTF8, SerializationSettings.ApplicationJson)));
                }
                catch
                {
                    return(Response.InternalServerError());
                }
            }
            else
            {
                return(Response.NotFound());
            }
        }
        public async Task RequestHandlerForgetsConversations()
        {
            // Arrange
            var handler        = new StreamingRequestHandler(new MockBot(), new BotFrameworkHttpAdapter(), "fakePipe");
            var conversationId = "testconvoid";
            var membersAdded   = new List <ChannelAccount>();
            var member         = new ChannelAccount
            {
                Id   = "123",
                Name = "bot",
            };

            membersAdded.Add(member);
            var activity = new Activity()
            {
                Type         = "conversationUpdate",
                MembersAdded = membersAdded,
                Conversation = new ConversationAccount(null, null, conversationId, null, null, null, null),
            };

            var payload             = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(activity, SerializationSettings.DefaultDeserializationSettings)));
            var fakeContentStreamId = Guid.NewGuid();
            var fakeContentStream   = new FakeContentStream(fakeContentStreamId, "application/json", payload);
            var testRequest         = new ReceiveRequest
            {
                Path = $"/v3/conversations/{activity.Conversation?.Id}/activities/{activity.Id}",
                Verb = "POST",
            };

            testRequest.Streams.Add(fakeContentStream);

            // Act
            _ = await handler.ProcessRequestAsync(testRequest);

            handler.ForgetConversation(conversationId);

            // Assert
            Assert.False(handler.HasConversation(conversationId));
        }
        public void ReceiveExtensions_ReadBodyAsJson_Streams()
        {
            var activity = new Activity {
                Type = ActivityTypes.Message
            };
            var stringInput       = JsonConvert.SerializeObject(activity);
            var stream            = new MemoryStream(Encoding.UTF8.GetBytes(stringInput));
            var mockContentStream = new Mock <IContentStream>();

            mockContentStream.Setup(e => e.Stream).Returns(stream);

            var request = new ReceiveRequest
            {
                Streams = new List <IContentStream> {
                    mockContentStream.Object
                }
            };
            var result = request.ReadBodyAsJson <Activity>();

            Assert.NotNull(result);
            Assert.Equal(activity.Type, result.Type);
        }
Beispiel #26
0
        public async void RequestHandlerAssignsAServiceUrl()
        {
            // Arrange
            var handler        = new StreamingRequestHandler(new MockBot(), new BotFrameworkHttpAdapter(), Guid.NewGuid().ToString());
            var conversationId = Guid.NewGuid().ToString();
            var serviceUrl     = "urn:FakeName:fakeProtocol://fakePath";
            var membersAdded   = new List <ChannelAccount>();
            var member         = new ChannelAccount
            {
                Id   = "123",
                Name = "bot",
            };

            membersAdded.Add(member);
            var activity = new Activity()
            {
                ServiceUrl   = serviceUrl,
                Type         = "conversationUpdate",
                MembersAdded = membersAdded,
                Conversation = new ConversationAccount(null, null, conversationId, null, null, null, null),
            };

            var payload             = new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(activity, SerializationSettings.DefaultDeserializationSettings)));
            var fakeContentStreamId = Guid.NewGuid();
            var fakeContentStream   = new FakeContentStream(fakeContentStreamId, "application/json", payload);
            var testRequest         = new ReceiveRequest
            {
                Path = $"/v3/conversations/{activity.Conversation?.Id}/activities/{activity.Id}",
                Verb = "POST",
            };

            testRequest.Streams.Add(fakeContentStream);

            // Act
            _ = await handler.ProcessRequestAsync(testRequest);

            // Assert
            Assert.Equal(serviceUrl, handler.ServiceUrl);
        }
Beispiel #27
0
        public void ReceivedRequests()
        {
            GlobalDefinitions.wait(60);


            Actions builder = new Actions(Global.GlobalDefinitions.driver);

            builder.MoveToElement(ClickManageRequests).Build().Perform();
            ClickManageRequests.Click();

            GlobalDefinitions.wait(60);

            WebDriverWait wait = new WebDriverWait(GlobalDefinitions.driver, TimeSpan.FromSeconds(60));

            wait.Until(ExpectedConditions.ElementToBeClickable(ReceiveRequest));

            ReceiveRequest.Click();

            Assert.That(ReceivedTitle.Text, Is.EqualTo("Received Requests"));

            Base.test.Log(LogStatus.Info, "Sucessully in Received Requests Page");
        }
Beispiel #28
0
        public Task<int> ReceiveAsync(byte[] buffer)
        {
            this.ThrowIfDisposed();
            Task<int> resultTask;

            ReceiveRequest requestResult = null;
            lock (this.excessBuffers)
            {
                if (this.pendingReceiveRequest != null)
                {
                    throw new InvalidOperationException("A receive operation is already in progress");
                }

                this.pendingReceiveRequest = new ReceiveRequest(buffer);
                resultTask = this.pendingReceiveRequest.ReceiveTask;

                bool dataSend = this.SendDataToReceiver();

                if (dataSend)
                {
                    requestResult = this.pendingReceiveRequest;

                    /* due to the synchronous continuation execution after SetResult to the pendingReceive task
                     * the SetResult must be after null assignment to this.pendingReceiveRequest
                     * otherwise, the conitnuation task might execute before null assignment to this.pendingReceiveRequest
                     */
                    this.pendingReceiveRequest = null;
                }
            }

            // to prevent deadlocks, you should generally avoid running arbitrary user code such as event handlers or in this case, continuations (invoked by SetResult), under a lock
            if (requestResult != null)
            {
                requestResult.CompleteRequest();
            }

            return resultTask;
        }
Beispiel #29
0
        public void Recv_StageReceive_SmallAmount_NewCustomer()
        {
            var sendRequest = new SendRequest
            {
                AgentState     = AgentLocation.MN,
                Country        = Country.Usa,
                State          = State.Ny,
                SendCurr       = Currency.Usd,
                AmtRange       = AmountRange.UnderOneHundred,
                FeeType        = ItemChoiceType1.amountExcludingFee,
                ThirdPartyType = TestThirdPartyType.None
            };

            sendRequest.PopulateAgentData(sendRequest.AgentState);

            var sendData = new SendData(sendRequest);

            sendData = SendOperations.SendCompleteForNewCustomer(sendData);
            var receiveRequest = new ReceiveRequest()
            {
                AgentState     = AgentLocation.NY,
                ThirdPartyType = TestThirdPartyType.None
            };

            receiveRequest.PopulateAgentData(receiveRequest.AgentState);
            var receiveData = new ReceiveData(receiveRequest);

            receiveData.Set(sendData);

            receiveData = ReceiveOperations.ReceiveCompleteStaged(receiveData);
            receiveData = ReceiveOperations.TransactionLookupForReceiveCompletion(receiveData);

            // ASSERT ALL THE THINGS
            Assert.IsFalse(sendData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{sendData.Errors?.Log()}");
            Assert.IsFalse(receiveData.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{sendData.Errors?.Log()}");
            Assert.IsFalse(receiveData.TransactionLookupResponse.Errors.Any(), $" {Environment.NewLine}Errors: {Environment.NewLine}{receiveData.TransactionLookupResponse.Errors?.Log()}");
            Assert.IsTrue(receiveData.TransactionLookupResponse.Payload.TransactionStatus == TransactionStatusType.AVAIL);
        }
Beispiel #30
0
        public Task <int> ReceiveAsync(byte[] buffer)
        {
            Task <int>     task;
            ReceiveRequest receiveToComplete = null;

            lock (this.excessBuffers)
            {
                this.ThrowIfDisposed();
                if (this.pendingReceive != null)
                {
                    throw new InvalidOperationException("A receive operation is already in progress.");
                }

                this.pendingReceive = new ReceiveRequest(buffer);
                task = this.pendingReceive.Task;

                while ((this.excessBuffers.Count > 0) && (this.pendingReceive.RemainingBytes > 0))
                {
                    receiveToComplete = this.pendingReceive;
                    byte[] excess = this.excessBuffers.First.Value;
                    this.excessBuffers.RemoveFirst();
                    int bytesReceived = this.pendingReceive.AddData(excess);
                    this.AddExcess(excess, bytesReceived, true);
                }

                if (receiveToComplete != null)
                {
                    this.pendingReceive = null;
                }
            }

            if (receiveToComplete != null)
            {
                receiveToComplete.Complete();
            }

            return(task);
        }
Beispiel #31
0
        public override async Task <StreamingResponse> ProcessRequestAsync(ReceiveRequest request, ILogger <RequestHandler> logger, object context = null, CancellationToken cancellationToken = default)
        {
            var routeContext = _router.Route(request);

            if (routeContext != null)
            {
                try
                {
                    var responseBody = await routeContext.Action.Action(request, routeContext.RouteData).ConfigureAwait(false);

                    return(StreamingResponse.OK(new StringContent(JsonConvert.SerializeObject(responseBody, SerializationSettings.DefaultSerializationSettings), Encoding.UTF8, SerializationSettings.ApplicationJson)));
                }
                catch (Exception ex)
                {
                    _botTelemetryClient.TrackException(ex);
                    return(StreamingResponse.InternalServerError());
                }
            }
            else
            {
                return(StreamingResponse.NotFound());
            }
        }
Beispiel #32
0
        public void Send(byte[] buffer)
        {
            this.ThrowIfDisposed();

            ReceiveRequest requestResult = null;
            lock (this.excessBuffers)
            {
                this.excessBuffers = this.excessBuffers.Concat(buffer).ToList();

                if (this.pendingReceiveRequest != null)
                {
                    bool dataSend = this.SendDataToReceiver();

                    if (dataSend)
                    {
                        requestResult = this.pendingReceiveRequest;

                        /* due to the synchronous continuation execution after SetResult to the pendingReceive task
                         * the SetResult must be after null assignment to this.pendingReceiveRequest
                         * otherwise, the conitnuation task might execute before null assignment to this.pendingReceiveRequest
                         */
                        this.pendingReceiveRequest = null;
                    }
                }
            }

            // to prevent deadlocks, you should generally avoid running arbitrary user code such as event handlers or in this case, continuations (invoked by SetResult), under a lock
            if (requestResult != null)
            {
                requestResult.CompleteRequest();
            }
        }
        static void Main(string[] args)
        {
            using (new MPI.Environment(ref args))
            {
                if (args.Length != 1)
                {
                    return;
                }

                const int matrixSize = 50;
                Intracommunicator comm = Communicator.world;
                int groupCount = int.Parse(args[0]);

                if (comm.Rank == 0)
                {
                    DateTime startTime = DateTime.Now;
                    MatrixMultiply testMultiply = new MatrixMultiply(comm.Size, matrixSize);
                    Matrix result = testMultiply.MultiplyForRank(0);
                    for (int i = 1; i < comm.Size; i++)
                    {
                        result.Append(testMultiply.MultiplyForRank(i));
                    }

                    DateTime endTime = DateTime.Now;
                    Console.WriteLine("Test multiply" + (startTime - endTime).ToString());

                    int workers = comm.Size - groupCount - 1;
                    Console.WriteLine("All process count: " + (comm.Size).ToString());
                    Console.WriteLine("Workers count: " + (workers + groupCount).ToString());
                    Console.WriteLine("Group count" + (groupCount).ToString());

                    int workerIndex = groupCount + 1;
                    int managersWithoutWorkers = groupCount;

                    Request[] sendRequest = new Request[groupCount];
                    for (int i = 0; i < groupCount; i++)
                    {
                        int workersIntheGroup = (int)Math.Floor((double)(workers / managersWithoutWorkers));
                        MatrixMultiply mp = new MatrixMultiply(workersIntheGroup + 1, matrixSize)
                            {
                                WorkersList = new List<int>(),
                                IsAManager = true
                            };

                        for (int j = 0; j < workersIntheGroup; j++)
                        {
                            mp.WorkersList.Add(workerIndex);
                            // Console.WriteLine("WorkerID " + workerIndex);
                            workerIndex++;
                            workers--;
                        }
                        managersWithoutWorkers--;
                        Console.WriteLine("Group " + i.ToString() + " has " + (workersIntheGroup + 1).ToString() + "members");
                        sendRequest[i] = comm.ImmediateSend(mp, i + 1, 0);
                    }

                    Console.WriteLine("Sending the job");

                    for (int i = 0; i < groupCount; i++)
                    {
                        sendRequest[i].Wait();
                    }

                    ReceiveRequest[] recieveRequest = new ReceiveRequest[groupCount];

                    for (int i = 0; i < groupCount; i++)
                    {
                        recieveRequest[i] = comm.ImmediateReceive<Matrix>(i + 1, 0);
                    }
                    Console.WriteLine("Recieve results");
                    for (int i = 0; i < groupCount; i++)
                    {
                        recieveRequest[i].Wait();
                    }
                    //for (int i = 0; i < groupCount; i++)
                    //    {
                    //    var result = recieveRequest[i].GetValue();
                    //    if(result == null)
                    //        {
                    //        Console.WriteLine("Null get");
                    //        }
                    //    Console.WriteLine("Group " + i + " has finished in " + ((TimeSpan)recieveRequest[i].GetValue()).ToString());
                    //}
                }
                else
                {
                    ReceiveRequest receiveRequest = comm.ImmediateReceive<MatrixMultiply>(Communicator.anySource, 0);
                    receiveRequest.Wait();
                    MatrixMultiply mp = (MatrixMultiply)receiveRequest.GetValue();
                    if (mp.IsAManager)
                    {
                        DateTime startTime = DateTime.Now;
                        mp.IsAManager = false;
                        mp.Chef = comm.Rank;

                        Request[] sendRequestToWorker = new Request[mp.WorkersList.Count];
                        int index = 0;

                        //Console.WriteLine("MAnager " + mp.WorkersList.Count);
                        foreach (int workerId in mp.WorkersList)
                        {
                            mp.workerId = index + 1;
                            sendRequestToWorker[index] = comm.ImmediateSend(mp, workerId, 0);
                            //  Console.WriteLine("Worker " + mp.WorkersList.Count + " " + index);
                            index++;
                        }

                        for (int i = 0; i < mp.WorkersList.Count; i++)
                        {
                            sendRequestToWorker[i].Wait();
                        }

                        var result = mp.MultiplyForRank(0);
                        ReceiveRequest[] receiveRequestFromWorkers = new ReceiveRequest[mp.WorkersList.Count];

                        for (int i = 0; i < mp.WorkersList.Count; i++)
                        {
                            receiveRequestFromWorkers[i] = comm.ImmediateReceive<Matrix>(mp.WorkersList.ToArray()[i], 0);
                        }
                        for (int i = 0; i < mp.WorkersList.Count; i++)
                        {
                            //  Console.WriteLine("Waiting for " + mp.WorkersList.ToArray()[i]);
                            receiveRequestFromWorkers[i].Wait();
                        }

                        for (int i = 0; i < mp.WorkersList.Count; i++)
                        {
                            result.Append((Matrix)receiveRequestFromWorkers[i].GetValue());
                        }

                        DateTime finishTime = DateTime.Now;
                        TimeSpan resultTime = (finishTime - startTime);
                        Request sendRequest = comm.ImmediateSend(resultTime, 0, 0);
                        sendRequest.Wait();
                        Console.WriteLine("Group " + comm.Rank + " has done in " + resultTime);
                    }
                    else
                    {
                        //Console.WriteLine("Worker " + comm.Rank + "manager" + mp.Chef);
                        mp.MultiplyForRank(mp.workerId);
                        Request sendRequest = comm.ImmediateSend(mp.MultiplyForRank(mp.workerId), mp.Chef, 0);
                        sendRequest.Wait();
                    }
                }
            }
        }
 public ReceiveResult Receive(ReceiveRequest request)
 {
     List<Channel> requestedChannels =
         request.Channels
             .Select(
                 requestedChannel =>
                     new
                     {
                         requestedChannel,
                         foundChannel = Channels.FirstOrDefault(c => c.Name == requestedChannel.Name)
                     })
             .Where(@t => @t.foundChannel != null)
             .Select(@t => new Channel
             {
                 Name = @t.foundChannel.Name,
                 Version = @t.foundChannel.Version,
                 Members = @t.foundChannel.Members,
                 Messages = @t.foundChannel.Messages.Where(m => m.Version > @t.requestedChannel.Version).ToList()
             }).ToList();
     return new ReceiveResult
     {
         Result = new ServiceResult<List<Channel>>
         {
             ReturnCode = 0,
             Data = requestedChannels
         }
     };
 }
Beispiel #35
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        /// 
        ///     ss.BeginReceive(callback, payload)
        /// 
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null, 
        /// it is the requested string (with the newline removed).  If the Exception is non-null, 
        /// it is the Exception that caused the send attempt to fail.
        /// 
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        /// 
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.        
        /// 
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload"> 
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>  
        /// 
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        /// 
        ///   </code>
        /// </example>
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            // Store the receive request, with its specified callback and payload.
            ReceiveRequest receiveRequest = new ReceiveRequest(callback, payload);
            ReceiveQueue.Enqueue(receiveRequest);

            // Ask the socket to call MessageReceive as soon as up to 1024 bytes arrive.
            byte[] buffer = new byte[1024];//this should work when this is set to a small number
            socket.BeginReceive(buffer, 0, buffer.Length,
                                SocketFlags.None, MessageReceived, buffer);
        }
        static void Main(string[] args)
        {
            //using (new MPI.Environment(ref args))
            //{
            //    Intracommunicator comm = Communicator.world;
            //    if (comm.Rank == 0)
            //    {
            //        MatrixMultiply mp = new MatrixMultiply(comm.Size, 2);
            //        mp.Show();
            //        Request sendRequest = comm.ImmediateSend(mp, 1, 0);
            //        Console.WriteLine("Sending MatrixMyltiply");
            //        Matrix res = mp.MultiplyForRank(comm.Rank);
            //        sendRequest.Wait();
            //        ReceiveRequest recieveRequest = comm.ImmediateReceive<MatrixMultiply>(Communicator.anySource, 0);
            //        recieveRequest.Wait();
            //        Console.WriteLine("Recieve MatrixMultiply");
            //        sendRequest = comm.ImmediateSend(res, 1, 1);
            //        Console.WriteLine("Sending Matrix result");
            //        sendRequest.Wait();
            //        recieveRequest = comm.ImmediateReceive<Matrix>(Communicator.anySource, 1);
            //        recieveRequest.Wait();
            //        res = (Matrix)recieveRequest.GetValue();
            //        Console.WriteLine("Recieve Matrix result");
            //        res.Show();
            //    }
            //    else
            //    {
            //        ReceiveRequest receiveRequest = comm.ImmediateReceive<MatrixMultiply>(comm.Rank - 1, 0);
            //        receiveRequest.Wait();
            //        MatrixMultiply mp = (MatrixMultiply)receiveRequest.GetValue();
            //        Request sendRequest = comm.ImmediateSend(mp, (comm.Rank + 1) % comm.Size, 0);
            //        Matrix res = mp.MultiplyForRank(comm.Rank);
            //        sendRequest.Wait();
            //        receiveRequest = comm.ImmediateReceive<Matrix>(comm.Rank - 1, 1);
            //        receiveRequest.Wait();
            //        receiveRequest.GetValue();
            //        sendRequest = comm.ImmediateSend<Matrix>(((Matrix)receiveRequest.GetValue()).Append(res), (comm.Rank + 1) % comm.Size, 1);
            //        sendRequest.Wait();
            //    }
            //}
            using (new MPI.Environment(ref args))
            {
                const int matrixSize = 50;
                Intracommunicator comm = Communicator.world;
                if (comm.Rank == 0)
                {
                    DateTime startTime = DateTime.Now;
                    MatrixMultiply testMultiply = new MatrixMultiply(comm.Size, matrixSize);
                    Matrix result = testMultiply.MultiplyForRank(0);
                    for (int i = 1; i < comm.Size; i++)
                    {
                        result.Append(testMultiply.MultiplyForRank(i));
                    }

                    DateTime endTime = DateTime.Now;
                    Console.WriteLine("Test multiply" + (startTime - endTime).ToString());

                    startTime = DateTime.Now;
                    MatrixMultiply mp = new MatrixMultiply(comm.Size, matrixSize);
                    // mp.Show();
                    Request[] sendRequest = new Request[comm.Size];

                    for (int i = 1; i < comm.Size; i++)
                    {
                        sendRequest[i] = comm.ImmediateSend(mp, i, 0);
                    }
                    Console.WriteLine("Sending partly MatrixMyltiply");
                    Matrix res = mp.MultiplyForRank(comm.Rank);

                    for (int i = 1; i < comm.Size; i++)
                    {
                        sendRequest[i].Wait();
                    }

                    ReceiveRequest[] recieveRequest = new ReceiveRequest[comm.Size];

                    for (int i = 1; i < comm.Size; i++)
                    {
                        recieveRequest[i] = comm.ImmediateReceive<Matrix>(i, 1);
                    }
                    Console.WriteLine("Recieve partly MatrixMultiply");
                    for (int i = 1; i < comm.Size; i++)
                    {
                        recieveRequest[i].Wait();
                    }

                    for (int i = 1; i < comm.Size; i++)
                    {
                        res.Append((Matrix)recieveRequest[i].GetValue());
                    }
                    //Console.WriteLine("Result is");
                    // res.Show();

                    endTime = DateTime.Now;
                    Console.WriteLine("Parallel multiply" + (startTime - endTime).ToString());
                }
                else
                {
                    ReceiveRequest receiveRequest = comm.ImmediateReceive<MatrixMultiply>(0, 0);
                    receiveRequest.Wait();
                    MatrixMultiply mp = (MatrixMultiply)receiveRequest.GetValue();
                    Request sendRequest = comm.ImmediateSend(mp.MultiplyForRank(comm.Rank), 0, 1);
                    sendRequest.Wait();
                }
            }
        }
Beispiel #37
0
        /// <summary>
        /// We can read a string from the StringSocket by doing
        /// 
        ///     ss.BeginReceive(callback, payload)
        /// 
        /// where callback is a ReceiveCallback (see below) and payload is an arbitrary object.
        /// This is non-blocking, asynchronous operation.  When the StringSocket has read a
        /// string of text terminated by a newline character from the underlying Socket, or
        /// failed in the attempt, it invokes the callback.  The parameters to the callback are
        /// a (possibly null) string, a (possibly null) Exception, and the payload.  Either the
        /// string or the Exception will be non-null, but nor both.  If the string is non-null, 
        /// it is the requested string (with the newline removed).  If the Exception is non-null, 
        /// it is the Exception that caused the send attempt to fail.
        /// 
        /// This method is non-blocking.  This means that it does not wait until a line of text
        /// has been received before returning.  Instead, it arranges for a line to be received
        /// and then returns.  When the line is actually received (at some time in the future), the
        /// callback is called on another thread.
        /// 
        /// This method is thread safe.  This means that multiple threads can call BeginReceive
        /// on a shared socket without worrying around synchronization.  The implementation of
        /// BeginReceive must take care of synchronization instead.  On a given StringSocket, each
        /// arriving line of text must be passed to callbacks in the order in which the corresponding
        /// BeginReceive call arrived.
        /// 
        /// Note that it is possible for there to be incoming bytes arriving at the underlying Socket
        /// even when there are no pending callbacks.  StringSocket implementations should refrain
        /// from buffering an unbounded number of incoming bytes beyond what is required to service
        /// the pending callbacks.        
        /// 
        /// <param name="callback"> The function to call upon receiving the data</param>
        /// <param name="payload"> 
        /// The payload is "remembered" so that when the callback is invoked, it can be associated
        /// with a specific Begin Receiver....
        /// </param>  
        /// 
        /// <example>
        ///   Here is how you might use this code:
        ///   <code>
        ///                    client = new TcpClient("localhost", port);
        ///                    Socket       clientSocket = client.Client;
        ///                    StringSocket receiveSocket = new StringSocket(clientSocket, new UTF8Encoding());
        ///                    receiveSocket.BeginReceive(CompletedReceive1, 1);
        /// 
        ///   </code>
        /// </example>
        /// </summary>
        public void BeginReceive(ReceiveCallback callback, object payload)
        {
            // Protect the ReceiveQueue
            lock (ReceiveQueue)
            {
                // Create and store the receive request.
                ReceiveRequest receiveRequest = new ReceiveRequest(callback, payload);
                ReceiveQueue.Enqueue(receiveRequest);

                // If there is no receive ongoing, start receiving.
                if (ReceiveQueue.Count == 1)
                {
                    ProcessReceivedMessage();
                }
            }
        }