Skip to content

Instantly share code, notes, and snippets.

@icebeam7
Created November 15, 2018 13:39
Show Gist options
  • Select an option

  • Save icebeam7/50f7657e5a7ceff613ced6fa915ef3b0 to your computer and use it in GitHub Desktop.

Select an option

Save icebeam7/50f7657e5a7ceff613ced6fa915ef3b0 to your computer and use it in GitHub Desktop.
HTTP Azure Function Code which selects N random comments on a Facebook post
#r "Newtonsoft.Json"
using System.Net;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public class FacebookPost
{
public string Id { get; set; }
public string Message { get; set; }
public string PermaLink_Url { get; set; }
}
public class Comments
{
public List<FacebookPost> Data { get; set; }
}
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
var url = "this is a hard-coded URL. Get yours from Facebook Graph API :) access-token is needed";
var winnersCount = 0;
var random = new Random();
List<FacebookPost> posts = null;
var winnersList = new List<FacebookPost>();
if (int.TryParse(req.Query["winners"], out winnersCount))
{
using (var client = new HttpClient())
{
var task = await client.GetAsync(url);
var json = await task.Content.ReadAsStringAsync();
var comments = JsonConvert.DeserializeObject<Comments>(json);
posts = comments.Data;
}
if (posts != null)
{
var postsCount = posts.Count;
for (int i = 0; i < winnersCount; i++)
{
var winner = posts[random.Next(0, postsCount)];
var search = winnersList.FirstOrDefault(x => x.Id == winner.Id);
if (object.Equals(search, default (FacebookPost)))
{
log.LogInformation($"{winner.Id} won");
winnersList.Add(winner);
}
else
{
log.LogInformation($"{winner.Id} has already won");
i--;
}
}
}
}
return (ActionResult)new OkObjectResult(winnersList);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment