| 13 | namespace CSharp |
| 14 | { |
| 15 | public static class Function |
| 16 | { |
| 17 | private static HttpClient httpClient = new HttpClient(); |
| 18 | private static string Etag = string.Empty; |
| 19 | private static string StarCount = "0"; |
| 20 | |
| 21 | [FunctionName("index")] |
| 22 | public static IActionResult GetHomePage([HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest req, ExecutionContext context) |
| 23 | { |
| 24 | var path = Path.Combine(context.FunctionAppDirectory, "content", "index.html"); |
| 25 | return new ContentResult |
| 26 | { |
| 27 | Content = File.ReadAllText(path), |
| 28 | ContentType = "text/html", |
| 29 | }; |
| 30 | } |
| 31 | |
| 32 | [FunctionName("negotiate")] |
| 33 | public static SignalRConnectionInfo Negotiate( |
| 34 | [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req, |
| 35 | [SignalRConnectionInfo(HubName = "serverless")] SignalRConnectionInfo connectionInfo) |
| 36 | { |
| 37 | return connectionInfo; |
| 38 | } |
| 39 | |
| 40 | [FunctionName("broadcast")] |
| 41 | public static async Task Broadcast([TimerTrigger("*/5 * * * * *")] TimerInfo myTimer, |
| 42 | [SignalR(HubName = "serverless")] IAsyncCollector<SignalRMessage> signalRMessages) |
| 43 | { |
| 44 | var request = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/repos/azure/azure-signalr"); |
| 45 | request.Headers.UserAgent.ParseAdd("Serverless"); |
| 46 | request.Headers.Add("If-None-Match", Etag); |
| 47 | var response = await httpClient.SendAsync(request); |
| 48 | if (response.Headers.Contains("Etag")) |
| 49 | { |
| 50 | Etag = response.Headers.GetValues("Etag").First(); |
| 51 | } |
| 52 | if (response.StatusCode == System.Net.HttpStatusCode.OK) |
| 53 | { |
| 54 | var result = JsonConvert.DeserializeObject<GitResult>(await response.Content.ReadAsStringAsync()); |
| 55 | StarCount = result.StarCount; |
| 56 | } |
| 57 | |
| 58 | await signalRMessages.AddAsync( |
| 59 | new SignalRMessage |
| 60 | { |
| 61 | Target = "newMessage", |
| 62 | Arguments = new[] { $"Current star count of https://github.com/Azure/azure-signalr is: {StarCount}" } |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | private class GitResult |
| 67 | { |
| 68 | [JsonRequired] |
| 69 | [JsonProperty("stargazers_count")] |
| 70 | public string StarCount { get; set; } |
| 71 | } |
| 72 | } |