-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
319 lines (261 loc) · 11.7 KB
/
Program.cs
File metadata and controls
319 lines (261 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.Identity.Client;
class Program
{
private const string ClientId = "<YOUR_CLIENT_ID>"; // Insert your Azure AD application client ID
private const string ClientSecret = "<YOUR_CLIENT_SECRET>"; // Insert your Azure AD application client secret
private const string TenantId = "<YOUR_TENANT_ID>"; // Insert your Azure AD tenant ID
private const string AzureDevOpsUri = "<YOUR_AZURE_DEVOPS_URI>"; // Insert the URI of your Azure DevOps instance (e.g., "https://dev.azure.com/yourorganization")
private const string PatToken = "<YOUR_PAT_TOKEN>"; // Insert your Azure DevOps personal access token
private const string TeamId = "<YOUR_AZURE_DEVOPS_TEAM_ID>"; // Insert your Azure DevOps team ID
private const string IterationId = "<YOUR_AZURE_DEVOPS_ITERATION_ID>"; // Insert the ID of the Azure DevOps iteration
private const string GraphApiUrl = "https://graph.microsoft.com/v1.0";
private const string TokenEndpoint = "https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
private const string TeamsGroupId = "<YOUR_TEAMS_GROUP_ID>"; // Insert the ID of the Microsoft Teams group
private const string ChannelId = "<YOUR_TEAMS_CHANNEL_ID>"; // Insert the ID of the Microsoft Teams channel
static async Task Main(string[] args)
{
// Authenticate and get access token for Microsoft Graph API
var graphAccessToken = await GetAccessToken();
// Get start and end dates of the sprint
DateTime sprintStartDate = await GetSprintStartDate();
DateTime sprintEndDate = await GetSprintEndDate();
// Retrieve appointments from the specified Microsoft Teams channel calendar within the sprint range
var appointments = await GetAppointments(graphAccessToken, sprintStartDate, sprintEndDate);
// Create absences for each team member based on their appointments
var absences = CreateAbsences(appointments);
// Copy capacity from the previous sprint
var previousCapacity = await GetSprintCapacity(TeamId, await GetPreviousSprintId());
// Update the capacity with the absences
var updatedCapacity = UpdateCapacityWithAbsences(previousCapacity, absences);
// Post updated capacity to Azure DevOps sprint capacity for each team member
await PostCapacityToSprint(updatedCapacity);
Console.WriteLine("Capacity posted to Azure DevOps sprint successfully.");
}
static async Task<string> GetAccessToken()
{
var clientApp = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{TenantId}/v2.0"))
.Build();
var authResult = await clientApp.AcquireTokenForClient(new string[] { $"{GraphApiUrl}/.default" })
.ExecuteAsync();
return authResult.AccessToken;
}
static async Task<DateTime> GetSprintStartDate()
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PatToken);
var requestUrl = $"{AzureDevOpsUri}/{TeamId}/_apis/work/teamsettings/iterations/{IterationId}?api-version=6.0";
var response = await httpClient.GetAsync(requestUrl);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var iteration = JsonSerializer.Deserialize<AzureDevOpsIteration>(responseContent, options);
return iteration.Attributes.StartDate;
}
else
{
throw new Exception($"Failed to retrieve sprint start date from Azure DevOps. Error: {responseContent}");
}
}
static async Task<DateTime> GetSprintEndDate()
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PatToken);
var requestUrl = $"{AzureDevOpsUri}/{TeamId}/_apis/work/teamsettings/iterations/{IterationId}?api-version=6.0";
var response = await httpClient.GetAsync(requestUrl);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var iteration = JsonSerializer.Deserialize<AzureDevOpsIteration>(responseContent, options);
return iteration.Attributes.FinishDate;
}
else
{
throw new Exception($"Failed to retrieve sprint end date from Azure DevOps. Error: {responseContent}");
}
}
static async Task<List<Appointment>> GetAppointments(string accessToken, DateTime startDate, DateTime endDate)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
string startDateTime = startDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
string endDateTime = endDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
string requestUrl = $"{GraphApiUrl}/groups/{TeamsGroupId}/channels/{ChannelId}/calendarView?startDateTime={startDateTime}&endDateTime={endDateTime}";
var response = await httpClient.GetAsync(requestUrl);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var events = JsonSerializer.Deserialize<GraphCalendarEventsResponse>(responseContent, options);
return events.Value;
}
else
{
throw new Exception($"Failed to retrieve appointments from Microsoft Teams channel calendar. Error: {responseContent}");
}
}
static List<Absence> CreateAbsences(List<Appointment> appointments)
{
var absences = new List<Absence>();
foreach (var appointment in appointments)
{
var absence = new Absence
{
TeamId = TeamId,
IterationId = IterationId,
TeamMemberEmail = appointment.Organizer.Email,
StartDate = appointment.Start.DateTime,
EndDate = appointment.End.DateTime
};
absences.Add(absence);
}
return absences;
}
static async Task<List<SprintCapacity>> GetSprintCapacity(string teamId, string sprintId)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PatToken);
var requestUrl = $"{AzureDevOpsUri}/{teamId}/_apis/work/teamsettings/iterations/{sprintId}/capacities?api-version=6.0";
var response = await httpClient.GetAsync(requestUrl);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var capacityResponse = JsonSerializer.Deserialize<AzureDevOpsCapacityResponse>(responseContent, options);
return capacityResponse.Capacities;
}
else
{
throw new Exception($"Failed to retrieve sprint capacity from Azure DevOps. Error: {responseContent}");
}
}
static List<SprintCapacity> UpdateCapacityWithAbsences(List<SprintCapacity> capacity, List<Absence> absences)
{
var updatedCapacity = new List<SprintCapacity>();
foreach (var cap in capacity)
{
var absence = absences.FirstOrDefault(a => a.TeamMemberEmail.Equals(cap.TeamMemberEmail));
if (absence != null)
{
cap.Activity = "Absence";
cap.CapacityPerDay = 0;
cap.StartDate = absence.StartDate.Date;
cap.EndDate = absence.EndDate.Date.AddDays(1).AddTicks(-1);
}
updatedCapacity.Add(cap);
}
return updatedCapacity;
}
static async Task PostCapacityToSprint(List<SprintCapacity> capacity)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PatToken);
var requestUrl = $"{AzureDevOpsUri}/{TeamId}/_apis/work/teamsettings/iterations/{IterationId}/capacities?api-version=6.0";
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var requestBody = JsonSerializer.Serialize(capacity, options);
var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(requestUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Failed to post capacity to Azure DevOps sprint capacity. Error: {responseContent}");
}
}
static async Task<string> GetPreviousSprintId()
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", PatToken);
var requestUrl = $"{AzureDevOpsUri}/{TeamId}/_apis/work/teamsettings/iterations/{IterationId}?api-version=6.0-preview.1";
var response = await httpClient.GetAsync(requestUrl);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var iteration = JsonSerializer.Deserialize<AzureDevOpsIteration>(responseContent, options);
return iteration.Relations.Single().Id;
}
else
{
throw new Exception($"Failed to retrieve previous sprint ID from Azure DevOps. Error: {responseContent}");
}
}
}
class GraphCalendarEventsResponse
{
public List<Appointment> Value { get; set; }
}
class Appointment
{
public string Subject { get; set; }
public GraphEmailAddress Organizer { get; set; }
public AppointmentDateTime Start { get; set; }
public AppointmentDateTime End { get; set; }
}
class GraphEmailAddress
{
public string Email { get; set; }
}
class AppointmentDateTime
{
public DateTime DateTime { get; set; }
}
class Absence
{
public string TeamId { get; set; }
public string IterationId { get; set; }
public string TeamMemberEmail { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
class AzureDevOpsCapacityResponse
{
public List<SprintCapacity> Capacities { get; set; }
}
class SprintCapacity
{
public string TeamMemberEmail { get; set; }
public string Activity { get; set; }
public double CapacityPerDay { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
class AzureDevOpsIteration
{
public List<AzureDevOpsRelation> Relations { get; set; }
public AzureDevOpsAttributes Attributes { get; set; }
}
class AzureDevOpsAttributes
{
public DateTime StartDate { get; set; }
public DateTime FinishDate { get; set; }
}
class AzureDevOpsRelation
{
public string Id { get; set; }
public string Rel { get; set; }
public string Url { get; set; }
}