public static void Err(ILogSource loggr, RestServiceException ex) { bool showInnerException = true; string msg = ""; switch (ex.Code) { case HttpStatusCode.NotAcceptable: msg = "Invalid JSON object format."; showInnerException = false; break; case HttpStatusCode.Conflict: msg = "Value already exists in the database."; break; case HttpStatusCode.BadRequest: msg = "Unrecognized data fields."; break; case HttpStatusCode.Forbidden: var usr = ex.InnerException.Message.Between("Access denied for user ", ").", true); msg = "{0} is not allowed to create new nodes.".f(usr.Quotify()); showInnerException = false; break; } OnAnyEvent.Error(loggr, ex, msg, showInnerException); }
public static void Err(ILogSource loggr, RestServiceException ex) { string msg = ""; switch (ex.Code) { case HttpStatusCode.InternalServerError: msg = "TODO: make this specific"; break; } OnAnyEvent.Error(loggr, ex, msg); }
public static void Err(ILogSource loggr, RestServiceException ex) { bool showInnerException = true; string msg = ""; switch (ex.Code) { case HttpStatusCode.NotFound: msg = "Requested node does not exist on the server."; showInnerException = false; break; } OnAnyEvent.Error(loggr, ex, msg, showInnerException); }
public static bool Err(ILogSource loggr, RestServiceException ex) { bool showInnerException = true; string msg = ""; switch (ex.Code) { case HttpStatusCode.NotFound: msg = "Resource not found: " + ex.BaseUrl.Slash(ex.Resource); showInnerException = false; break; } OnAnyEvent.Error(loggr, ex, msg, showInnerException); return(false); }
public static bool Err(ILogSource loggr, RestServiceException ex) { bool showInnerException = true; string msg = ""; switch (ex.Code) { case HttpStatusCode.BadRequest: msg = "Invalid field values."; showInnerException = false; break; } OnAnyEvent.Error(loggr, ex, msg, showInnerException); return(false); }
public static bool Err(ILogSource loggr, RestServiceException ex) { bool showInnerException = true; string msg = ""; switch (ex.Code) { case HttpStatusCode.Unused: var usr = ex.InnerException.Message.Between("Access denied for user ", ").", true); msg = "{0} is not allowed to delete this file.".f(usr.Quotify()); showInnerException = false; break; } OnAnyEvent.Error(loggr, ex, msg, showInnerException); return(false); }
public static void Error(ILogSource loggr, RestServiceException ex, string msg, bool showInnerException = true) { if (msg.IsBlank()) { msg = "Http Error {0} : {1}".f((int)ex.Code, ex.Code); } //var line1 = loggr.Title; var line2 = showInnerException ? ex.Details(false, false) : "\t" + ex.Message; //loggr.Title = line1; loggr.Error_n("Error encountered", msg + L.F + line2); }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <returns></returns> private async Task <Exception> ParseResponseErrorMessageContent(HttpResponseMessage response) { Exception exceptionResult; RestResponseMessage responseMessage = response as RestResponseMessage; if (responseMessage != null) { exceptionResult = responseMessage.Exception; } else { string errorMessage = await response.Content.ReadAsStringAsync(); exceptionResult = new RestServiceException((int)response.StatusCode, errorMessage); } return(exceptionResult); }
public static void Err(ILogSource loggr, RestServiceException ex) { string msg = ""; switch (ex.Code) { case HttpStatusCode.Forbidden: msg = "SSL certificate is invalid."; break; case HttpStatusCode.ServiceUnavailable: msg = "Unable to reach the server."; break; case HttpStatusCode.Unauthorized: msg = "Server rejected application credentials."; break; } OnAnyEvent.Error(loggr, ex, msg); }
public static bool Err(ILogSource loggr, RestServiceException ex) { bool showInnerException = true; string msg = ""; switch (ex.Code) { case HttpStatusCode.NotAcceptable: msg = "Invalid JSON object format."; showInnerException = false; break; case HttpStatusCode.Forbidden: var usr = ex.InnerException.Message.Between("Access denied for user ", ").", true); msg = "{0} is not allowed to edit this node.".f(usr.Quotify()); showInnerException = false; break; } OnAnyEvent.Error(loggr, ex, msg, showInnerException); return(false); }
public async Task <IResponseShim> Send(IRequestShim request, CancellationToken cancelToken, string taskIntro, object successMessage, params object[] successMsgArgs) { Beginning: var client = CreateClient(request); var req = request as RequestShim; //Trace_i(taskIntro.IsBlank() ? " [{0}] {1} ...".f(req.Method.ToString().ToUpper(), req.Resource) : taskIntro); RestServiceException err = null; IRestResponse resp = null; try { resp = await client.Execute(req.UnShim(), cancelToken); } catch (HttpRequestException ex) { err = RestErr(ex, req); LogError($"client.Execute {req.Method}", err); if (LowRetryIntervalSeconds > -1) { await TaskEx.Delay(1000 *LowRetryIntervalSeconds); goto Beginning; } throw err; } catch (Exception ex) { throw Unhandled(ex); } finally { client.Dispose(); } //if (resp != null) // Trace_o((successMessage == null) ? "response: [{0}] {1}".f((int)resp.StatusCode, resp.StatusDescription.Quotify()) : successMessage.ToString().f(successMsgArgs)); RaiseResponseReceived(true); return(new ResponseShim(resp, request, this.BaseUrl, err)); }
private static RestServiceException CastWebException(WebException ex, RestSharpClientShim client, RequestShim req) { var inr = ex.InnerException; if (inr == null) { return(Unknown("A WebException with NO innards", ex, client, req)); } if (inr.GetType().Name == "AuthenticationException") { return(RestServiceException.InvalidSsl( req.Method, client.BaseUrl, req.Resource, ex)); } if (inr.GetType().Name == "SocketException") { return(RestServiceException.Unavailable( req.Method, client.BaseUrl, req.Resource, ex)); } return(Unknown("A WebException with UNKNOWN innards", ex, client, req)); }
private static RestServiceException ParseByMessage(Exception ex, RestSharpClientShim client, RequestShim req) { if (ex == null) { return(null); } if (ex.Message.Contains("remote name could not be resolved")) { return(RestServiceException.Unresolvable( req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("Missing required argument ")) { return(RestServiceException.BadRequest("Missing required argument : " + ex.Message.Between("Missing required argument ", ").", true).Quotify(), req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("401")) { return(RestServiceException.Unauthorized( req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("403")) { return(RestServiceException.Forbidden( req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("404")) { return(RestServiceException.NotFound( req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("406")) { return(RestServiceException.NotAcceptable( req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("Integrity constraint violation: ")) { return(RestServiceException.Conflict(ex.Message .Between("constraint violation: ", ").", true) + ".", req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("Unknown data property")) { return(RestServiceException.BadRequest("Unknown data property " + ex.Message.Between("Unknown data property ", ".).", true).Quotify(), req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("value list does not match column list: ")) { return(RestServiceException.BadRequest(ex.Message .Between("value list does not match column list: ", ").", true) + ".", req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("Internal Server Error : An error occurred")) { return(RestServiceException.InternalServer(ex.Message .Between("An error occurred ", ").", true) + ".", req.Method, client.BaseUrl, req.Resource, ex)); } if (ex.Message.Contains("Could not create destination directory")) { return(RestServiceException.InternalServer( "Could not create destination directory for file.", req.Method, client.BaseUrl, req.Resource, ex)); } return(null); }
private static RestServiceException Unknown(string clue, Exception ex, RestSharpClientShim client, RequestShim req) { return(RestServiceException.Unknown(clue, req.Method, client.BaseUrl, req.Resource, ex)); }
public void ProcessRequest(HttpContext context) { App app = CodeTorch.Core.Configuration.GetInstance().App; StringBuilder builder = new StringBuilder(); StringWriter writer = new StringWriter(builder); try { if (Me == null) { if (context.Request.Path.ToLower().EndsWith("xml")) { Format = "xml"; } throw new ApplicationException("No service has been configured for this path"); } DataCommand command = null; RestServiceMethodReturnTypeEnum returnType = RestServiceMethodReturnTypeEnum.None; //collect parameters DataTable dt = null; XmlDocument doc = null; context.Response.TrySkipIisCustomErrors = true; if (Format.ToLower() == "json") { context.Response.ContentType = "application/json"; } else { context.Response.ContentType = "text/xml"; } BaseRestServiceMethod method = Me.Methods.Where(i => (i.Action.ToString() == HttpContext.Current.Request.HttpMethod)).SingleOrDefault(); if (method != null) { //pass parameters - minus dbcommand parameters to datacommand DataCommandService dataCommandDB = DataCommandService.GetInstance(); if (String.IsNullOrEmpty(method.RequestDataCommand)) { throw new ApplicationException(String.Format("Request Data Command has not been configured for this service - {0}", Me.Name)); } command = DataCommand.GetDataCommand(method.RequestDataCommand); if (command == null) { throw new ApplicationException(String.Format("Request Data Command - {0} - could not be found in configuration", method.RequestDataCommand)); } List <ScreenDataCommandParameter> parameters = GetPopulatedCommandParameters(method.RequestDataCommand, method.DataCommands, null); returnType = method.ReturnType; //execute request datacommand and return data if applicable switch (command.ReturnType) { case DataCommandReturnType.Integer: object newID = dataCommandDB.ExecuteDataCommand(method.RequestDataCommand, parameters); if (method is PostRestServiceMethod) { DataCommand postCommand = null; PostRestServiceMethod postMethod = (PostRestServiceMethod)method; returnType = postMethod.ReturnType; if (!String.IsNullOrEmpty(postMethod.ResponseDataCommand)) { postCommand = DataCommand.GetDataCommand(postMethod.ResponseDataCommand); if (postCommand == null) { throw new ApplicationException(String.Format("Response Data Command - {0} - could not be found in configuration", postMethod.ResponseDataCommand)); } parameters = GetPopulatedCommandParameters(postMethod.ResponseDataCommand, method.DataCommands, newID); switch (returnType) { case RestServiceMethodReturnTypeEnum.DataRow: case RestServiceMethodReturnTypeEnum.DataTable: dt = dataCommandDB.GetDataForDataCommand(postMethod.ResponseDataCommand, parameters); break; case RestServiceMethodReturnTypeEnum.Xml: doc = dataCommandDB.GetXmlDataForDataCommand(postMethod.ResponseDataCommand, parameters); break; } } } if (method is PutRestServiceMethod) { PutRestServiceMethod putMethod = (PutRestServiceMethod)method; returnType = putMethod.ReturnType; if (!String.IsNullOrEmpty(putMethod.ResponseDataCommand)) { parameters = GetPopulatedCommandParameters(putMethod.ResponseDataCommand, method.DataCommands, newID); dt = dataCommandDB.GetDataForDataCommand(putMethod.ResponseDataCommand, parameters); } } break; case DataCommandReturnType.Xml: doc = dataCommandDB.GetXmlDataForDataCommand(method.RequestDataCommand, parameters); break; default: dt = dataCommandDB.GetDataForDataCommand(method.RequestDataCommand, parameters); break; } //in certain cases execute response datacommand } else { throw new NotSupportedException(); } //get data if any if ( ((dt != null) && (returnType == RestServiceMethodReturnTypeEnum.DataTable)) || ((dt != null) && (returnType == RestServiceMethodReturnTypeEnum.DataRow)) || ((doc != null) && (returnType == RestServiceMethodReturnTypeEnum.Xml)) ) { if (Format.ToLower() == "json") { using (JsonWriter json = new JsonTextWriter(writer)) { DataColumnCollection columns = null; switch (returnType) { case RestServiceMethodReturnTypeEnum.DataTable: columns = dt.Columns; BuildJsonArrayResponse(app, context, method, command, dt, json, columns); break; case RestServiceMethodReturnTypeEnum.DataRow: columns = dt.Columns; BuildJsonObjectResponse(app, context, method, command, dt, json, columns); break; case RestServiceMethodReturnTypeEnum.Xml: BuildJsonXmlObjectResponse(app, method, builder, doc); break; } } } else { //xml using (XmlWriter xml = new XmlTextWriter(writer)) { DataColumnCollection columns = null; switch (method.ReturnType) { case RestServiceMethodReturnTypeEnum.DataTable: columns = dt.Columns; BuildXmlListResponse(app, context, method, command, dt, xml, columns); break; case RestServiceMethodReturnTypeEnum.DataRow: columns = dt.Columns; BuildXmlItemResponse(app, context, method, command, dt, xml, columns); break; case RestServiceMethodReturnTypeEnum.Xml: BuildXmlObjectResponse(app, method, doc, xml); break; } } } } //perform any special post processing //string url = ((System.Web.Routing.Route)(RouteData.Route)).Url; //context.Response.Write("From the handler at " + DateTime.Now + " - " + Me.Name + " - " + url + " - " + HttpContext.Current.Request.HttpMethod); //context.Response.ContentType = "text/xml"; //context.Response.Write(dt.DataSet.GetXml()); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.Write(builder.ToString()); } catch (CodeTorchException cex) { builder = new StringBuilder(); RestServiceException exception = new RestServiceException(); exception.Status = (int)HttpStatusCode.InternalServerError; exception.Message = cex.Message; exception.MoreInfo = cex.MoreInfo; exception.ErrorCode = cex.ErrorCode; context.Response.TrySkipIisCustomErrors = true; context.Response.StatusCode = exception.Status; SerializeRestException(app, context, builder, writer, exception); } catch (Exception ex) { builder = new StringBuilder(); RestServiceException exception = new RestServiceException(); exception.Status = (int)HttpStatusCode.InternalServerError; exception.Message = ex.Message; context.Response.TrySkipIisCustomErrors = true; context.Response.StatusCode = exception.Status; SerializeRestException(app, context, builder, writer, exception); } }
private void SerializeRestException(App app, HttpContext context, StringBuilder builder, StringWriter writer, RestServiceException exception) { if (Format.ToLower() == "json") { if (app.RestServiceResponseMode == RestServiceResponseMode.Simple) { context.Response.Write(JsonConvert.SerializeObject(exception)); } else { StructuredError err = new StructuredError { Error = exception }; context.Response.Write(JsonConvert.SerializeObject(err)); } } else { System.Xml.Serialization.XmlSerializer x = null; XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; if (app.RestServiceResponseMode == RestServiceResponseMode.Simple) { x = new System.Xml.Serialization.XmlSerializer(exception.GetType()); using (XmlWriter xmlwriter = XmlWriter.Create(builder, settings)) { x.Serialize(xmlwriter, exception); writer.Close(); } } else { StructuredError err = new StructuredError { Error = exception }; x = new System.Xml.Serialization.XmlSerializer(err.GetType()); using (XmlWriter xmlwriter = XmlWriter.Create(builder, settings)) { x.Serialize(xmlwriter, err); writer.Close(); } } context.Response.Write(builder.ToString()); } }