using HtmlAgilityPack;
namespace RobertMart
{
public class CommodityTracker
{
public static readonly Dictionary Commodities = new Dictionary()
{
{"Eggs", 6.00m},
{"Gas", 3.000m},
};
private const string EggsSourceUri = "https://tradingeconomics.com";
private const string GasSourceUri = "https://gasprices.aaa.com/";
public static async void FetchCommodities()
{
try
{
var client = new HttpClient();
var httpRequest = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{EggsSourceUri}/commodity/eggs-us"),
Headers =
{
{"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"},
{ "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0" },
}
};
var html = await client.SendAsync(httpRequest).Result.Content.ReadAsStringAsync();
var doc = new HtmlDocument();
doc.LoadHtml(html);
var tableNode = doc.DocumentNode.SelectSingleNode("//table[@class='table']");
var tr = tableNode.SelectSingleNode("./tr");
var priceNode = tr.SelectSingleNode("./td[2]");
var price = decimal.Parse(priceNode.InnerText.Trim());
Commodities["Eggs"] = price;
var gasHttpRequest = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(GasSourceUri),
Headers =
{
{ "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" },
{
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0"
},
},
};
var gasClient = new HttpClient();
var gasHtml = await gasClient.SendAsync(gasHttpRequest).Result.Content.ReadAsStringAsync();
var gasDoc = new HtmlDocument();
gasDoc.LoadHtml(gasHtml);
var gasPriceNode = gasDoc.DocumentNode.SelectSingleNode("//p[@class='numb']");
var stringGasPrice = gasPriceNode.SelectSingleNode("text()").InnerText.Trim();
var gasPrice = decimal.Parse(stringGasPrice.Replace("$", ""));
Commodities["Gas"] = gasPrice;
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}