/// <summary> /// ProcessRequests runs async in separate thread until Stop() or received a quit request /// The IResponseHandler will be called on the original calling thread after each request processed /// </summary> public async void ProcessRequestsAsync(IResponseHandler handler) { while (_active) { HttpServiceResponse hostResponse = null; await Task.Run(async() => { try { hostResponse = await GetContextAsync(); } catch (Exception err) { } }).ConfigureAwait(true); // calls handler to process the response handler?.Process(hostResponse); // stop the loop if quit requested if (_quitRequestHandler.GetAndResetQuitRequested) { break; } } Stop(); }
/// <summary> /// derived class must implement to handle Post request /// </summary> protected override HttpServiceResponse ProcessPostRequest(HttpServiceContext context) { SubscriptionData subscriptionData = null; string json = GetFromRequestStream(context.Context.Request); try { subscriptionData = JsonConvert.DeserializeObject <SubscriptionData>(json); } catch (Exception err) { return(CreateResponseForBadRequest(context, Name, $"InvalidSubscription: {json}")); } if (!ValidateSubscriptionData(subscriptionData)) { return(CreateResponseForBadRequest(context, Name)); } HttpServiceResponse response = null; HttpTargetSite target = subscriptionData.Target; string invalidList = string.Empty; int okCount = 0; foreach (SubscriptionItem item in subscriptionData.Items) { bool ok = Subscribe(item, target); if (ok) { okCount++; } else { if (!string.IsNullOrEmpty(invalidList)) { invalidList += ", "; } invalidList += $"{item.Node}.{item.Data}"; } } if (string.IsNullOrEmpty(invalidList)) { response = CreateSuccessResponse(context, Name, 200, null); } else { string invalidJson = $"{{\"subscriptionError\": \"{invalidList}\"}}"; if (okCount > 0) { response = CreateSuccessResponse(context, Name, 206, invalidJson); } else { CreateResponse(context, Name, false, 400, invalidJson); } } return(response); }
private async Task InspectResult <TResponse>(HttpServiceResponse <TResponse> result, string successMsg) { if (!result.Success) { ShowMessage(result.ErrorMessage, MessageType.Error); return; } ShowMessage(successMsg, MessageType.Success); await Reload(); }
/// <summary> /// display the response after a request /// </summary> void IResponseHandler.Process(HttpServiceResponse hostResponse) { if (hostResponse != null) { HttpListenerRequest request = hostResponse.Request; HttpListenerResponse response = hostResponse.Response; if (hostResponse.Success) { TextLabel.Text = $"{request.HttpMethod} {request.Url.AbsoluteUri} Status: {response.StatusCode} Result:\n{hostResponse.Content}"; } else { TextLabel.Text = $"{request.HttpMethod} {request.Url.AbsoluteUri} Status: {response.StatusCode} Result:\n{hostResponse.Content}\n Error:{hostResponse.ErrorMessage}"; } } }