Alan can motivate you with a brilliant quote
private async Task GetInspiringQuote()
{
try
{
QuoteObject inspiring_quote = await QuoteAPIManager.GetQuote();
await GUIOutput(inspiring_quote.contents.quotes[0].quote, true);
}
catch
{
await GUIOutput("I'm sorry, I couldn't retrieve the informations from the web.", true);
}
state = AssistantState.BACKGROUND_DEFAULT;
}
public class QuoteAPIManager
{
public async static Task<QuoteObject> GetQuote()
{
var http = new HttpClient();
var response = await http.GetAsync("https://quotes.rest/qod.json");
string response_str = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(QuoteObject)); // JSON object to C# class transformer
var stream = new MemoryStream(Encoding.UTF8.GetBytes(response_str));
return (QuoteObject)serializer.ReadObject(stream);
}
}
This functionality, as we can see above, is implemented using two different functions:
GetInspiringQuote
is in charge of handling errors (for example when the connection with the web API is lost) and outputting the quote (using, as always, the functionGUIOutput
).GetQuote
(method of the classQuoteAPIManager
) is the one that actually retrieves the quote's content from the web: firstly it creates an http client and then establishes a connection to the web API to obtain the needed content; after that, the function creates an object (serializer
) that handles the conversion of the JSON data obtained by the API to the standard C# class. Once such a conversion is completed, the class containing all the data related to the quote is returned.