public IActionResult GetBeerRatings(string BeerName) { Beer selectedBeer = GetBeer(BeerName); if (!(selectedBeer == null)) { IEnumerable <Ratings> ratings = GetSpecificRatings(Convert.ToInt32(selectedBeer.Id)); BeerRating beerRating = new BeerRating() { Id = selectedBeer.Id, Name = selectedBeer.Name, Description = selectedBeer.Name, UserRatings = ratings }; var jsonBeerRating = JsonConvert.SerializeObject(beerRating); return(Ok(JValue.Parse(jsonBeerRating).ToString(Formatting.Indented))); } else { return(StatusCode(StatusCodes.Status400BadRequest, "Invalid Beer Name")); } }
public async Task Can_List_Beers() { var name = "Beer"; var result = await BeerRating.ListBeerByName(name); Assert.IsTrue(result.Any(p => p.Name.Contains(name))); }
public HttpResponseMessage AddRatingToBeer(BeerRating beerRating) { try { JArray beers = null; HttpResponseMessage httpResponseMessage; if (!string.IsNullOrWhiteSpace(_data)) { beers = JArray.Parse(_data); if (beers.All(x => x.SelectToken("id").ToString() != beerRating.BeerId.ToString())) { httpResponseMessage = new HttpResponseMessage() { Content = new ObjectContent <object>(new { message = "Please enter valid id with this no beer exists.", error = "1" }, new JsonMediaTypeFormatter()), ReasonPhrase = "Invalid request", StatusCode = HttpStatusCode.BadRequest }; return(httpResponseMessage); } } if (beerRating != null && (beerRating.Rating == 0 || beerRating.Rating > 5)) { httpResponseMessage = new HttpResponseMessage() { Content = new ObjectContent <object>(new { message = "Please enter rating range between 1 to 5 only.", error = "1" }, new JsonMediaTypeFormatter()), ReasonPhrase = "Invalid request", StatusCode = HttpStatusCode.BadRequest }; return(httpResponseMessage); } var jObject = (JObject)beers.FirstOrDefault(x => beerRating != null && x.SelectToken("id").ToString() == beerRating.BeerId.ToString()); string json = JsonConvert.SerializeObject(beerRating, Formatting.Indented); var dataFile = Path.Combine("E:\\Test Projects\\TestPunkApi\\", "Database.json"); //Reading the file var jsonData = System.IO.File.ReadAllText(dataFile); var db = JsonConvert.DeserializeObject <DbJson>(jsonData); db.userRatings.Add(beerRating); jsonData = JsonConvert.SerializeObject(db); System.IO.File.WriteAllText(dataFile, jsonData); httpResponseMessage = new HttpResponseMessage { Content = new ObjectContent <object>(new { message = "success", error = "0" }, new JsonMediaTypeFormatter()), StatusCode = HttpStatusCode.OK }; return(httpResponseMessage); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Failure")); } }
//Before Execution /// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting(HttpActionContext actionContext) { //Extracts Rating from the parameter BeerRating rating = (BeerRating)actionContext.ActionArguments["rating"]; if (!CheckEmailRegex(rating.Username)) { actionContext.Response = actionContext.Request.CreateResponse( HttpStatusCode.BadRequest, new { error = "Username should be an Email/Username supplied is not valid." }, actionContext.ControllerContext.Configuration.Formatters.JsonFormatter ); } }
public HttpResponseMessage Post(int id, [FromBody] BeerRating rating) { HttpResponseMessage message = null; List <string> errors = new List <string>(); PunkApi punkObj = new PunkApi(); if (!punkObj.CheckIdExists(id)) { errors.Add("ID does not exist"); } if (rating.Rating < 1 || rating.Rating > 5) { errors.Add("Not a valid rating. Should be between 1 and 5"); } if (errors.Count > 0) { Dictionary <string, string[]> messageDictionary = new Dictionary <string, string[]>(); messageDictionary.Add("errors", errors.ToArray()); message = Request.CreateResponse(HttpStatusCode.BadRequest, messageDictionary); } else { Dictionary <string, string> messageDictionary = new Dictionary <string, string>(); //Appending JSON to file (database.json) try { rating.Id = id; //Attaching id to rating object WriteToJsonFile(rating); messageDictionary.Add("message", "Rating Successfully Added"); message = Request.CreateResponse(HttpStatusCode.OK, messageDictionary); } catch (IOException ex) { messageDictionary.Add("error", "Could not write to JSON file. \n Error: " + ex.Message); message = Request.CreateResponse(HttpStatusCode.InternalServerError, messageDictionary); } } return(message); }
//Helper Methods /// <summary> /// Writes to json file. /// </summary> /// <param name="rating">The rating.</param> /// <returns>Boolean (Whether or not succeeded</returns> public bool WriteToJsonFile(BeerRating rating) { //File Path var jsonFilePath = System.Web.HttpContext.Current.Server.MapPath(@"~/database.json"); //Reading the file var jsonData = File.ReadAllText(jsonFilePath); //List of Ratings to store current values or an empty list if none exists List <BeerRating> currentRatingsStored = new List <BeerRating>(); currentRatingsStored = JsonConvert.DeserializeObject <List <BeerRating> >(jsonData) ?? new List <BeerRating>(); //Adding newest Rating to the List currentRatingsStored.Add(rating); //Updating the file jsonData = JsonConvert.SerializeObject(currentRatingsStored); File.WriteAllText(jsonFilePath, jsonData); return(false); }
public async Task <bool> RateBeerAsync(string userId, int beerId, int rating) { var beer = this.db .BeerRatings .Find(beerId, userId); if (beer != null) { return(false); } var beerRating = new BeerRating { BeerId = beerId, UserId = userId, Rate = rating }; await this.db.AddAsync(beerRating); await this.db.SaveChangesAsync(); return(true); }