public async Task <IHttpActionResult> Handle(string commandName, [FromBody] Newtonsoft.Json.Linq.JObject json) { try { var result = await _commandProcessor.ProcessWithOrWithoutResultAsync(commandName, json); if (result == CommandResult.None) { return(Ok()); } return(Ok(result.Value)); } catch (CommandProcessorException exception) { _logger?.Error(Request, LogEvents.CommandProcessorException, exception, "Handle command failed"); return(BadRequest(exception.Message)); } catch (CommandValidationException exception) { _logger?.Error(Request, LogEvents.CommandValidationException, exception, "Handle command failed"); return(BadRequest(exception.Message)); } catch (Exception exception) { _logger?.Error(Request, LogEvents.CommandException, exception, "Handle command failed"); return(InternalServerError(exception)); } }
public async Task <IHttpActionResult> HandlePost(string queryName, [FromBody] Newtonsoft.Json.Linq.JObject json) { try { var result = await _queryProcessor.ProcessAsync <object>(queryName, json); return(Ok(result)); } catch (Exception exception) { _logger?.Error(Request, exception.GetQueryCategory(), exception, "Handle query failed: {0}, {1}", queryName, json.ToString(Formatting.None)); return(Content(exception.IsHandled() ? HttpStatusCode.BadRequest : HttpStatusCode.InternalServerError, exception.ToError())); } }
public async Task <IHttpActionResult> HandlePost(string queryName, [FromBody] Newtonsoft.Json.Linq.JObject json) { try { var result = await _queryProcessor.ProcessAsync <object>(queryName, json); return(Ok(result)); } catch (QueryProcessorException exception) { _logger?.Error(Request, LogEvents.QueryProcessorException, exception, "Handle query failed"); return(BadRequest(exception.Message)); } catch (QueryValidationException exception) { _logger?.Error(Request, LogEvents.QueryValidationException, exception, "Handle query failed"); return(BadRequest(exception.Message)); } catch (Exception exception) { _logger?.Error(Request, LogEvents.QueryException, exception, "Handle query failed"); return(InternalServerError(exception)); } }
public static bool InsureBreweryDbIsInitialized(MobileAppSettingsDictionary appSettings, ITraceWriter logger) { settings = appSettings; tracer = logger; if (string.IsNullOrEmpty(BreweryDB.BreweryDBClient.ApplicationKey)) { string apiKey; // Try to get the BreweryDB API key app settings. if (!(settings.TryGetValue("BREWERYDB_API_KEY", out apiKey))) { tracer.Error("Could not retrieve BreweryDB API key."); return false; } tracer.Info($"BreweryDB API Key {apiKey}"); BreweryDB.BreweryDBClient.Initialize(apiKey); } return true; }
public async Task <IHttpActionResult> Handle(string commandName, [FromBody] Newtonsoft.Json.Linq.JObject json) { try { var result = await _commandProcessor.ProcessWithOrWithoutResultAsync(commandName, json); if (result == CommandResult.None) { return(Ok()); } return(Ok(result.Value)); } catch (Exception exception) { _logger?.Error(Request, exception.GetCommandCategory(), exception, "Handle command failed: {0}, {1}", commandName, json.ToString(Formatting.None)); return(Content(exception.IsHandled() ? HttpStatusCode.BadRequest : HttpStatusCode.InternalServerError, exception.ToError())); } }
private static void SetCachePolicy(ICachePolicyProvider provider, HttpRequestMessage request, HttpResponseMessage response, ITraceWriter tracer) { if (provider != null && response != null && IsCacheableMethod(request.Method) && !HasCachingHeaders(response)) { try { provider.SetCachePolicy(response); } catch (Exception ex) { string msg = RResources.CachePolicy_BadProvider.FormatForUser(provider.GetType().Name, ex.Message); tracer.Error(msg, ex, request, LogCategories.MessageHandlers); } } }
public HttpResponseMessage GetPlans(int id) { try { var group = groupService.GetPlans(id); if (group != null) { return(Request.CreateResponse(HttpStatusCode.OK, group)); } return(Request.CreateErrorResponse(HttpStatusCode.NoContent, "There no plans in this group.")); } catch (EntityException e) { tracer.Error(Request, ControllerContext.ControllerDescriptor.ControllerType.FullName, e); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
public async Task <HttpResponseMessage> PutInstallation([FromUri] string installationId, [FromBody] NotificationInstallation notificationInstallation) { //String ni = Newtonsoft.Json.JsonConvert.SerializeObject(notificationInstallation); ITraceWriter traceWriter = this.Configuration.Services.GetTraceWriter(); traceWriter.Info($"notificationInstallation.Tags.Count : {notificationInstallation.Tags.Count}"); if (!ModelState.IsValid) { throw new HttpResponseException(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState)); } this.ValidateInstallationId(installationId); this.ValidateNotificationInstallation(installationId, notificationInstallation); // The installation object that will be sent to NH. Installation installation = this.CreateInstallation(notificationInstallation); CopyAllTagsToInstallation(installation, notificationInstallation.Tags); HashSet <string> tagsAssociatedWithInstallationId = await this.GetTagsAssociatedWithInstallationId(notificationInstallation.InstallationId); ClaimsPrincipal serviceUser = this.User as ClaimsPrincipal; if (tagsAssociatedWithInstallationId.Count == 0) { // Installation does not exist on NH. Add it. if (installation.Tags == null) { installation.Tags = new List <string>(); } // Tag the installation with the UserId if authenticated. if (serviceUser != null && serviceUser.Identity.IsAuthenticated) { Claim userIdClaim = serviceUser.FindFirst(ClaimTypes.NameIdentifier); if (userIdClaim != null) { string incomingUserTag = string.Format(UserIdTagPlaceholder, userIdClaim.Value); installation.Tags.Add(incomingUserTag); } } try { await this.UpsertInstallationAsync(installation); } catch (HttpResponseException) { throw; } catch (Exception ex) { string error = RResources.NotificationHub_CreateOrUpdateInstallationFailed.FormatForUser(installationId, ex.Message); traceWriter.Error(error, ex, this.Request, ServiceLogCategories.NotificationControllers); traceWriter.Error(error, ex, this.Request, LogCategories.NotificationControllers); // We return 4xx status code on error as it is impossible to know whether it is bad input or a // server error from NH. As a result we err on the bad request side. return(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } } else { // Installation already existed on NH. if (serviceUser != null && serviceUser.Identity.IsAuthenticated) { // Because the user is authenticated, copy all previous tags except UserId. CopyTagsToInstallation(installation, tagsAssociatedWithInstallationId, false); // Add the incoming UserId. Claim userIdClaim = serviceUser.FindFirst(ClaimTypes.NameIdentifier); if (userIdClaim != null) { string incomingUserTag = string.Format(UserIdTagPlaceholder, userIdClaim.Value); AddTagToInstallation(installation, incomingUserTag); } } else { // Because the request is anonymous, copy all previous tags to the installation object, including the previous user tag. CopyTagsToInstallation(installation, tagsAssociatedWithInstallationId, true); } CopyTagsToInstallation(installation, tagsAssociatedWithInstallationId, true); try { await this.UpsertInstallationAsync(installation); } catch (HttpResponseException) { throw; } catch (Exception ex) { string error = RResources.NotificationHub_CreateOrUpdateInstallationFailed.FormatForUser(installationId, ex.Message); traceWriter.Error(error, ex, this.Request, ServiceLogCategories.NotificationControllers); traceWriter.Error(error, ex, this.Request, LogCategories.NotificationControllers); // We return 4xx status code on error as it is impossible to know whether it is bad input or a // server error from NH. As a result we err on the bad request side. return(this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message)); } } return(this.Request.CreateResponse(HttpStatusCode.OK)); }
/// <summary> /// 错误 /// </summary> /// <param name="tracer">跟踪编写器</param> /// <param name="request">Http请求消息</param> /// <param name="controller">WebApi控制器</param> /// <param name="exception">异常信息</param> /// <param name="messageFormat">消息</param> /// <param name="messageArguments">消息参数</param> public static void Error(this ITraceWriter tracer, HttpRequestMessage request, ApiController controller, Exception exception, string messageFormat, params object[] messageArguments) { tracer.Error(request, controller.ControllerContext.ControllerDescriptor.ControllerType.FullName, exception, messageFormat, messageArguments); }
/// <summary> /// 错误 /// </summary> /// <param name="tracer">跟踪编写器</param> /// <param name="request">Http请求消息</param> /// <param name="controller">WebApi控制器</param> /// <param name="exception">异常信息</param> public static void Error(this ITraceWriter tracer, HttpRequestMessage request, ApiController controller, Exception exception) { tracer.Error(request, controller.ControllerContext.ControllerDescriptor.ControllerType.FullName, exception); }
public async Task <HttpResponseMessage> GetAllTasksAsync() { try { var allTasks = await taskService.GetAllTasksAsync(); if (allTasks != null) { return(Request.CreateResponse(HttpStatusCode.OK, allTasks)); } return(Request.CreateErrorResponse(HttpStatusCode.NoContent, "There are no tasks in database.")); } catch (EntityException e) { tracer.Error(Request, ControllerContext.ControllerDescriptor.ControllerType.FullName, e); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }
public async Task <HttpResponseMessage> GetPlansAsync(int id) { try { IEnumerable <PlanDto> group = await groupService.GetPlansAsync(id); if (group != Enumerable.Empty <PlanDto>()) { return(Request.CreateResponse(HttpStatusCode.OK, group)); } return(Request.CreateErrorResponse(HttpStatusCode.NoContent, "There no plans in this group.")); } catch (EntityException e) { tracer.Error(Request, ControllerContext.ControllerDescriptor.ControllerType.FullName, e); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); } }