public HttpResponseMessage Get(int id) { var periodDetialsRequestViewModel = new PeriodDetailsRequestViewModel() { PeriodId = id }; var serviceResponse = _periodDetailsPresenter.GetPeriodicDetailsByPeriodId(periodDetialsRequestViewModel); HttpResponseMessage httpResponse; switch (serviceResponse.StatusCode) { case PeriodicTableStatusCodes.Success: httpResponse = Request.CreateResponse(HttpStatusCode.OK, serviceResponse); break; case PeriodicTableStatusCodes.Error: var internalServiceError = PeriodicTableServerExceptionResponse.GetInternalServiceError(); httpResponse = Request.CreateResponse(HttpStatusCode.InternalServerError, internalServiceError); break; default: var error = new HttpError(GetCorrectErrorMessage(serviceResponse.StatusCode)) { {"ErrorCode", serviceResponse.StatusCode} }; httpResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); break; } return httpResponse; }
public HttpResponseMessage PostSchool([FromBody]SchoolModel schoolToAdd) { if (schoolToAdd.Name == null) { var httpError = new HttpError("Schools must have a name."); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, httpError); } var school = this.repository.Post(new School() { Name = schoolToAdd.Name, Location = schoolToAdd.Location }); if (school.Id == 0) { var httpError = new HttpError("Incorrect database operation."); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, httpError); } return Request.CreateResponse(HttpStatusCode.OK, new SchoolModel() { Id = school.Id, Name = school.Name, Location = school.Location }); }
public override void OnException(HttpActionExecutedContext ctx) { if (!IgnoreExceptions.Contains(ctx.Exception.GetType())) { var statusCode = GetStatus(ctx.Exception.GetType()); var error = new HttpError(ctx.Exception, IncludeErrorDetails(ctx)); var req = ctx.Request; var exLog = ctx.Exception.LogException(e => { e.ActionName = ctx.ActionContext.ActionDescriptor.ActionName; e.ControllerName = ctx.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; e.UserAgent = req.Headers.UserAgent.ToString(); e.RequestUrl = req.RequestUri.ToString(); e.UrlReferer = req.Headers.Referrer?.ToString(); e.UserHostAddress = GetClientIp(req); e.UserHostName = GetClientName(req); e.QueryString = ExceptionEntity.Dump(req.RequestUri.ParseQueryString()); e.Form = (string)(req.Properties.ContainsKey(SignumAuthenticationAndProfilerAttribute.SavedRequestKey) ? req.Properties[SignumAuthenticationAndProfilerAttribute.SavedRequestKey] : null); e.Session = GetSession(req); }); error["ExceptionID"] = exLog.Id.ToString(); ctx.Response = ctx.Request.CreateResponse<HttpError>(statusCode, error); } base.OnException(ctx); }
public HttpResponseMessage CancelReservation(int id) { ReservationModels reserve = db.Reservations.Find(id); ShowModels show = db.Shows.Find(reserve.ShowId); if (reserve != null && WebSecurity.GetUserId(User.Identity.Name) == reserve.UserId) { if (reserve.Status == "C" || reserve.Date <= DateTime.Now) { HttpError cancelError = new HttpError("Invalid cancel operation. The reservation is already cancelled or the show date has passed.") { { "CustomErrorCode", 35 } }; return Request.CreateResponse(HttpStatusCode.BadRequest, cancelError); } db.Entry(reserve).State = EntityState.Modified; reserve.Status = "C"; db.Entry(show).State = EntityState.Modified; show.AvailableSeat += reserve.NumberOfSeats; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return Request.CreateResponse(HttpStatusCode.NotFound); } return Request.CreateResponse(HttpStatusCode.OK); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
public HttpResponseMessage AddLink(Link link) { if (ModelState.IsValid) { //hosting protocol & domain matches this app root. Does not take into consideration any fun routing Uri CurrentUri = HttpContext.Current.Request.Url; string ShortenedUrlHost = CurrentUri.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath; Uri ShortenedUri; if (!String.IsNullOrWhiteSpace(link.ShortenedUrl) && link.IsVanityUrl && !Uri.TryCreate(link.ShortenedUrl, UriKind.Absolute, out ShortenedUri)) { //strip bad vanity chars link.ShortenedUrl = System.Text.RegularExpressions.Regex.Replace(link.ShortenedUrl, "[\\~#%&*{}/:<>?|\"-]", ""); //prepend protocol & host link.ShortenedUrl = ShortenedUrlHost + link.ShortenedUrl; } if(String.IsNullOrWhiteSpace(link.ShortenedUrl) || !Uri.TryCreate(link.ShortenedUrl, UriKind.RelativeOrAbsolute, out ShortenedUri) || (ShortenedUri.IsAbsoluteUri && !ShortenedUri.OriginalString.StartsWith(ShortenedUrlHost))){ //incoming shortened url is empty, not a valid uri, or refers to authority other than the current, //so, generate our own shortened url link.ShortenedUrl = ShortenedUrlHost + UrlShortener.Generate(); link.IsVanityUrl = false; } //Verify this short URL is not in use while (db.Links.Any(l => l.ShortenedUrl == link.ShortenedUrl)) { if (!link.IsVanityUrl) { //if in use and not vanity, regenerate link.ShortenedUrl = ShortenedUrlHost + UrlShortener.Generate(); } else { //if in use and vanity, error var message = "Shortened URL with this vanity path already exists."; HttpError err = new HttpError(message); return Request.CreateResponse(HttpStatusCode.BadRequest, err); } } db.Links.Add(link); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, link); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = link.LinkId })); return response; } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
public static HttpError GetInternalServiceError() { var internalServiceError = new HttpError("Sorry, an error occurred while processing your request.") { {"ErrorCode", (int) PeriodicTableStatusCodes.Error} }; return internalServiceError; }
public override void Handle(ExceptionHandlerContext context) { // Get the Trace ID that was associated with this Exception by the Exception Logger. // This Trace ID was logged with the Exception information and should now be returned to the // consumer of the service so they can call the support Team when there is an issue. string traceId = context.Exception.Data["errorTraceId"] as string; string message = string.Empty; var errorCodes = new List<string>(); HttpError httpError; HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError; // Map Domain Model Exceptions to Http Status Code if (context != null) { if (context.Exception is SqlException) { // Copy the Error Code from the exception, consumer of the service can use this to resolve to // a language dependent error message instead of using the default English error message errorCodes.Add(((SqlException)context.Exception).Number.ToString()); // Copy message from exception, default English error message for the consumer of the service message = context.Exception.Message; if (errorCodes.Contains("50002") || errorCodes.Contains("50001") || errorCodes.Contains("50102") || errorCodes.Contains("50201")) { httpStatusCode = HttpStatusCode.Conflict; } else { httpStatusCode = HttpStatusCode.BadRequest; } } else { // System.Exception: Unexpected Exception (Shielded Exception) // Exception shielding helps prevent a Web service from disclosing information about the // internal implementation of the service when an exception occurs. Only exceptions that // have been sanitized or are safe by design should be returned to the client application. // use the Exception Shielding pattern to sanitize unsafe exceptions by replacing them with // exceptions that are safe by design. // Assign Error Code for Shielded Exception, consumer of service can use this to resolve to // a language dependent error message instead of using the default English error message message = "Please re-try your action. If you continue to get this error, please contact the Administrator with the following details: "; errorCodes.Add(context.Exception.Message); httpStatusCode = HttpStatusCode.InternalServerError; } // Return error message to consumer of service httpError = new HttpError() { { "TraceId", traceId }, { "ErrorMessage", message }, { "ErrorCodes", errorCodes } }; context.Result = new ResponseMessageResult(context.Request.CreateResponse(httpStatusCode, httpError)); } }
public HttpResponseMessage GetById(int id) { var school = this.repository.GetById(id); if (school == null) { var httpError = new HttpError("Such school does not exist"); return Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError); } return Request.CreateResponse(HttpStatusCode.OK, new SchoolModel() { Id = school.Id, Name = school.Name, Location = school.Location }); }
public HttpResponseMessage GetCar(int id) { if ((id % 2) != 0) { var httpError = new HttpError(); httpError.Add("id", "Only \"even numbers\" are accepted as id."); return Request.CreateErrorResponse( HttpStatusCode.InternalServerError, httpError); } return Request.CreateResponse( HttpStatusCode.OK, string.Format("Car {0}", id)); }
public HttpResponseMessage PostStudent([FromBody]StudentModel studentToAdd) { if (studentToAdd.LastName == null) { var httpError = new HttpError("Students must have a last name."); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, httpError); } if ((studentToAdd.Age <0)) { var httpError = new HttpError("Students must have a non-negative age."); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, httpError); } if ((studentToAdd.Grade <= 0) || (studentToAdd.Grade > 12)) { var httpError = new HttpError("Students must have an appropriate grade (1 - 12)."); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, httpError); } var student = this.repository.Post(new Student() { FirstName = studentToAdd.FirstName, LastName = studentToAdd.LastName, Grade = studentToAdd.Grade, Age = studentToAdd.Age }); if (student.Id == 0) { var httpError = new HttpError("Incorrect database operation."); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, httpError); } return Request.CreateResponse(HttpStatusCode.OK, student); }
public HttpResponseMessage GetById(int id) { if (id <= 0) { var httpError = new HttpError("Id should be non-negative integer."); return Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError); } var student = this.repository.GetById(id); if (student == null) { var httpError = new HttpError("Such student does not exist"); return Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError); } return Request.CreateResponse(HttpStatusCode.OK, new StudentModel() { Id = student.Id, FirstName = student.FirstName, LastName = student.LastName, Age = student.Age, Grade = student.Grade }); }
// PUT api/<controller>/5 public HttpResponseMessage Post(UserInfo aUser) { if (ModelState.IsValid) { string phoneQuery = "Select * from userinfo where CellNumber=" + aUser.PhoneNumber + " ;"; string userNameQuery = "Select * from users where UserName='******' ;"; DataSet aDataSet = aGateway.Select(phoneQuery); DataSet anotherDataSet = aGateway.Select(userNameQuery); if (aDataSet.Tables[0].Rows.Count > 0) { var message = string.Format("Duplicate Phone Number"); HttpError err = new HttpError(message); return Request.CreateResponse(HttpStatusCode.NotAcceptable, err); } else if (anotherDataSet.Tables[0].Rows.Count > 0) { var message = string.Format("Duplicate UserName"); HttpError err = new HttpError(message); return Request.CreateResponse(HttpStatusCode.NotAcceptable, err); } else { string usersQuery = "insert into users(UserName,UserCellNumber,UserRoleId) values (@UserName,@CellNumber,"+aUser.UserRole+") "; string userInfoQuery = "INSERT INTO `tikaappdb`.`userinfo` (`UserId`, `UserName`, `FullName`, `FatherName`, `MotherName`, `CellNumber`, `BirthDay`, `CurrentAddress`, `PermanentAddress`, `BirthCertificateID`) VALUES ((select ID from users where UserName='******'), @UserName, @FullName, @FatherName, @MotherName, @CellNumber, @BirthDay, @CurrentAddress, @PermanentAddress, @BirthCertificateID);"; Hashtable aHashtable = new Hashtable(); aHashtable.Add("id", aUser.Id); // aHashtable.Add("UserID", 101); aHashtable.Add("UserName", aUser.UserName); aHashtable.Add("FullName", aUser.FullName); aHashtable.Add("FatherName", aUser.FatherName); aHashtable.Add("MotherName", aUser.MotherName); aHashtable.Add("CellNumber", aUser.PhoneNumber); aHashtable.Add("BirthDay", aUser.BirthDate); aHashtable.Add("CurrentAddress", aUser.CurrentAddress); aHashtable.Add("PermanentAddress", aUser.PermanentAddress); aHashtable.Add("BirthCertificateID", aUser.BirthCertificateID); aGateway.Insert(usersQuery, aHashtable); aGateway.Insert(userInfoQuery, aHashtable); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, aUser); return response; } } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }
public HttpResponseMessage GetBySubjectAndValue(string subject, string value) { if ((subject == null) || (subject == string.Empty)) { var httpError = new HttpError("Subject should be specified."); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, httpError); } decimal decimalValue; value = value.Replace('.', ','); if ((value == null) || (value == string.Empty) || (!decimal.TryParse(value, out decimalValue))) { var httpError = new HttpError("Value should be specified and be parsable as decimal."); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, httpError); } var students = this.repository.GetBySubjectAndValue(subject, decimalValue); List<StudentModel> modelsToReturn = new List<StudentModel>(); foreach (var student in students) { modelsToReturn.Add(new StudentModel { Id = student.Id, FirstName = student.FirstName, LastName = student.LastName, Age = student.Age, Grade = student.Grade }); } return Request.CreateResponse(HttpStatusCode.OK, modelsToReturn); }
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { base.HandleUnauthorizedRequest(actionContext); if (string.IsNullOrEmpty(Roles)) return; var objectContent = actionContext.Response.Content as ObjectContent<HttpError>; if (objectContent == null) return; var httpError1 = objectContent.Value as HttpError; if (httpError1 == null || !string.IsNullOrEmpty(httpError1.MessageDetail)) return; var httpError2 = new HttpError(httpError1.Message); if (actionContext.ControllerContext.RequestContext.Principal.Identity.IsAuthenticated) { IDictionary<string, ActionRoleItem> dictionary = ActionRole.ToListDictionary(); string str = Roles; if (dictionary.ContainsKey(Roles)) str = dictionary[Roles].RoleKeyLabel; httpError2.MessageDetail = string.Format("You must have permission in [{0}] to access this page.\n\nPls contact admin to support.", (object)str); actionContext.Response.Content = new ObjectContent<HttpError>(httpError2, objectContent.Formatter); } else { httpError2.MessageDetail = "You need login to access this page."; actionContext.Response.Content = new ObjectContent<HttpError>(httpError2, objectContent.Formatter); } }
public static HttpResponseMessage GenerateCustomError(this HttpRequestMessage request, ErrorEnum error) { var customError = new HttpError(); var statusCode = 400; var errorMessage = ""; switch (error) { case ErrorEnum.MissingRequiredQueryParameter: { statusCode = 400; errorMessage = "A required query parameter was not specified for this request."; break; }; case ErrorEnum.UnsupportedQueryParameter: { statusCode = 400; errorMessage = "One of the query parameters specified in the request URI is not supported."; break; }; case ErrorEnum.InvalidQueryParameterValue: { statusCode = 400; errorMessage = "An invalid value was specified for one of the query parameters in the request URI."; break; }; case ErrorEnum.OutOfRangeQueryParameterValue: { statusCode = 400; errorMessage = "A query parameter specified in the request URI is outside the permissible range."; break; }; case ErrorEnum.RequestUrlFailedToParse: { statusCode = 400; errorMessage = "The url in the request could not be parsed."; break; }; case ErrorEnum.InvalidUri: { statusCode = 400; errorMessage = "The requested URI does not represent any resource on the server."; break; }; case ErrorEnum.InvalidAuthenticationInfo: { statusCode = 400; errorMessage = "The authentication information was not provided in the correct format. Verify the value of Authorization header."; break; }; case ErrorEnum.AuthenticationFailed: { statusCode = 403; errorMessage = "The server failed to authenticate the request. Verify that the value of authorization header is formed correctly and includes the signature."; break; }; case ErrorEnum.ResourceNotFound: { statusCode = 404; errorMessage = "The specified resource does not exist."; break; }; case ErrorEnum.AccountIsDisabled: { statusCode = 403; errorMessage = "The specified account is disabled."; break; }; case ErrorEnum.InsufficientAccountPermissions: { statusCode = 403; errorMessage = "The account being accessed does not have sufficient permissions to execute this operation."; break; }; case ErrorEnum.InternalError: { statusCode = 500; errorMessage = "The server encountered an internal error. Please retry the request."; break; }; case ErrorEnum.OperationTimedOut: { statusCode = 500; errorMessage = "The operation could not be completed within the permitted time."; break; }; case ErrorEnum.ServerBusy: { statusCode = 503; errorMessage = "The server is currently unable to receive requests. Please retry your request."; break; }; case ErrorEnum.AccountExisting: { statusCode = 400; errorMessage = "User with account's Facebook or account's LinkedIn already exists."; break; } } customError["status_code"] = statusCode.ToString(); customError["error_code"] = error.ToString(); customError["error"] = errorMessage; HttpStatusCode code = HttpStatusCode.InternalServerError; switch (statusCode) { case 400: { code = HttpStatusCode.BadRequest; break; } case 404: { code = HttpStatusCode.NotFound; break; } case 403: { code = HttpStatusCode.Forbidden; break; } case 503: { code = HttpStatusCode.ServiceUnavailable; break; } } return request.CreateErrorResponse(code, customError); }
public HttpResponseMessage Get(string Entrada) { try { #region Get Keys and Vectors in Firebase FireBaseEntrada EntradaFireBaseChaveAES = new FireBaseEntrada { AuthSecret = "iY8kzmEr6cvEhTo6fdYbKDsdVAD4xJZR46NdGsGf", BasePath = "https://cryptography.firebaseio.com/", item = "AES/KEY" }; FireBaseRetorno RetornoFireBaseChaveAES = new FireBaseRetorno(); RetornoFireBaseChaveAES = FireBase.GetFireBaseData(EntradaFireBaseChaveAES); string chaveAes = RetornoFireBaseChaveAES.Body.Replace("\"", ""); FireBaseEntrada EntradaFireBaseVetorAES = new FireBaseEntrada { AuthSecret = "iY8kzmEr6cvEhTo6fdYbKDsdVAD4xJZR46NdGsGf", BasePath = "https://cryptography.firebaseio.com/", item = "AES/VECTOR" }; FireBaseRetorno RetornoFireBaseVetorAES = new FireBaseRetorno(); RetornoFireBaseVetorAES = FireBase.GetFireBaseData(EntradaFireBaseVetorAES); string vetorAes = RetornoFireBaseVetorAES.Body.Replace("\"", ""); FireBaseEntrada EntradaFireBaseChaveDES = new FireBaseEntrada { AuthSecret = "iY8kzmEr6cvEhTo6fdYbKDsdVAD4xJZR46NdGsGf", BasePath = "https://cryptography.firebaseio.com/", item = "DES/KEY" }; FireBaseRetorno RetornoFireBaseChaveDES = new FireBaseRetorno(); RetornoFireBaseChaveDES = FireBase.GetFireBaseData(EntradaFireBaseChaveDES); string chaveDES = RetornoFireBaseChaveDES.Body.Replace("\"", ""); FireBaseEntrada EntradaFireBaseVetorDES = new FireBaseEntrada { AuthSecret = "iY8kzmEr6cvEhTo6fdYbKDsdVAD4xJZR46NdGsGf", BasePath = "https://cryptography.firebaseio.com/", item = "DES/VECTOR" }; FireBaseRetorno RetornoFireBaseVetorDES = new FireBaseRetorno(); RetornoFireBaseVetorDES = FireBase.GetFireBaseData(EntradaFireBaseVetorDES); string vetorDES = RetornoFireBaseVetorDES.Body.Replace("\"", ""); FireBaseEntrada EntradaFireBaseChaveRijndael = new FireBaseEntrada { AuthSecret = "iY8kzmEr6cvEhTo6fdYbKDsdVAD4xJZR46NdGsGf", BasePath = "https://cryptography.firebaseio.com/", item = "RIJNDAEL/KEY" }; FireBaseRetorno RetornoFireBaseChaveRijndael = new FireBaseRetorno(); RetornoFireBaseChaveRijndael = FireBase.GetFireBaseData(EntradaFireBaseChaveRijndael); string chaveRijndael = RetornoFireBaseChaveRijndael.Body.Replace("\"", ""); FireBaseEntrada EntradaFireBaseVetorRijndael = new FireBaseEntrada { AuthSecret = "iY8kzmEr6cvEhTo6fdYbKDsdVAD4xJZR46NdGsGf", BasePath = "https://cryptography.firebaseio.com/", item = "RIJNDAEL/VECTOR" }; FireBaseRetorno RetornoFireBaseVetorRijndael = new FireBaseRetorno(); RetornoFireBaseVetorRijndael = FireBase.GetFireBaseData(EntradaFireBaseVetorRijndael); string vetorRijndael = RetornoFireBaseVetorRijndael.Body.Replace("\"", ""); #endregion #region Cryptography Level 1 ParametroEntreda ParmatroParametroAES = new ParametroEntreda { plainText = Entrada, Key = Convert.FromBase64String(chaveAes), IV = Convert.FromBase64String(vetorAes), OrigemChamadaToken = HttpContext.Current.Request.Url.AbsoluteUri }; DAO.AES cryptAES = new DAO.AES(); string encryptedAES = Convert.ToBase64String(cryptAES.EncryptAES(ParmatroParametroAES)); #endregion #region Cryptography Level 2 ParametroEntreda ParmatroParametroDES = new ParametroEntreda { plainText = encryptedAES, Key = Convert.FromBase64String(chaveDES), IV = Convert.FromBase64String(vetorDES), OrigemChamadaToken = HttpContext.Current.Request.Url.AbsoluteUri }; DAO.DES cryptDES = new DAO.DES(); string encryptedDES = Convert.ToBase64String(cryptDES.EncryptDES(ParmatroParametroDES)); #endregion #region Cryptography Level 3 ParametroEntreda ParmatroParametroRijndael = new ParametroEntreda { plainText = encryptedDES, Key = Convert.FromBase64String(chaveRijndael), IV = Convert.FromBase64String(vetorRijndael), OrigemChamadaToken = HttpContext.Current.Request.Url.AbsoluteUri }; DAO.Rijndael cryptRijndael = new DAO.Rijndael(); string encryptedRijndael = Convert.ToBase64String(cryptRijndael.EncryptRijndael(ParmatroParametroRijndael)); #endregion ParametroRetorno Retorno = new ParametroRetorno { CodigoRetorno = HttpStatusCode.OK.ToString(), Mensagem = "Criptografia gerada com sucesso", Retorno = encryptedRijndael.Replace("/", "InfoTech2u") }; return Request.CreateResponse(HttpStatusCode.OK, Retorno); ; } catch (KeyNotFoundException) { string mensagem = string.Format("Não foi possível criptografar a entrada: ", Entrada); HttpError error = new HttpError(mensagem); return Request.CreateResponse(HttpStatusCode.NotFound, error); } }
public HttpResponseMessage PostReservationModels([FromBody]ReservationModels reserve) { ShowModels show = db.Shows.Find(reserve.ShowId); if (WebSecurity.GetUserId(User.Identity.Name) != reserve.UserId) { return Request.CreateResponse(HttpStatusCode.BadRequest); } if (show == null) { HttpError runtimeError = new HttpError("Sorry, the show reserved no longer exists.") { { "CustomErrorCode", 36 } }; return Request.CreateResponse(HttpStatusCode.BadRequest, runtimeError); } if (show.Date <= DateTime.Now) { HttpError cancelError = new HttpError("The show date " + show.Date.ToShortDateString() + " has passed.") { { "CustomErrorCode", 37 } }; return Request.CreateResponse(HttpStatusCode.BadRequest, cancelError); } if (show.AvailableSeat >= reserve.NumberOfSeats) { show.AvailableSeat -= reserve.NumberOfSeats; reserve.BeginTime = show.BeginTime; reserve.Date = show.Date; reserve.Email = db.UserProfiles.Find(reserve.UserId).Email; reserve.SubmitDate = DateTime.Today; reserve.SubmitTime = DateTime.Now.TimeOfDay.ToString(); reserve.Status = "V"; try { db.Entry(show).State = EntityState.Modified; db.Reservations.Add(reserve); db.SaveChanges(); } catch (Exception ex) { HttpError runtimeError = new HttpError("Sorry, your reservation is failed." + ex.Message) { { "CustomErrorCode", 38 } }; return Request.CreateResponse(HttpStatusCode.BadRequest, runtimeError); } try { SendWelcomeMessage(reserve.Email, reserve); } catch (Exception ex) {//if email sent failed, do nonthing here } //return the link to the new reservation HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, reserve); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = reserve.ReserveId })); return response; } else { HttpError reserveError = new HttpError("Sorry, there is not enough available seats. \nThe total seats available now is " + show.AvailableSeat) { { "CustomErrorCode", 39 } }; return Request.CreateResponse(HttpStatusCode.BadRequest, reserveError); } }
/// <summary> /// Unwraps an arbitrarily deep collection of inner exceptions inside an /// <see cref="HttpError"/> instance into a list of error messages. /// </summary> /// <param name="httpError">The input <see cref="HttpError"/>.</param> /// <param name="messages">The list of messages to which the exceptions should be added.</param> private static void AddExceptions(HttpError httpError, List<string> messages) { object exceptionMessageObject = null; object exceptionTypeObject = null; object stackTraceObject = null; object innerExceptionObject = null; for (int i = 0; httpError != null; i++) { // For uniqueness, key names append the depth of inner exception string indexText = i == 0 ? String.Empty : String.Format("[{0}]", i); if (httpError.TryGetValue(ExceptionTypeKey, out exceptionTypeObject)) { messages.Add(String.Format(EventSourceResources.HttpErrorExceptionTypeFormat, indexText, exceptionTypeObject)); } if (httpError.TryGetValue(ExceptionMessageKey, out exceptionMessageObject)) { messages.Add(String.Format(EventSourceResources.HttpErrorExceptionMessageFormat, indexText, exceptionMessageObject)); } if (httpError.TryGetValue(StackTraceKey, out stackTraceObject)) { messages.Add(String.Format(EventSourceResources.HttpErrorStackTraceFormat, indexText, stackTraceObject)); } if (!httpError.TryGetValue(InnerExceptionKey, out innerExceptionObject)) { break; } httpError = innerExceptionObject as HttpError; } }
/// <summary> /// Downloads the file from Repository. /// </summary> /// <param name="fileId">File Id.</param> /// <param name="user">User instance.</param> /// <returns>File stream.</returns> private HttpResponseMessage DownloadFileFromRepository(int fileId, User user) { HttpError error; try { if (fileId <= 0) { error = new HttpError(string.Format(MessageStrings.Argument_Error_Message_Template, "fileId")); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } var file = this.fileService.GetFiles(p => p.FileId == fileId && p.CreatedBy == user.UserId).FirstOrDefault(); if (file == null) { error = new HttpError(MessageStrings.FileDoesntExist) { { "FileId", fileId } }; return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } if (file.RepositoryId == null) { error = new HttpError(MessageStrings.File_Repository_Is_Null) { { "FileId", fileId } }; return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } DM.Repository repository = this.repositoryService.GetRepositoryById((int)file.RepositoryId); if (repository == null) { error = new HttpError(MessageStrings.Repository_Not_Found) { { "RepositoryId", (int)file.RepositoryId } }; return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } RepositoryCredentials repositoryCredentials = GetRepsitoryCredentials(); this.fileService = this.fileServiceFactory.GetFileService(repository.BaseRepository.Name); DataFile dataFile = this.fileService.DownLoadFileFromRepository(file, repository, user, repositoryCredentials); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(new MemoryStream(dataFile.FileContent)); result.Content.Headers.ContentType = new MediaTypeHeaderValue(Constants.APPLICATION_X_ZIP); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = dataFile.FileName; return result; } catch (ArgumentNullException ane) { message = string.Format(MessageStrings.Argument_Error_Message_Template, ane.ParamName); status = HttpStatusCode.BadRequest; } catch (FileDownloadException downloadException) { if (downloadException.FileDownloadExceptionType == FileDownloadExceptionType.DownloadUrlNotFound.ToString()) { error = downloadException.GetHttpError(MessageStrings.Download_URL_Empty); } else { error = downloadException.GetHttpError(string.Empty); } return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } catch (WebException ex) { // If status code is 404 then send the custom message indicating file does not exist in repository. // else read the message and send it to client as text. HttpResponseMessage response; if (ex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound) { error = new HttpError(MessageStrings.FileDoesNotExistInRepository); response = Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } else { string errorText = string.Empty; using (Stream st = ((System.Net.WebException)(ex)).Response.GetResponseStream()) using (StreamReader reader = new StreamReader(st)) { errorText = reader.ReadToEnd(); } error = new HttpError(errorText); response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } return response; } return Request.CreateErrorResponse(status, message); }
public HttpResponseMessage DownloadFileFromRepository(string nameIdentifier, int fileId) { HttpError error; try { Check.IsNotEmptyOrWhiteSpace(nameIdentifier, "nameIdentifier"); User user = IdentityHelper.GetUser(this.userService, nameIdentifier); if (user == null) { error = new HttpError(MessageStrings.User_Not_Found) { { "nameIdentifier", nameIdentifier } }; return Request.CreateErrorResponse(HttpStatusCode.NotFound, error); } return this.DownloadFileFromRepository(fileId, user); } catch (ArgumentException ex) { message = string.Format(CultureInfo.CurrentCulture, MessageStrings.Argument_Error_Message_Template, ex.ParamName); status = HttpStatusCode.BadRequest; } return Request.CreateErrorResponse(status, message); }
/// <summary> /// Unwrap model binding errors into human-readable error messages. /// </summary> /// <param name="httpError">The input <see cref="HttpError"/> to be /// treated as a set of model binding errors.</param> /// <returns></returns> private static string FormatModelStateErrors(HttpError httpError) { List<string> messages = new List<string>(); foreach (var pair in httpError) { IEnumerable<string> errorList = pair.Value as IEnumerable<string>; if (errorList != null) { messages.Add(String.Format(EventSourceResources.HttpErrorModelStatePairFormat, pair.Key, String.Join(", ", errorList))); } } return String.Format(EventSourceResources.HttpErrorModelStateErrorFormat, String.Join(", ", messages)); }
public HttpResponseMessage Get(string AuthSecret, string BasePath, string command) { try { IFirebaseConfig config = new FirebaseConfig { AuthSecret = AuthSecret, BasePath = BasePath }; IFirebaseClient client = new FirebaseClient(config); FirebaseResponse response; if (String.IsNullOrWhiteSpace(command)) response = client.Get("/"); else response = client.Get("/"+command.ToString()); return Request.CreateResponse(HttpStatusCode.OK, response); ; } catch (KeyNotFoundException) { string mensagem = string.Format("Não foi possível criptografar a entrada: ", command); HttpError error = new HttpError(mensagem); return Request.CreateResponse(HttpStatusCode.NotFound, error); } }