async Task <HttpResponse> HandleRegisterDevice(HttpRequest request) { JsonHttpResponse response = new JsonHttpResponse(); StreamReader sr = new StreamReader(request.Body, Encoding.UTF8); string json = await sr.ReadToEndAsync(); AddDevice(Serializer.DeserializeJson <DiscoveryBroadcast>(json)); return(response); }
async Task <HttpResponse> HandleNewXaml(HttpRequest request) { JsonHttpResponse response = new JsonHttpResponse(); StreamReader sr = new StreamReader(request.Body, Encoding.UTF8); string json = await sr.ReadToEndAsync(); EvalRequest evalRequest = Serializer.DeserializeJson <EvalRequest>(json); EvalResponse evalResponse = new EvalResponse(); response.Data = evalResponse; EvalResult result = null; try { result = await vm.Eval(evalRequest, mainScheduler, CancellationToken.None); evalResponse.Messages = result.Messages; evalResponse.Duration = result.Duration; Log.Information($"Visualizing result {result.Result}"); if (result.HasResult) { var tcs = new TaskCompletionSource <bool>(); Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { try { await previewer.Preview(result); tcs.SetResult(true); } catch (Exception ex) { await previewer.NotifyError(new ErrorViewModel("Oh no! An exception!", ex)); tcs.SetException(ex); } }); await tcs.Task; } else { Xamarin.Forms.Device.BeginInvokeOnMainThread(async() => { await previewer.NotifyError(new ErrorViewModel("Oh no! An evaluation error!", result)); }); } return(response); } catch (Exception ex) { Log.Exception(ex); response.StatusCode = HttpStatusCode.InternalServerError; return(response); } }
private Task <IResponse> GetPopularServers(int serversCount) { IResponse response = new JsonHttpResponse(HttpStatusCode.OK, reportStorage.PopularServers(serversCount).Select(server => new { endpoint = server.Server.Id, name = server.Server.Name, averageMatchesPerDay = server.AverageMatchesPerDay(globalStatisticStorage) })); return(Task.FromResult(response)); }
private Task <IResponse> GetBestPlayers(int playersCount) { var bestPlayers = reportStorage.BestPlayers(playersCount).Select(player => new { name = player.Player.Name, killToDeathRatio = player.KillToDeathRatio }); IResponse response = new JsonHttpResponse(HttpStatusCode.OK, bestPlayers); return(Task.FromResult(response)); }
private static JsonHttpResponse CreateSuccesResponse <TResult>(TResult result) where TResult : class { var successResponse = new JsonHttpResponse(new ServiceResult <TResult> { Success = true, Result = result }) { StatusCode = 200 }; return(successResponse); }
//RESPONSE private static JsonHttpResponse CreateErrorResponse(string errorMessage, int statusCode) { var errorResponse = new JsonHttpResponse(new ServiceResult <object> { Success = false, Error = errorMessage }) { StatusCode = statusCode }; return(errorResponse); }
private Task <IResponse> GetRecentMatches(int matchCount) { var recentMatches = reportStorage.RecentMatches(matchCount).Select(match => new { server = match.HostServer.Id, timestamp = match.EndTime, results = match }); IResponse response = new JsonHttpResponse(HttpStatusCode.OK, recentMatches); return(Task.FromResult(response)); }
/// <summary> /// Обрабатывает запрос с использованием указанных правил. /// </summary> protected async Task <object> ProcessRequestAsync <TQuery, TResult>( IHttpRequest request, Func <IHttpRequest, TQuery> queryFunc, Func <TQuery, Task <TResult> > handlerFunc, Func <TQuery, Task <TResult> > onBefore, Func <TQuery, TResult, Exception, Task> onAfter) where TResult : DocumentQueryResult { var startTime = DateTime.Now; object response; TResult result = null; Exception error = null; try { // Разбор входящего запроса var queryResult = TryExecute(() => queryFunc(request)); var query = queryResult.Item1; error = queryResult.Item2; if (error == null) { // Выполнение предобработчика var onBeforeResult = await TryExecuteAsync(() => onBefore(query)); result = onBeforeResult.Item1; error = onBeforeResult.Item2; if (error == null) { // Если нет результата if (result == null) { // Выполнение обработчика var handlerResult = await TryExecuteAsync(() => handlerFunc(query)); result = handlerResult.Item1; error = handlerResult.Item2; } var resultClosure = result; var errorClosure = error; // Выполнение постобработчика var onAfterError = await TryExecuteAsync(() => onAfter(query, resultClosure, errorClosure)); if (onAfterError != null) { error = (error == null) ? onAfterError : new AggregateException(error, onAfterError); } } } } catch (Exception exception) { error = exception; } finally { var success = (error == null && (result?.ValidationResult == null || result.ValidationResult.IsValid)); var requestResult = new ServiceResult <TResult> { Success = success, Result = result, Error = error?.GetFullMessage() }; response = new JsonHttpResponse(requestResult) { StatusCode = success ? 200 : 500 }; } // Запись в журнал var method = $"{request.Method}::{request.Path}"; if (error != null) { _log.Error(Resources.RequestProcessedWithException, new Dictionary <string, object> { { "method", method } }, error); } _performanceLog.Log(method, startTime, error); return(response); }