public HttpResponseMessage GetLeaderBoards(HttpRequestMessage request) { GenericApiResponse response = new GenericApiResponse(); try { var responseSuccess = interactor.createResponseSaveJson(); if (responseSuccess != null) { return(Request.CreateResponse <IResponse>(HttpStatusCode.OK, responseSuccess)); } else { response.HttpCode = 500; response.Message = "something went wrong"; return(Request.CreateResponse <IResponse>(HttpStatusCode.BadRequest, response)); } } catch (Exception) { response.HttpCode = 500; response.Message = "something went wrong"; return(Request.CreateResponse <IResponse>(HttpStatusCode.BadRequest, response)); } }
public ActionResult <GenericApiResponse <List <Empleado> > > GetEmpleados(int id) { var puesto = contexto.Puesto.Include(e => e.Empleados).FirstOrDefault(p => p.Id == id); GenericApiResponse <List <Empleado> > response = new GenericApiResponse <List <Empleado> >(); if (puesto == null) { response.OK = false; response.Error.title = "Puesto no existe"; response.Error.error = $"No se encontro el puesto con id {id}"; return(NotFound(response)); } if (puesto.Empleados.Count == 0) { response.OK = false; response.Error.title = "Lista vacia"; response.Error.error = $"No se encontraron empleados registrados para el puesto con id {id}"; return(NotFound(response)); } response.OK = true; response.Data = puesto.Empleados.ToList(); return(response); }
public IResponse createSuccessResponse(string search) { GenericApiResponse response = new GenericApiResponse(); List <LeaderBoardsResponse> list = new List <LeaderBoardsResponse>(); LeaderBoardsResponse responseLeaderBoards = new LeaderBoardsResponse(); try { var appData = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Repository"); // read JSON directly from a file //using (StreamReader file = File.OpenText(appData + "\\LeaderBoards.json")) var jsonText = File.ReadAllText(appData + "\\LeaderBoards.json"); var leaderBoards = JsonConvert.DeserializeObject <List <LeaderBoardsResponse> >(jsonText); responseLeaderBoards = (from l in leaderBoards where l.filter == search select new LeaderBoardsResponse { Leaderboards = l.Leaderboards, LastWinner = l.LastWinner }).FirstOrDefault(); return(responseLeaderBoards); } catch (Exception ex) { Console.WriteLine(ex.InnerException); responseLeaderBoards = null; return(responseLeaderBoards); } }
public HttpResponseMessage Post(HttpRequestMessage request, [FromBody] LeaderBoardsRequest search) { GenericApiResponse response = new GenericApiResponse(); if (!string.IsNullOrEmpty(search.Search)) { var responseSuccess = interactor.createSuccessResponse(search.Search); if (responseSuccess != null) { return(Request.CreateResponse <IResponse>(HttpStatusCode.OK, responseSuccess)); } else { response.HttpCode = 500; response.Message = "something went wrong"; return(Request.CreateResponse <IResponse>(HttpStatusCode.BadRequest, response)); } } else { response.HttpCode = 400; response.Message = "search parameter cannot be empty"; return(Request.CreateResponse <IResponse>(HttpStatusCode.BadRequest, response)); } }
public GenericApiResponse <Descuento> ModificarDescuento(int id, [FromBody] Descuento descuento) { GenericApiResponse <Descuento> response = new GenericApiResponse <Descuento>(); if (id != descuento.Id) { response.OK = false; response.Error.title = "Id no coincide"; response.Error.error = "El id no coincide con el id del cuerpo"; return(response); } var temp = contexto.Descuento.Find(id); if (temp == null) { response.OK = false; response.Error.title = "No se encontro el registro"; response.Error.error = $"No se encontro el descuento con id= {id} para ser modificado"; return(response); } temp.Descripcion = descuento.Descripcion; temp.Porcentaje = descuento.Porcentaje; contexto.Entry(temp).State = EntityState.Modified; contexto.SaveChanges(); response.OK = true; response.Data = descuento; return(response); }
public GenericApiResponse <Bonificacion> ModificarBonificacion(int id, [FromBody] Bonificacion bonificacion) { GenericApiResponse <Bonificacion> response = new GenericApiResponse <Bonificacion>(); if (id != bonificacion.Id) { response.OK = false; response.Error.title = "Id no coincide"; response.Error.error = "El id no coincide con el id del cuerpo"; return(response); } var temp = contexto.Bonificacion.Find(id); if (temp == null) { response.OK = false; response.Error.title = "No se encontro el registro"; response.Error.error = $"No se encontro la bonificacion con id= {id} para ser modificada"; return(response); } temp.Descripcion = bonificacion.Descripcion; temp.Monto = bonificacion.Monto; contexto.Entry(temp).State = EntityState.Modified; contexto.SaveChanges(); response.OK = true; response.Data = bonificacion; return(response); }
public GenericApiResponse <Prestacion> ModificarPrestacion(int id, [FromBody] Prestacion prestacion) { GenericApiResponse <Prestacion> response = new GenericApiResponse <Prestacion>(); if (id != prestacion.Id) { response.OK = false; response.Error.title = "Id no coincide"; response.Error.error = "El id no coincide con el id del cuerpo"; return(response); } var temp = contexto.Prestacion.FirstOrDefault(p => p.Id == id); if (temp == null) { response.OK = false; response.Error.title = "No se encontro el registro"; response.Error.error = "No se encontro la prestacion con id= {id} para ser modificada"; return(response); } temp.Nombre = prestacion.Nombre; temp.PorcentajeDeSueldo = prestacion.PorcentajeDeSueldo; contexto.Entry(temp).State = EntityState.Modified; contexto.SaveChanges(); response.OK = true; response.Data = temp; return(response); }
public GenericApiResponse <Puesto> ModificarPuesto(int id, [FromBody] Puesto puesto) { GenericApiResponse <Puesto> response = new GenericApiResponse <Puesto>(); if (id != puesto.Id) { response.OK = false; response.Error.title = "Id no coincide"; response.Error.error = "El id no coincide con el id del cuerpo"; return(response); } var temp = contexto.Puesto.FirstOrDefault(p => p.Id == id); if (temp == null) { response.OK = false; response.Error.title = "No se encontro el registro"; response.Error.error = $"No se encontro el puesto con id= {id} para ser modificado"; return(response); } temp.PuestoFuncional = puesto.PuestoFuncional; temp.PuestoNominal = puesto.PuestoNominal; temp.SueldoBase = puesto.SueldoBase; contexto.Entry(temp).State = EntityState.Modified; contexto.SaveChanges(); response.OK = true; response.Data = temp; return(response); }
public async Task <GenericApiResponse <object> > DeletePhonebookEntry(int id) { GenericApiResponse <object> gResponse = new GenericApiResponse <object>(); object returnObj = null; try { gResponse.Status = HttpStatusCode.OK; gResponse.Message = "Success"; var parameters = new DynamicParameters(); parameters.Add("@id", id, dbType: DbType.String); await PhonebookDbConnection.Connection.ExecuteAsync("sp_delete_phonebook_entry", parameters, commandType : CommandType.StoredProcedure); } catch (Exception ex) { gResponse.Status = HttpStatusCode.InternalServerError; gResponse.Message = "Failure"; logger.Information(ex.Message); } gResponse.Payload = returnObj; return(gResponse); }
public static ActionResult <GenericApiResponse <object> > HandleConflict(this ControllerBase controller, string title, string error) { var response = new GenericApiResponse <object>(); response.Error.title = title; response.Error.error = error; return(controller.Conflict(response)); }
private IActionResult HandleError(ActionContext arg) { var response = new GenericApiResponse <object>(); var first = arg.ModelState.First(m => m.Value.Errors.Count > 0); response.Error.title = first.Value.Errors.First().ErrorMessage; return(new BadRequestObjectResult(response)); }
public static IHttpActionResult GetResponse <T>(this ApiController @this, T response) { if (response != null) { return(new OkNegotiatedContentResult <GenericApiResponse <T> >(GenericApiResponse <T> .Success(response), @this)); } return(new OkNegotiatedContentResult <GenericApiResponse <T> >(GenericApiResponse <T> .Failure(), @this)); }
public HttpResponseMessage SendLackCreditReport(HttpRequestMessage request, [FromBody] StoreAttributes data) { PersonBL ConsumerAuth = new PersonBL(); GenericApiResponse response = new GenericApiResponse(); StoreBL storeBL = new StoreBL(); string error = ""; SimpleTextResponse ReportResponse = new SimpleTextResponse(); try { IEnumerable <string> key = null; request.Headers.TryGetValues("authenticationKey", out key); var consumerFb = ConsumerAuth.authenticateConsumer(key.FirstOrDefault().ToString()); if (consumerFb != null) { if (!string.IsNullOrEmpty(data.FirebaseID)) { int?ResultOfReport = storeBL.AirTimeReporting(data.StoreName, data.AddressStore, data.Longitude, data.Latitude, data.FirebaseID, consumerFb.ConsumerID, consumerFb.RegistrationDate, consumerFb.ModificationDate, ref error); if (ResultOfReport > 0) { ReportResponse.Message = "Operation completed succesfully"; ReportResponse.result = true; return(Request.CreateResponse <IResponse>(HttpStatusCode.OK, ReportResponse)); } else { ReportResponse.Message = "Something went wrong"; ReportResponse.result = false; return(Request.CreateResponse <IResponse>(HttpStatusCode.InternalServerError, ReportResponse)); } } else { ReportResponse.Message = "Bad Request"; ReportResponse.result = false; return(Request.CreateResponse <IResponse>(HttpStatusCode.BadRequest, ReportResponse)); } } else { response.HttpCode = 404; response.Message = "Facebook information not found"; return(Request.CreateResponse <IResponse>(HttpStatusCode.BadRequest, response)); } } catch (Exception ex) { response.HttpCode = 500; response.Message = "something went wrong"; return(Request.CreateResponse <IResponse>(HttpStatusCode.InternalServerError, response)); } }
public static GenericApiResponse<Feed> GetFeed(String appKey) { GenericApiResponse<Feed> apiResponse = new GenericApiResponse<Feed>(); if (HttpContext.Current.User.Identity.IsAuthenticated) { apiResponse.status = "ok"; apiResponse.data = new Feed() { Items = new String[3] { "item1", "item2", "item3" } }; } return apiResponse; }
public GenericApiResponse <Descuento> CrearDescuento([FromBody] Descuento descuento) { contexto.Descuento.Add(descuento); contexto.SaveChanges(); GenericApiResponse <Descuento> response = new GenericApiResponse <Descuento>(); response.OK = true; response.Data = descuento; return(response); }
public GenericApiResponse <Prestacion> CrearPrestacion([FromBody] Prestacion prestacion) { contexto.Prestacion.Add(prestacion); contexto.SaveChanges(); GenericApiResponse <Prestacion> response = new GenericApiResponse <Prestacion>(); response.OK = true; response.Data = prestacion; return(response); }
public GenericApiResponse <Bonificacion> CrearBonificacion([FromBody] Bonificacion bonificacion) { contexto.Bonificacion.Add(bonificacion); contexto.SaveChanges(); GenericApiResponse <Bonificacion> response = new GenericApiResponse <Bonificacion>(); response.OK = true; response.Data = bonificacion; return(response); }
public GenericApiResponse <Puesto> CrearPuesto([FromBody] Puesto puesto) { contexto.Puesto.Add(puesto); contexto.SaveChanges(); GenericApiResponse <Puesto> response = new GenericApiResponse <Puesto>(); response.OK = true; response.Data = puesto; return(response); }
public IActionResult AddPokemon([FromBody] PokemonForCreationDto pokemonForCreateDto) { var pokemon = _mapper.Map <Core.Entities.Pokemon>(pokemonForCreateDto); _pokemonRepository.AddPokemon(pokemon); var pokemonDto = _mapper.Map <PokemonDto>(pokemon); var genericApiResponse = new GenericApiResponse <Core.Entities.Pokemon> { Data = pokemon }; return(Created($"{ControllerRoute}/{nameof(GetPokemon)}", genericApiResponse)); }
public GenericApiResponse SaveRetail([FromBody] RetailTicket ticketInfo, [FromBody] RetailTicketItem[] ticketItems) { var response = new GenericApiResponse(); var ticket = _context.Tickets.FirstOrDefault(x => x.Id == ticketInfo.Id); if (ticket == null) { response.Success = false; response.Error = (int)ErrorCodes.RetailScreenNotFoundTicket; response.Message = ErrorMessages.RetailScreenNotFoundTicket; return(response); } ticket.Paid = ticketInfo.Paid; ticket.PaidAmount = ticketInfo.PaidAmount; ticket.ClosingDate = Convert.ToDateTime(ticketInfo.ClosingDate); ticket.CreationDate = Convert.ToDateTime(ticketInfo.CreationDate); ticket.DueAmount = ticketInfo.DueAmount; ticket.SubTotal = ticketInfo.SubTotal; ticket.Settled = ticketInfo.Settled; ticket.Status = ticketInfo.Status; ticket.TableId = ticketInfo.TableId; ticket.TotalDiscount = ticketInfo.TotalDiscount; ticket.TotalPrice = ticketInfo.TotalPrice; ticket.TotalTax = ticketInfo.TotalTax; ticket.Voided = ticketInfo.Voided; ticket.VoidByUser = ticketInfo.VoidedByUser; ticket.VoidReason = ticketInfo.VoidedReason; var currentTicketItems = _context.TicketItems.Where(x => x.TicketId == ticket.Id); foreach (var ticketItem in ticketItems) { var currentTicketItem = currentTicketItems.FirstOrDefault(x => x.Id == ticketItem.Id); if (currentTicketItem == null) { var item = new TicketItem(); SyncTicketItem(item, ticketItem); _context.TicketItems.Add(item); continue; } SyncTicketItem(currentTicketItem, ticketItem); } _context.SaveChanges(); response.Success = true; return(response); }
private void Challenge(HttpActionContext actionContext) { var host = actionContext.Request.RequestUri.DnsSafeHost; actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); actionContext.Response.Headers.Add("WWW-Authenticate", $"Basic realm=\"{host}\""); var result = GenericApiResponse <object> .Failure(); result.Message = ""; result.Payload = new { }; actionContext.Response.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json"); }
public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.Items["User"]; if (user == null) { var response = new GenericApiResponse <object>(); response.Error.title = "No tiene permisos"; response.Error.error = "Falta Token"; context.Result = new JsonResult(response) { StatusCode = StatusCodes.Status401Unauthorized }; } }
public IActionResult DeletePokemon(string name) { var genericApiResponse = new GenericApiResponse <string>(); var success = _pokemonRepository.TryDeletePokemon(name); genericApiResponse.Success = success; if (!success) { genericApiResponse.ErrorMessage = ApiErrors.DeletionFailure.GetDescription(); throw new ApiException(ApiErrors.DeletionFailure); } genericApiResponse.Data = $"{name} deleted."; return(Ok(genericApiResponse)); }
protected IEnumerable <PokemonDto> GetPokemonsBySortOrder(string propertyToSortOn, string sortOrder, string propertyToOrderBy) { //Arrange var pagingParams = new PagingParams() { Sort = sortOrder }; MockedPokemonRepository.Setup(x => x.GetPokemons(pagingParams)).Returns(PagedListPokemon); MockedPokemonService.Setup(x => x.GetFilteredSortQuery(It.IsAny <string>())).Returns($"{propertyToSortOn} {sortOrder}"); PokemonsController = new PokemonsController(MockedPokemonRepository.Object, AutoMapper, MockedPokemonService.Object); //Act GenericApiResponse <ObjectDto> objDto = PokemonsController.GetPokemons(pagingParams); return(objDto?.Data?.Pokemons); }
public static ActionResult <GenericApiResponse <List <T> > > HandleNotFound <T>(this ControllerBase controller, List <T> data, string title, string error) { var response = new GenericApiResponse <List <T> >(); if (data?.Count == 0) { response.Error.title = title; response.Error.error = error; return(controller.NotFound(response)); } else { response.OK = true; response.Data = data; return(response); } }
public void OnException(ExceptionContext context) { var error = new GenericApiResponse(); if (_env.IsDevelopment()) { error.Message = context.Exception.Message; } else { error.Message = "A simple error occured"; } error.Code = 301; context.Result = new ObjectResult(error) { StatusCode = 500 }; }
public GenericApiResponse <SueldoBruto_Descuento> Eliminar([FromBody] SueldoBruto_Descuento registro) { GenericApiResponse <SueldoBruto_Descuento> response = new GenericApiResponse <SueldoBruto_Descuento>(); var temp = contexto.SueldoBruto_Descuento.FirstOrDefault(s => s.Id_Empleado == registro.Id_Empleado && s.Id_Descuento == registro.Id_Descuento); if (temp == null) { response.OK = false; response.Error.title = "Registro no encontrado"; response.Error.error = $"No se encontro ningun registro {registro.Id_Descuento} | {registro.Id_Empleado}"; return(response); } contexto.SueldoBruto_Descuento.Remove(temp); contexto.SaveChanges(); response.OK = true; response.Data = registro; return(response); }
public GenericApiResponse <PokemonDto> GetPokemon(string name) { var pokemon = _pokemonRepository.GetByName(name); var pokemonDto = new PokemonDto(); _mapper.Map(pokemon, pokemonDto); var genericApiResponse = new GenericApiResponse <PokemonDto> { Data = pokemonDto }; if (pokemon != null) { return(genericApiResponse); } genericApiResponse.Success = false; genericApiResponse.ErrorMessage = ApiErrors.NotFound.GetDescription(); throw new ApiException(ApiErrors.NotFound); }
public GenericApiResponse <Empleado_Bonificacion> Eliminar([FromBody] Empleado_Bonificacion registro) { GenericApiResponse <Empleado_Bonificacion> response = new GenericApiResponse <Empleado_Bonificacion>(); var temp = contexto.Empleado_Bonificacion.FirstOrDefault(s => s.Id_Empleado == registro.Id_Empleado && s.Id_Bonificacion == registro.Id_Bonificacion); if (temp == null) { response.OK = false; response.Error.title = "Registro no encontrado"; response.Error.error = $"No se encontro ningun registro {registro.Id_Bonificacion} | {registro.Id_Empleado}"; return(response); } contexto.Empleado_Bonificacion.Remove(temp); contexto.SaveChanges(); response.OK = true; response.Data = registro; return(response); }
public HttpResponseMessage EncryptedSignin([FromBody] SigninReqBody signinRequest) { GenericApiResponse response = new GenericApiResponse(); if (String.IsNullOrEmpty(signinRequest.email) || String.IsNullOrEmpty(signinRequest.password)) { response.HttpCode = 400; response.Message = "Email or password cannot be empty"; return(Request.CreateResponse <IResponse>(HttpStatusCode.BadRequest, response)); } //else if (String.IsNullOrEmpty(signinRequest.buildVersion)) //{ // response.HttpCode = 400; // response.Message = "Build version must be provided"; // return Request.CreateResponse<IResponse>(HttpStatusCode.BadRequest, response); //} else { var person = personBL.AuthenticatePerson(signinRequest.email, signinRequest.password, signinRequest.deviceInfo, signinRequest.deviceIP, signinRequest.deviceID, true); if (person != null) { if (!person.ProfileCompleted) { response.HttpCode = 403; response.Message = "Make sure your profile is complete."; return(Request.CreateResponse <IResponse>(HttpStatusCode.Forbidden, response)); } else { //Crear respuesta exitosa SigninInteractor interactor = new SigninInteractor(); var responseSuccess = interactor.createSuccessResponse(person); return(Request.CreateResponse <IResponse>(HttpStatusCode.OK, responseSuccess)); } } else { response.HttpCode = 401; response.Message = "Invalid credentials"; return(Request.CreateResponse <IResponse>(HttpStatusCode.Unauthorized, response)); } } }
public async Task <GenericApiResponse <T> > PostResponse <T>(string uriRequest) { var response = new GenericApiResponse <T>(); //cancellationToken.ThrowIfCancellationRequested(); _connection.CheckConnectivity(); try { HttpResponseMessage httpResponse = await _client.PostAsync(uriRequest, null); response.IsSuccess = httpResponse.IsSuccessStatusCode; response.Message = httpResponse.ReasonPhrase; response.StatusCode = (int)httpResponse.StatusCode; if (response.IsSuccess) { //cancellationToken.ThrowIfCancellationRequested(); string result = await httpResponse.Content.ReadAsStringAsync(); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.NullValueHandling = NullValueHandling.Ignore; response.Result = JsonConvert.DeserializeObject <T>(result, settings); } } catch (OperationCanceledException ex) { throw ex; } catch (Exception ex) { response.IsSuccess = false; response.StatusCode = -1; response.Message = GetExceptionMessage(ex); } //cancellationToken.ThrowIfCancellationRequested(); return(response); }