public async Task <IActionResult> Edit(int id, [Bind("JokeId,JokeQuestion,JokeAnswer")] JokeModel jokeModel) { if (id != jokeModel.JokeId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(jokeModel); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!JokeModelExists(jokeModel.JokeId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(jokeModel)); }
public async Task SaveJokeToDatabase(JokeModel jokeModel) { if (await _jokeRepository.GetById(jokeModel.Id.ToString()) == null) { await _jokeRepository.AddAsync(Mapper.ToEntity(jokeModel)); } }
public Task InsertJoke(JokeModel joke) { string sql = @"insert into joke (date, setup, punchline, source, author) values (@Date, @Setup, @Punchline, @Source, @Author);"; return(_db.SaveData(sql, joke)); }
public static Joke ToEntity(JokeModel model) { var entity = new Joke { Id = model.Id, joke = model.Joke }; return(entity); }
public static JokeModel ToModel(Joke entity) { var model = new JokeModel { Id = entity.Id, Joke = entity.joke }; return(model); }
public ActionResult Rating(JokeModel jokeprop) { string dadurl = "https://icanhazdadjoke.com/"; string chuckurl = "https://api.chucknorris.io/jokes/random"; jokeprop.Ijokelist = Joke(chuckurl, "value"); jokeprop.Ijokelist = Joke(dadurl, "joke"); ViewBag.List = jokeprop.Ijokelist; return(View(jokeprop)); }
public async Task <IActionResult> Create([Bind("JokeId,JokeQuestion,JokeAnswer")] JokeModel jokeModel) { if (ModelState.IsValid) { _context.Add(jokeModel); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(jokeModel)); }
/// <summary> /// Returns a random joke as a json object. /// </summary> /// <returns></returns> public async Task <IActionResult> GetRandomJoke() { JokeApplicationServices jokeApi = new JokeApplicationServices(); JokeModel joke = await jokeApi.GetRandomJoke(); if (joke != null) { return(Json(joke)); } return(StatusCode(500)); }
public IHttpActionResult Post([FromBody] JokeModel uploadedJoke, [FromUri] string secret) { try { var idString = ""; if (secret.Length < 6) { return(Content <string>(System.Net.HttpStatusCode.Unauthorized, "The secret is incorrect!")); } for (var i = 6; i < secret.Length; i++) { idString += secret[i]; } int SecretID = Int32.Parse(idString); var user = DbContext.Users .Where(x => x.Id == SecretID).FirstOrDefault(); if (user == null) { return(Content <string>(System.Net.HttpStatusCode.Unauthorized, "You don't have access here!")); } var exists = user != null && user.Jokes != null && user.Jokes.Where(x => x.Description == uploadedJoke?.Text).FirstOrDefault() != null; if (exists) { return(Content <string>(System.Net.HttpStatusCode.NotAcceptable, "The joke already exists in your list")); } var joke = new Joke() { Name = user.Username + " - joke no. " + (user.Jokes.Count + 1), Description = uploadedJoke.Text, NoLikes = 0, NoUnlikes = 0, Ratings = new List <Rating>(), UserID = user.Id }; //user.Jokes.Add(joke); //Statics.GetAllJokes().Add(joke); DbContext.Jokes.Add(joke); DbContext.SaveChanges(); } catch (Exception) { return(Content <string>(System.Net.HttpStatusCode.ServiceUnavailable, "An error has ocurred"));; } return(Content <string>(System.Net.HttpStatusCode.Created, "Joke has been created"));; }
public async Task <IActionResult> ClientGetJokeByThemeAsync(string theme) { try { JokeModel jokes = await _jokeClient.ApiGetJokeByTheme(theme); return(Ok(jokes)); } catch (ApiException exMessage) { _logger.LogError(exMessage.Message); return(NotFound(exMessage)); } }
public void RandomJoke_ReturnsJokeModel_WhenJokeIsNotNull() { var randomJoke = new JokeModel { Joke = "this is not a joke" }; var factory = new Mock <IBusinessFactory>(); factory.Setup(src => src.GetBusinessClass <IJokeBusiness>().GetRandomJoke()).Returns(randomJoke); var controller = new JokesController(factory.Object); var returns = controller.RandomJoke() as OkNegotiatedContentResult <JokeModel>; Assert.AreEqual(returns.Content, randomJoke); }
public void GetRandomJoke_ReturnsJokeModel_Type() { //Arrange var mockJokeRepository = new Mock <IJokeRepository>(); mockJokeRepository.Setup(x => x.GetRandomJoke()).Returns(new JokeModel()); var mockRepositoryFactory = new Mock <IRepositoryFactory>(); mockRepositoryFactory.Setup(x => x.GetDataRepository <IJokeRepository>()).Returns(mockJokeRepository.Object); var business = new JokeBusiness(mockRepositoryFactory.Object, new Shared.Utilities.JokesHelper()); //Act JokeModel result = business.GetRandomJoke(); //Assert Assert.IsInstanceOfType(result, typeof(JokeModel)); }
/// <summary> /// Gets a random joke from the joke api. /// </summary> /// <returns></returns> public async Task <JokeModel> GetRandomJoke() { try { _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Task <Stream> stringTask = _client.GetStreamAsync(_baseAddress); JokeModel joke = await JsonSerializer.DeserializeAsync <JokeModel>(await stringTask); return(joke); } catch { return(null); } }
public List <JokeModel> Joke(string url, string value) { JokeModel hej = new JokeModel(); string response; using (WebClient client = new WebClient()) { client.Headers.Add("accept", "application/json"); response = client.DownloadString(url); } var jObject = JObject.Parse(response); hej.joke = (string)jObject[value]; hej.rating = 0; newjokes.Add(hej); return(newjokes); }
public HttpResponseMessage PostJoke([FromBody] JokeModel model) { var response = this.PerformOperationAndHandleExceptions(() => { Joke newJoke = new Joke() { PostedBy = model.PostedBy, PostDate = DateTime.Now, Content = model.Content }; this.context.Jokes.Add(newJoke); this.context.SaveChanges(); return(this.Request.CreateResponse(HttpStatusCode.Created)); }); return(response); }
public JokeModel GetJoke(int jokeid) { var jokeBD = DbContext.Jokes.Where(x => x.JokeID == jokeid).FirstOrDefault(); if (jokeBD != null) { var j = new JokeModel() { Text = jokeBD.Description, Title = jokeBD.Name, UserID = (int)jokeBD.UserID, NoLikes = jokeBD.NoLikes ?? 0, NoUnlikes = jokeBD.NoUnlikes ?? 0, JokeID = jokeBD.JokeID }; return(j); } return(new JokeModel()); }
public static async Task <JokeModel> LoadJoke() { string url = "http://api.icndb.com/jokes/random?limitTo=[nerdy]"; using (HttpResponseMessage response = await Initialization.ApiClient.GetAsync(url)) { if (response.IsSuccessStatusCode) { JokeModel joke = await response.Content.ReadAsAsync <JokeModel>(); return(joke); } else { throw new Exception(response.ReasonPhrase); } } }
public IEnumerable <JokeModel> Get([FromUri] int userid) { var jokesBD = DbContext.Jokes.Where(x => x.UserID == userid).OrderBy(x => x.JokeID).ToList(); var jokes = new List <JokeModel>(); foreach (var jokeBD in jokesBD) { var j = new JokeModel() { Text = jokeBD.Description, Title = jokeBD.Name, UserID = (int)jokeBD.UserID, NoLikes = jokeBD.NoLikes ?? 0, NoUnlikes = jokeBD.NoUnlikes ?? 0, JokeID = jokeBD.JokeID }; jokes.Add(j); } return(jokes); }
public void JokesByTerm_ReturnsJokeModels_WhenItHasJokes() { var jokeModel = new JokeModel { Joke = "this is not a joke" }; var jokeList = new List <JokeModel> { jokeModel }; var jokeModels = new JokesModels { Results = jokeList }; var factory = new Mock <IBusinessFactory>(); factory.Setup(src => src.GetBusinessClass <IJokeBusiness>().GetJokesByTerm(It.IsAny <string>())).Returns(jokeModels); var controller = new JokesController(factory.Object); var returns = controller.JokesByTerm("this") as OkNegotiatedContentResult <JokesModels>; Assert.AreEqual(returns.Content, jokeModels); }
public async Task <JokeModel> GetRandomJoke() { JokeModel joke = new JokeModel(); using (HttpClient client = new HttpClient()) { try { client.DefaultRequestHeaders.Add("Accept", "application/json"); var response = await client.GetAsync(this._url); string jsonString = await response.Content.ReadAsStringAsync(); joke = JsonConvert.DeserializeObject <JokeModel>(jsonString); } catch (Exception e) { // log exceptions } } return(joke); }
public async Task Post([FromBody] JokeModel joke) { await _db.InsertJoke(joke); }
public async Task <JsonResult> AddJoke([FromBody] JokeModel newJoke) { //give our new joke a guid newJoke.ID = Guid.NewGuid(); return(await base.AddNewWithMapping <JokeModel>(newJoke)); }
public async Task <IEnumerable <int> > GatherData(int fromId, int toId) { var jokes = new List <JokeModel>(); var users = new List <Users>(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var parser = new HtmlParser(); var webClient = new WebClient { Encoding = Encoding.GetEncoding("windows-1251") }; for (var i = fromId; i <= toId; i++) { var url = $"https://users.pomagalo.com/204,1,0,0,0,0,0,0,0,0,?page=3"; string html = null; for (var j = 0; j < 10; j++) { try { html = webClient.DownloadString(url); break; } catch (Exception) { Thread.Sleep(1000); } } if (string.IsNullOrWhiteSpace(html)) { continue; } var document = parser.ParseDocument(html); var jokeContent = document.QuerySelector(".my_buddies_list"); var getElements = jokeContent.QuerySelectorAll("tr"); foreach (var element in getElements) { var contentElement = element.GetElementsByClassName("text"); foreach (var item in contentElement) { if (string.IsNullOrWhiteSpace(item.QuerySelector("span").InnerHtml)) { break; } var test = item.QuerySelector("span").InnerHtml; var userName = new Users { User = test }; users.Add(userName); var userAcc = new UserAcc { Name = test, }; await this.repository.AddAsync(userAcc); await this.repository.SaveChangesAsync(); Console.WriteLine($"{test}"); } // var userName= new Users { User = contentElement }; // users.Add(userName); } var categoryName = jokeContent.QuerySelector("tr")?.TextContent?.Trim(); if (!string.IsNullOrWhiteSpace(jokeContent.TextContent) && !string.IsNullOrWhiteSpace(categoryName)) { var jokeModel = new JokeModel { Category = categoryName, Content = jokeContent.TextContent }; jokes.Add(jokeModel); } } return(null); }
public async Task <JsonResult> UpdateJoke([FromBody] JokeModel updatedJoke) { return(await base.SaveWithMapping <JokeModel>(updatedJoke)); }