public void ReceiveResponse_Streams_Zero() { var r = new ReceiveResponse(); Assert.NotNull(r.Streams); Assert.Empty(r.Streams); }
public List <ReceiveResponse <T> > PeekAllMessages(int timeoutSeconds) { List <ReceiveResponse <T> > list = new List <ReceiveResponse <T> >(); Cursor cursor = _messageQueue.CreateCursor(); PeekAction action = PeekAction.Current; Message message; try { while ((message = _messageQueue.Peek(TimeSpan.FromSeconds(timeoutSeconds), cursor, action)) != null) { ReceiveResponse <T> response = new ReceiveResponse <T>(false, (T)message.Body, message.Label, message.Id); list.Add(response); action = PeekAction.Next; } } catch (MessageQueueException e) { if (e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout) { return(list); } Debug.WriteLine(e); throw; } return(list); }
public ReceiveResponse <T> ReceiveTransactional() { if (_messageQueue.Transactional) { return(new ReceiveResponse <T>(true, default(T), "Error: Queue is not transactional type", string.Empty)); } try { Message message = _messageQueue.Receive(TimeSpan.FromSeconds(5), MessageQueueTransactionType.Automatic); ReceiveResponse <T> response = new ReceiveResponse <T>(false, (T)message.Body, message.Label, message.Id); return(response); } catch (MessageQueueException e) { if (e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout) { return(new ReceiveResponse <T>(true, default(T), "Error: Timeout", string.Empty)); } if (e.MessageQueueErrorCode == MessageQueueErrorCode.TransactionUsage) { return(new ReceiveResponse <T>(true, default(T), "Error: Transaction Usage", string.Empty)); } throw; } }
public void RequestManager_GetResponse_ReturnsResponse() { var d = new ConcurrentDictionary <Guid, TaskCompletionSource <ReceiveResponse> >(); var g = Guid.NewGuid(); var rm = new RequestManager(d); var resp = new ReceiveResponse(); Task.WaitAll( Task.Run(async() => { var r = await rm.GetResponseAsync(g, CancellationToken.None); Assert.IsTrue(resp.Equals(r)); }), Task.Run(() => { TaskCompletionSource <ReceiveResponse> value; while (!d.TryGetValue(g, out value)) { // Wait for a value; } value.SetResult(resp); })); }
private async Task <HttpResponseMessage> CreateHttpResponseAsync(ReceiveResponse receiveResponse) { var httpResponseMessage = new HttpResponseMessage((HttpStatusCode)receiveResponse.StatusCode); httpResponseMessage.Content = new StringContent(await receiveResponse.ReadBodyAsStringAsync().ConfigureAwait(false)); return(httpResponseMessage); }
// private folks private void GetPendingMessages() { if (string.IsNullOrEmpty(MessengerService.ClientId) == true) { return; } // Send a receive request: ReceiveRequest receiveRequest = new ReceiveRequest() { MessageIndex = 0, UserId = MessengerService.ClientId }; this.SendRequest(receiveRequest.SerializeToJson(), this.ReceiveSocket); // Get the response from the server: string jsonReceiveResponse = this.ReceiveResponse(this.ReceiveSocket); // Deserialize the response from the JSON string: ReceiveResponse receiveResponse = jsonReceiveResponse .DeserializeFromJson <ReceiveResponse>(); if (receiveResponse.Data == null || receiveResponse.Data.Messages == null || receiveResponse.Data.Messages.Count <= 0) { return; } // Shows the response in the console: this.ShowMessages(receiveResponse.Data.Messages); }
public void ReceiveResponse_Streams_Zero() { var r = new ReceiveResponse(); Assert.IsNotNull(r.Streams); Assert.AreEqual(0, r.Streams.Count); }
public Request(ISearchCriteria criteria, int depth, ReceiveResponse callback) { Identifier = Environment.MachineName + Peer.Self.Name + DateTime.UtcNow; SearchCriteria = criteria; Requester = Peer.Self; Depth = depth; Callback = callback; }
public Task <bool> SignalResponseAsync(Guid requestId, ReceiveResponse response) { if (_responseTasks.TryGetValue(requestId, out TaskCompletionSource <ReceiveResponse> signal)) { Task.Run(() => { signal.TrySetResult(response); }); return(Task.FromResult(true)); } return(Task.FromResult(false)); }
public Task <T> GetAsync <T>(string route, QueryString queryString = null, Func <string, T> customDeserialization = null) { ReceiveResponse receiveResponse = ReflectionUtil.DeserializeFile <ReceiveResponse>("receive_response_mock"); if (receiveResponse is T) { return(Task.FromResult((T)(object)receiveResponse)); } return(Task.FromResult(default(T))); }
public void ReceiveBase_ReadBodyAsString_NoContent_EmptyString() { var r = new ReceiveResponse(); r.Streams = new List <IContentStream>(); var result = r.ReadBodyAsString(); Assert.Equal(string.Empty, result); }
protected override async Task <int> OnMessageReceived(ReceiveResponse receiveResponse) { Console.WriteLine($"{receiveResponse.Text}, counter = {++_counter}"); string localIp = IpHelper.GetLocalIpAddress(); var txt = $"hello client, my ip is {localIp}, counter"; return(await Send(receiveResponse.Endpoint, txt)); }
public void ReceiveExtensions_ReadBodyAsJson_Streams_Zero() { var response = new ReceiveResponse { StatusCode = 3, }; var result = response.ReadBodyAsJson <dynamic>(); Assert.Null(result); Assert.Equal(3, response.StatusCode); }
public void A_Message_Received_From_A_Queue_In_A_Transaction() { string payload = "Payload 0"; string label = "Label 0"; DeleteAllMessagesFromQueues(); WriteManyToQueue(1); ReceiveResponse <string> result = _textQueueWrapper.ReceiveTransactional(); Assert.That(result.Label, Is.EqualTo(label)); Assert.That(result.Payload, Is.EqualTo(payload)); }
private List <ReceiveResponse <string> > ReadManyStringFromQueue(int i) { List <ReceiveResponse <string> > responses = new List <ReceiveResponse <string> >(); for (int j = 0; j < i; j++) { ReceiveResponse <string> r = _textQueueWrapper.Receive(); responses.Add(r); } return(responses); }
/// <inheritdoc/> public Task <bool> SignalResponseAsync(Guid requestId, ReceiveResponse response) { if (_responseTasks.TryGetValue(requestId, out TaskCompletionSource <ReceiveResponse> signal)) { #pragma warning disable VSTHRD110 // Observe result of async calls Task.Run(() => { signal.TrySetResult(response); }); #pragma warning restore VSTHRD110 // Observe result of async calls return(Task.FromResult(true)); } return(Task.FromResult(false)); }
public async Task RequestManager_SignalResponse_Response() { var d = new ConcurrentDictionary<Guid, TaskCompletionSource<ReceiveResponse>>(); var g = Guid.NewGuid(); var tcs = new TaskCompletionSource<ReceiveResponse>(); d.TryAdd(g, tcs); var rm = new RequestManager(d); var resp = new ReceiveResponse(); var r = await rm.SignalResponse(g, resp); Assert.IsTrue(resp.Equals(tcs.Task.Result)); }
public async void ReceiveFunds_MockRequest_Valid() { using (BlockchainApiHelper apiHelper = new BlockchainApiHelper(baseHttpClient: new MockReceiveHttpClient())) { ReceiveResponse receiveResponse = await apiHelper.FundReceiver.ReceiveFundsAsync("MockAddress", "CallbackUrl"); Assert.NotNull(receiveResponse); Assert.Equal(receiveResponse.CallbackUrl, "http://yoururl.com"); Assert.Equal(receiveResponse.DestinationAddress, "1A8JiWcwvpY7tAopUkSnGuEYHmzGYfZPiq"); Assert.Equal(receiveResponse.FeePercent, 0); Assert.Equal(receiveResponse.InputAddress, "1KZoUuPWFAeyVySHAGqvTUDoX6P3ntuLNF"); } }
private void OnServerMessageReceived(object sender, ReceiveResponse e) { if (MessageReceived != null) { UpdateEndpointStore(e.Text, e.Endpoint); MessageReceived.Invoke(this, new ConnectionMessageEventArgs() { Source = e.Endpoint.ToString(), Message = e.Text, Type = MessageType.Text }); e.Handled = true; } }
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 ReceiveExtensions_ReadBodyAsString_Streams() { const string stringInput = "message"; var stream = new MemoryStream(Encoding.UTF8.GetBytes(stringInput)); var mockContentStream = new Mock <IContentStream>(); mockContentStream.Setup(e => e.Stream).Returns(stream); var response = new ReceiveResponse { Streams = new List <IContentStream> { mockContentStream.Object } }; var result = response.ReadBodyAsString(); Assert.NotNull(result); Assert.Equal(stringInput, result); }
public static async Task <String> ReadBodyAsStringAsync(this ReceiveResponse response) { // 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. try { var contentStream = response.Streams.FirstOrDefault(); if (contentStream != null) { return(await ReadBuffer(contentStream).ConfigureAwait(false)); } return(null); } catch (Exception ex) { throw; } }
public void A_Message_Is_Deleted_By_Id() { int numberOfMessages = 1; WriteManyToQueue(numberOfMessages); int queueDepth = _textQueueWrapper.GetQueueDepth(); Assert.That(queueDepth, Is.EqualTo(numberOfMessages)); List <ReceiveResponse <string> > responses = _textQueueWrapper.PeekAllMessages(5); ReceiveResponse <string> response = responses.First(); string id = response.Id; ReceiveResponse <string> receiveById = _textQueueWrapper.ReceiveById(id); Assert.That(receiveById.Id, Is.EqualTo(id)); queueDepth = _textQueueWrapper.GetQueueDepth(); Assert.That(queueDepth, Is.LessThan(numberOfMessages)); }
public static async Task <T> ReadBodyAsJsonAsync <T>(this ReceiveResponse response) { // 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. try { T returnValue = default(T); string streamContent = await response.ReadBodyAsStringAsync().ConfigureAwait(false); if (streamContent != null) { returnValue = JsonConvert.DeserializeObject <T>(streamContent); } return(returnValue); } catch (Exception ex) { throw; } }
public virtual void ReceiveResponse(Header header, ReceiveResponse response) { if (header == null) { throw new ArgumentNullException(nameof(header)); } if (header.Type != PayloadTypes.Response) { throw new InvalidOperationException($"StreamingSession cannot receive payload of type {header.Type} as response"); } if (response == null) { throw new ArgumentNullException(nameof(response)); } Log.PayloadReceived(_logger, header); lock (_receiveSync) { if (!response.Streams.Any()) { if (_pendingResponses.TryGetValue(header.Id, out TaskCompletionSource <ReceiveResponse> responseTask)) { responseTask.SetResult(response); _pendingResponses.TryRemove(header.Id, out TaskCompletionSource <ReceiveResponse> removedResponse); } } else { _responses.Add(header.Id, response); foreach (var streamDefinition in response.Streams) { _streamDefinitions.Add(streamDefinition.Id, streamDefinition as StreamDefinition); } } } }
private async Task ProcessResponse(Stream stream) { using (var textReader = new StreamReader(stream)) { using (var jsonReader = new JsonTextReader(textReader)) { var responsePayload = Serializer.Deserialize <ResponsePayload>(jsonReader); var response = new ReceiveResponse() { StatusCode = responsePayload.StatusCode, Streams = new List <IContentStream>(), }; if (responsePayload.Streams != null) { foreach (var streamDescription in responsePayload.Streams) { if (!Guid.TryParse(streamDescription.Id, out var 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; response.Streams.Add(new ContentStream(id, streamAssembler) { Length = streamDescription.Length, ContentType = streamDescription.ContentType, }); } } await _onCompleted(this.Id, response).ConfigureAwait(false); } } }
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 response = new ReceiveResponse { Streams = new List <IContentStream> { mockContentStream.Object } }; var result = response.ReadBodyAsJson <Activity>(); Assert.NotNull(result); Assert.Equal(activity.Type, result.Type); }
public static Peer CreateInstance(string name, ReceiveResponse response) { return new Peer(name, MusicDatabase.Load(ConfigurationManager.AppSettings["DATABASE_FILE"]), response); }
private static bool IsSuccessResponse(ReceiveResponse response) { return(response != null && response.StatusCode >= 200 && response.StatusCode <= 299); }
public async Task StreamingSession_SendRequest_ReceiveResponse(int streamLength, int streamCount, int chunkCount) { // Arrange var request = new StreamingRequest() { Verb = "GET", Path = "api/version", Streams = new List <ResponseMessageStream>() }; request.AddStream(new StringContent("Hello human, I'm Bender!")); var requestHandler = new Mock <RequestHandler>(); var requestCompletionSource = new TaskCompletionSource <bool>(); requestHandler .Setup(r => r.ProcessRequestAsync(It.IsAny <ReceiveRequest>(), null, null, CancellationToken.None)) .ReturnsAsync(() => new StreamingResponse() { StatusCode = 200 }) .Callback(() => requestCompletionSource.SetResult(true)); var transportHandler = new Mock <TransportHandler>(new Mock <IDuplexPipe>().Object, NullLogger.Instance); var responseCompletionSource = new TaskCompletionSource <bool>(); var transportHandlerSetup = transportHandler.Setup(t => t.SendRequestAsync(It.IsAny <Guid>(), It.IsAny <RequestModel>(), CancellationToken.None)); var session = new StreamingSession(requestHandler.Object, transportHandler.Object, NullLogger.Instance); Header responseHeader = null; ReceiveResponse response = null; transportHandlerSetup.Callback( (Guid requestId, RequestModel requestPayload, CancellationToken cancellationToken) => { responseHeader = new Header() { Id = requestId, Type = PayloadTypes.Response }; response = new ReceiveResponse() { StatusCode = 200, Streams = StreamingDataGenerator.CreateStreams(requestId, streamLength, streamCount, chunkCount, PayloadTypes.Response) }; session.ReceiveResponse(responseHeader, response); foreach (AugmentedStreamDefinition definition in response.Streams) { var chunkList = definition.Chunks; for (int i = 0; i < chunkCount; i++) { bool isLast = i == chunkCount - 1; session.ReceiveStream( new Header() { End = isLast, Id = definition.Id, PayloadLength = chunkList[i].Length, Type = PayloadTypes.Stream }, chunkList[i]); } } }); // Act var responseTask = session.SendRequestAsync(request, CancellationToken.None); var responseWithTimeout = await Task.WhenAny(responseTask, Task.Delay(TimeSpan.FromSeconds(5))); // Assert Assert.Equal(responseTask, responseWithTimeout); var receivedResponse = await responseTask; Assert.Equal(response.StatusCode, receivedResponse.StatusCode); Assert.Equal(response.Streams.Count, receivedResponse.Streams.Count); Assert.True(response.Streams.SequenceEqual(receivedResponse.Streams)); }
public void StreamingSession_ReceiveResponse_ParameterValidation(Header header, ReceiveResponse response, Type exceptionType) { // Arrange var transportHandler = new Mock <TransportHandler>(new Mock <IDuplexPipe>().Object, NullLogger.Instance); var session = new StreamingSession(new Mock <RequestHandler>().Object, transportHandler.Object, NullLogger.Instance); // Act + Assert Assert.Throws(exceptionType, () => session.ReceiveResponse(header, response)); }
public SearchEngine(MusicDatabase database, ReceiveResponse callback) { _localIndexer = new LocalIndexer(database); Callback = callback; Database = database; }
public Request(ISearchCriteria criteria, ReceiveResponse callback) : this(criteria, 50, callback) { }
public Peer(string name, MusicDatabase database, ReceiveResponse responseCallback) { Name = name; PeerContainer = new PeerContainer(); SearchEngine = new SearchEngine(database, responseCallback); }