private static async Task <Product> TrackPriceAndSaveProductAsync(WebProduct webProduct) { using (var dbContext = new DiscountMonitorContext()) { var product = dbContext.Products .Include(i => i.HistoryPrices) .SingleOrDefault(i => i.Url.Equals(webProduct.Url)); product ??= new Product( webProduct.Name, webProduct.Price, webProduct.Description, webProduct.Url ); product.VerifyAndTrackPrice(webProduct.Price); if (product.PriceWasChanged) { Console.WriteLine("O preço do produto foi alterado."); } dbContext.Products.Update(product); await dbContext.SaveChangesAsync(); return(product); } }
private static async Task <WebProduct> GetProductFromWebAsync(string url) { Console.WriteLine($"Obtendo dados do produto da página { url }."); using (var httpClient = new HttpClient()) { var htmlContent = await httpClient.GetStringAsync(url); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(htmlContent); var productName = htmlDocument.DocumentNode.SelectSingleNode("//h1"); var productPrice = htmlDocument.DocumentNode.SelectSingleNode("//span[@class=\"price-template__text\"]"); var ignoredTags = new[] { "h2", "table" }; var productDescription = htmlDocument.DocumentNode .SelectSingleNode("//div[@class=\"description__container-text\"]") .ChildNodes .Where(i => !ignoredTags.Contains(i.OriginalName) && !string.IsNullOrWhiteSpace(i.InnerText)) .FirstOrDefault(); var product = new WebProduct { Name = productName.InnerText, Price = Convert.ToDouble(productPrice.InnerText), Description = productDescription.InnerText, Url = url }; return(product); } }