public static async Task EnsureProjectIsSubscribedToEvents([QueueTrigger("projects-events-check")] ProjectEntity queuedProject, [Table("Projects")] CloudTable projects) { var project = projects .CreateQuery <ProjectEntity>() .Where(p => p.PartitionKey == queuedProject.PartitionKey && p.RowKey == queuedProject.RowKey) .ToList() .FirstOrDefault(); if (!project.SubscribedToEvents && !string.IsNullOrWhiteSpace(project.AccessToken)) { project.SubscribedToEvents = await SubscribeToProjectEventsAsync(project); await projects.ExecuteAsync(TableOperation.InsertOrMerge(project)); } }
private static async Task <bool> SubscribeToProjectEventsAsync(ProjectEntity projectEntity) { using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", projectEntity.AccessToken); var url = projectEntity.GetCreateSubscriptionUri(); var createBody = projectEntity.GetCreatePullRequestCreatedSubscriptionBody(); var createPRSuccessful = false; if (await IsEventSubscribedToProjectAsync(createBody, projectEntity)) { createPRSuccessful = true; } else { var createEventResponse = await httpClient.PostAsJsonAsync( url.ToString(), createBody); createPRSuccessful = createEventResponse.IsSuccessStatusCode; } var updateBody = projectEntity.GetCreatePullRequestUpdatedSubscriptionBody(); var updatePRSuccessful = false; if (await IsEventSubscribedToProjectAsync(updateBody, projectEntity)) { updatePRSuccessful = true; } else { var updateEventResponse = await httpClient.PostAsJsonAsync( url.ToString(), updateBody); updatePRSuccessful = updateEventResponse.IsSuccessStatusCode; } return(createPRSuccessful && updatePRSuccessful); } }
private static async Task <bool> IsEventSubscribedToProjectAsync(CreateSubscription subscription, ProjectEntity projectEntity) { using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", projectEntity.AccessToken); var url = $"https://{projectEntity.PartitionKey}/_apis/hooks/subscriptionsquery?api-version=4.1-preview"; var query = new CreateSubscriptionQuery(subscription); var resp = await httpClient.PostAsJsonAsync(url, query); if (!resp.IsSuccessStatusCode) { return(false); } var subscriptionResultJson = await resp.Content.ReadAsStringAsync(); var subscriptionResult = JsonConvert.DeserializeObject <dynamic>(subscriptionResultJson); return((subscriptionResult?.results.Count ?? 0) > 0); } }
public static Uri GetCreateSubscriptionUri(this ProjectEntity project) { return(new Uri($"https://{project.PartitionKey}" + "/DefaultCollection/_apis/hooks/subscriptions?api-version=1.0")); }