/// <summary> /// Generates a task sequence for getting the properties of the queue service. /// </summary> /// <param name="setResult">A delegate to receive the service properties.</param> /// <returns>A task sequence that gets the properties of the queue service.</returns> private TaskSequence GetServicePropertiesImpl(Action <ServiceProperties> setResult) { HttpWebRequest request = QueueRequest.GetServiceProperties(this.BaseUri, this.Timeout.RoundUpToSeconds()); CommonUtils.ApplyRequestOptimizations(request, -1); this.Credentials.SignRequest(request); // Get the web response. Task <WebResponse> responseTask = request.GetResponseAsyncWithTimeout(this, this.Timeout); yield return(responseTask); using (HttpWebResponse response = responseTask.Result as HttpWebResponse) using (Stream responseStream = response.GetResponseStream()) using (MemoryStream memoryStream = new MemoryStream()) { // Download the service properties. Task <NullTaskReturn> downloadTask = new InvokeTaskSequenceTask(() => { return(responseStream.WriteTo(memoryStream)); }); yield return(downloadTask); // Materialize any exceptions. NullTaskReturn scratch = downloadTask.Result; // Get the result from the memory stream. memoryStream.Seek(0, SeekOrigin.Begin); setResult(QueueResponse.ReadServiceProperties(memoryStream)); } }
static void Main(string[] args) { var q = CloudStorageAccount.Parse("UseDevelopmentStorage=true").CreateCloudQueueClient().GetQueueReference("testqueue"); q.CreateIfNotExist(); var req = QueueRequest.PutMessage(new Uri(q.Uri, q.Name + "/messages"), 30, null); var body = QueueRequest.GenerateMessageRequestBody("hello world"); req.ContentLength = body.Length; q.ServiceClient.Credentials.SignRequest(req); using (var stream = req.GetRequestStream()) { stream.Write(body, 0, body.Length); stream.Close(); } req.GetResponse(); req = QueueRequest.GetMessages(new Uri(q.Uri, q.Name + "/messages"), 30, 32, null); q.ServiceClient.Credentials.SignRequest(req); using (var response = (HttpWebResponse)req.GetResponse()) { using (var msgResponse = QueueResponse.GetMessages(response)) { foreach (var msg in msgResponse.Messages) { Console.WriteLine("MESSAGE: " + msg.Text); q.DeleteMessage(msg.Id, msg.PopReceipt); } } } q.Delete(); }
public void run() { try { this.initClient(); Console.Out.WriteLine("big queue size before enqueue : " + client.getSize(TOPIC)); QueueRequest req = new QueueRequest(); req.Data = Encoding.Default.GetBytes("hello world"); client.enqueue(TOPIC, req); Console.Out.WriteLine("big queue size after enqueue : " + client.getSize(TOPIC)); QueueResponse resp = client.peek(TOPIC); Console.Out.WriteLine("big queue size after peek : " + client.getSize(TOPIC)); Console.Out.WriteLine("peeked message : " + Encoding.Default.GetString(resp.Data)); resp = client.dequeue(TOPIC); Console.Out.WriteLine("big queue size after dequeue : " + client.getSize(TOPIC)); Console.Out.WriteLine("dequeued message : " + Encoding.Default.GetString(resp.Data)); } finally { this.closeClient(); } }
public void PostResponse <T>(QueueResponse <T> response) { var message = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)); _responseQueueChannelManager.GetChannel().BasicPublish(exchange: _responseQueueSettings.ExchangeName, routingKey: _responseQueueSettings.RoutingKey, basicProperties: null, body: message); }
/// <summary> /// Lists the queues impl core. /// </summary> /// <param name="prefix">The prefix.</param> /// <param name="detailsIncluded">The details included.</param> /// <param name="continuationToken">The continuation token.</param> /// <param name="pagination">The pagination.</param> /// <param name="setResult">The set result.</param> /// <returns>A <see cref="TaskSequence"/> for listing the queues.</returns> private TaskSequence ListQueuesImplCore( string prefix, QueueListingDetails detailsIncluded, ResultContinuation continuationToken, ResultPagination pagination, Action <ResultSegment <CloudQueue> > setResult) { CommonUtils.AssertContinuationType(continuationToken, ResultContinuation.ContinuationType.Queue); ListingContext listingContext = new ListingContext(prefix, pagination.GetNextRequestPageSize()) { Marker = continuationToken != null ? continuationToken.NextMarker : null }; var queueList = new List <CloudQueue>(); var webRequest = QueueRequest.List(this.BaseUri, this.Timeout.RoundUpToSeconds(), listingContext, detailsIncluded); this.Credentials.SignRequest(webRequest); var listTask = webRequest.GetResponseAsyncWithTimeout(this, this.Timeout); yield return(listTask); string nextMarker; using (var response = listTask.Result as HttpWebResponse) { var parsedResponse = QueueResponse.List(response); // Materialize the results so that we can close the response queueList.AddRange(parsedResponse.Queues.Select((Func <QueueEntry, CloudQueue>) this.SelectResponse)); nextMarker = parsedResponse.NextMarker; } ResultContinuation newContinuationToken = new ResultContinuation() { NextMarker = nextMarker, Type = ResultContinuation.ContinuationType.Queue }; ResultSegment.CreateResultSegment( setResult, queueList, newContinuationToken, pagination, this.RetryPolicy, (paginationArg, continuationArg, resultSegment) => this.ListQueuesImplCore(prefix, detailsIncluded, continuationArg, paginationArg, resultSegment)); }
private void SendResponse(string connectionId, int code) { var queueResponse = new QueueResponse { Code = code }; var message = new SocketMessage { Data = queueResponse, Context = Constants.NowPlayingQueue, NewLineTerminated = true, }; _hub.Publish(new PluginResponseAvailableEvent(message, connectionId)); }
public async void Should_Return_OkObjectResult_with_one_Queue() { //Arrange var expectedResult = new Queue() { QueueId = 1 }; var finalResult = new QueueResponse() { QueueId = 1 }; QueueRepositoryMock .Setup(x => x.Get(expectedResult.QueueId)) .ReturnsAsync(expectedResult).Verifiable(); UnitofWorkMock .Setup(m => m.Queue) .Returns(QueueRepositoryMock.Object); MapperMock .Setup(m => m.Map <QueueResponse>(expectedResult)) .Returns(finalResult); //Act var result = await _uut.Get(expectedResult.QueueId); //Assert QueueRepositoryMock.Verify(); MapperMock.Verify(); var okResult = Assert.IsType <OkObjectResult>(result); Assert.Same(finalResult, okResult.Value); }
public Task <HttpContext> Parse(ConsumeResult <byte[], byte[]> consumeResult, FeatureCollection features) { _log.LogTrace("kafka request to http context. Parse headers"); var headers = consumeResult.Message.Headers.Aggregate(new Dictionary <string, string>(consumeResult.Message.Headers.Count), (dictionary, header) => { dictionary.TryAdd(header.Key, GetValue(header.GetValueBytes())); return(dictionary); }); headers.TryGetValue(QueueHeaders.Uri, out var uri); _log.LogTrace($"request Headers: {headers.Aggregate(new StringBuilder(), (builder, pair) => builder.Append($"{pair.Key}:{pair.Value}"))}"); if (string.IsNullOrWhiteSpace(uri)) { _log.LogError($"Header {QueueHeaders.Uri} missing. Request declined"); return(null); } if (!headers.TryGetValue(QueueHeaders.Method, out var method)) { method = HttpMethods.Get; _log.LogWarning($"Header {QueueHeaders.Method} missing. Default method {method}"); } var requestUri = new Uri(uri); var query = requestUri.ParseQueryString(); var body = consumeResult.Message.Value; _log.LogTrace($"Create HttpRequest {uri} {method}"); var contentTypeHeader = HeaderNames.ContentType.ToLowerInvariant(); if (!headers.TryGetValue(contentTypeHeader, out var contentType)) { contentType = QueueConsts.DefaultContentType; if (body != null) { _log.LogWarning($"Header {contentTypeHeader} is missing. Set value to {contentType}"); } } var request = new QueueRequest { Body = body != null ? new MemoryStream(body) : Stream.Null, ContentType = contentType ?? QueueConsts.DefaultContentType, IsHttps = false, Method = method, Protocol = requestUri.Scheme, QueryString = new QueryString(requestUri.Query), Query = new QueryCollection(query.AllKeys.GroupBy(x => x).ToDictionary(x => x.Key, x => new StringValues(query[x.Key]))), Path = requestUri.AbsolutePath, Host = new HostString(requestUri.Host), Scheme = requestUri.Scheme, PathBase = PathString.Empty }; request.ContentLength = request.Body.Length; headers.TryGetValue(HeaderNames.Accept, out var acceptValues); var accept = acceptValues; headers.TryGetValue(QueueHeaders.CorrelationId, out var replyTo); _log.LogTrace("Create default HttpResponse"); var response = new QueueResponse { ContentType = string.IsNullOrWhiteSpace(accept) ? QueueConsts.DefaultContentType : accept, StatusCode = StatusCodes.Status200OK, Body = !_option.ForceResponseStream && replyTo == null ? Stream.Null : new MemoryStream() }; var context = new QueueContext(features, response, request); _log.LogTrace("Parse sucessful"); return(Task.FromResult(context as HttpContext)); }
public Task <QueueContext> Parse(BasicDeliverEventArgs args, IFeatureCollection features) { try { _log.LogTrace("Validate request"); _validator.Validate(args); var props = args.BasicProperties; var headers = args.BasicProperties.Headers.ToDictionary(x => x.Key.ToLower(CultureInfo.InvariantCulture), pair => pair.Value); _log.LogTrace("Parsing standart headers method, accept, uri, content-type e.t.c"); var method = headers.GetOrDefaultString(QueueHeaders.Method, HttpMethods.Get); var accept = headers.GetOrDefaultString(HeaderNames.Accept.ToLowerInvariant(), QueueConsts.DefaultContentType); var uriHeader = headers.GetOrDefaultString(QueueHeaders.Uri); if (!Uri.TryCreate(uriHeader, UriKind.RelativeOrAbsolute, out var uri)) { throw new ArgumentException($"Header {QueueHeaders.Uri} must be valid uri absolute or relative"); } var relativeUri = uri.IsAbsoluteUri ? QueueNameExtensions.GetQueue(uri) : uriHeader; if (relativeUri[0] != '/') { relativeUri = "/" + relativeUri; } var contentType = headers.GetOrDefaultString(HeaderNames.ContentType.ToLowerInvariant(), QueueConsts.DefaultContentType); _log.LogTrace("Parse query parameters"); var startIndex = uriHeader.IndexOf('?'); var queryString = new QueryString(startIndex == -1 ? string.Empty : uriHeader.Substring(startIndex)); var query = HttpUtility.ParseQueryString(queryString.Value ?? string.Empty); var host = headers.GetOrDefaultString(HeaderNames.Host.ToLowerInvariant(), _options.Queue.Uri.Host); var emptyBody = method == HttpMethods.Get || method == HttpMethods.Delete; if (emptyBody && args.Body.Length != 0) { _log.LogWarning($"{args.ConsumerTag}, uri: {relativeUri} method not available body. But body is set"); } MemoryMarshal.TryGetArray(args.Body, out ArraySegment <byte> array); var request = new QueueRequest { Body = !emptyBody ? new MemoryStream(array.Array, 0, array.Count, false) : Stream.Null, ContentLength = array.Count, ContentType = contentType, IsHttps = false, Method = method, Protocol = props.ProtocolClassName, QueryString = queryString, Query = new QueryCollection(query.AllKeys.ToDictionary(x => x, x => new StringValues(query[x]))), Path = relativeUri, Host = host != null ? new HostString(host) : new HostString(string.Empty), Scheme = RabbitConsts.Schema, PathBase = PathString.Empty, }; _log.LogTrace("Filling in the request headers"); foreach (var header in headers) { if (header.Value is List <object> list) { } else { request.Headers.TryAdd(header.Key, Encoding.UTF8.GetString((byte[])header.Value)); } } _log.LogTrace($"Create default response"); var response = new QueueResponse { ContentType = accept, StatusCode = StatusCodes.Status200OK, Body = !_options.ForceResponseStream && args.BasicProperties.ReplyTo == null ? Stream.Null : new MemoryStream() }; _log.LogTrace($"Create queue context"); var context = new QueueContext(features, response, request); return(Task.FromResult(context)); } catch (Exception e) { _log.LogError(e, "Error create Context"); return(Task.FromResult(default(QueueContext))); } }
public static void PostOkResponse <T>(this IResponseQueue queue, Guid correlationId, T response) { queue.PostResponse(QueueResponse <T> .Ok(correlationId, response)); }