This repository has been archived by the owner on Oct 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 513
/
ProjectsSample.cs
383 lines (304 loc) · 15.1 KB
/
ProjectsSample.cs
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Operations;
using Microsoft.VisualStudio.Services.WebApi;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
namespace Microsoft.Azure.DevOps.ClientSamples.ProjectsAndTeams
{
[ClientSample(CoreConstants.AreaName, CoreConstants.ProjectsRouteName)]
public class ProjectsSample: ClientSample
{
/// <summary>
/// Returns all team projects and the teams for each.
/// </summary>
/// <returns></returns>
[ClientSampleMethod]
public Dictionary<TeamProjectReference,IEnumerable<WebApiTeam>> ListAllProjectsAndTeams()
{
// Get the project and team clients
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
TeamHttpClient teamClient = connection.GetClient<TeamHttpClient>();
// Call to get the list of projects
IEnumerable<TeamProjectReference> projects = projectClient.GetProjects().Result;
Dictionary<TeamProjectReference, IEnumerable<WebApiTeam>> results = new Dictionary<TeamProjectReference, IEnumerable<WebApiTeam>>();
// Iterate over the returned projects
foreach (var project in projects)
{
// Get the teams for the project
IEnumerable<WebApiTeam> teams = teamClient.GetTeamsAsync(project.Name).Result;
// Add the project/teams item to the results dictionary
results.Add(project, teams);
Console.WriteLine(" " + project.Name);
// Iterate over the teams and show the name
foreach (var team in teams)
{
Console.WriteLine(" " + team.Name);
}
}
if (projects.Count() == 0)
{
Console.WriteLine("No projects found.");
}
return results;
}
/// <summary>
/// Returns only the first page of projects
/// </summary>
/// <returns></returns>
[ClientSampleMethod]
public IEnumerable<TeamProjectReference> ListProjectsByPage()
{
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
int currentPage = 0;
int pageSize = 3;
int lastPageSize = -1;
List<TeamProjectReference> allProjects = new List<TeamProjectReference>();
do
{
// Get a single page of projects
IEnumerable<TeamProjectReference> projects = projectClient.GetProjects(top: pageSize, skip: (currentPage * pageSize)).Result;
// Add the set to the full list
allProjects.AddRange(projects);
lastPageSize = projects.Count();
currentPage++;
Console.WriteLine(currentPage);
// Iterate and show the name of each project
foreach (var project in projects)
{
Console.WriteLine(" " + project.Name);
}
}
while (lastPageSize == pageSize);
return allProjects;
}
[ClientSampleMethod]
public TeamProjectReference GetProjectDetails()
{
string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
// Get the details for the specified project
TeamProject project = projectClient.GetProject(projectName, includeCapabilities: true, includeHistory: true).Result;
// Get the "web" URL for this project
ReferenceLink webLink = project.Links.Links["web"] as ReferenceLink;
Console.WriteLine("Details for project {0}:", projectName);
Console.WriteLine();
Console.WriteLine(" ID : {0}", project.Id);
Console.WriteLine(" Description : {0}", project.Description);
Console.WriteLine(" Web URL : {0}", (webLink != null ? webLink.Href : "(not available)"));
return project;
}
[ClientSampleMethod]
public TeamProject CreateProject()
{
string projectName = "Sample project " + Guid.NewGuid();
string projectDescription = "Short description for my new project";
string processName = "Agile";
// Setup version control properties
Dictionary<string, string> versionControlProperties = new Dictionary<string, string>();
versionControlProperties[TeamProjectCapabilitiesConstants.VersionControlCapabilityAttributeName] =
SourceControlTypes.Git.ToString();
// Setup process properties
ProcessHttpClient processClient = Context.Connection.GetClient<ProcessHttpClient>();
Guid processId = processClient.GetProcessesAsync().Result.Find(process => { return process.Name.Equals(processName, StringComparison.InvariantCultureIgnoreCase); }).Id;
Dictionary<string, string> processProperties = new Dictionary<string, string>();
processProperties[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityTemplateTypeIdAttributeName] =
processId.ToString();
// Construct capabilities dictionary
Dictionary<string, Dictionary<string, string>> capabilities = new Dictionary<string, Dictionary<string, string>>();
capabilities[TeamProjectCapabilitiesConstants.VersionControlCapabilityName] =
versionControlProperties;
capabilities[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityName] =
processProperties;
// Construct object containing properties needed for creating the project
TeamProject projectCreateParameters = new TeamProject()
{
Name = projectName,
Description = projectDescription,
Capabilities = capabilities
};
// Get a client
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
TeamProject project = null;
try
{
Console.WriteLine("Queuing project creation...");
// Queue the project creation operation
// This returns an operation object that can be used to check the status of the creation
OperationReference operation = projectClient.QueueCreateProject(projectCreateParameters).Result;
ClientSampleHttpLogger.SetSuppressOutput(Context, true);
// Check the operation status every 5 seconds (for up to 30 seconds)
Operation completedOperation = WaitForLongRunningOperation(operation.Id, 5, 30).Result;
// Check if the operation succeeded (the project was created) or failed
if (completedOperation.Status == OperationStatus.Succeeded)
{
// Get the full details about the newly created project
project = projectClient.GetProject(
projectCreateParameters.Name,
includeCapabilities: true,
includeHistory: true).Result;
Console.WriteLine();
Console.WriteLine("Project created (ID: {0})", project.Id);
// Save the newly created project (other sample methods will use it)
Context.SetValue<TeamProject>("$newProject", project);
}
else
{
Console.WriteLine("Project creation operation failed: " + completedOperation.ResultMessage);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception during create project: ", ex.Message);
}
return project;
}
private async Task<Operation> WaitForLongRunningOperation(Guid operationId, int interavalInSec = 5, int maxTimeInSeconds = 60, CancellationToken cancellationToken = default(CancellationToken))
{
OperationsHttpClient operationsClient = this.Context.Connection.GetClient<OperationsHttpClient>();
DateTime expiration = DateTime.Now.AddSeconds(maxTimeInSeconds);
int checkCount = 0;
while (true)
{
Console.WriteLine(" Checking status ({0})... ", (checkCount++));
Operation operation = await operationsClient.GetOperation(operationId, cancellationToken);
if (!operation.Completed)
{
Console.WriteLine(" Pausing {0} seconds", interavalInSec);
await Task.Delay(interavalInSec * 1000);
if (DateTime.Now > expiration)
{
throw new Exception(String.Format("Operation did not complete in {0} seconds.", maxTimeInSeconds));
}
}
else
{
return operation;
}
}
}
[ClientSampleMethod]
public bool ChangeProjectDescription()
{
// Use the project created in the earlier "create project" sample method
TeamProject project;
if (!Context.TryGetValue<TeamProject>("$newProject", out project))
{
Console.WriteLine("No previously created project to change the description of.");
return false;
}
TeamProject updatedProject = new TeamProject()
{
Description = "An event better description for my project!"
};
// Get a client
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
Console.WriteLine("Queuing project update...");
// Queue the update operation
Guid updateOperationId = projectClient.UpdateProject(project.Id, updatedProject).Result.Id;
ClientSampleHttpLogger.SetSuppressOutput(Context, true);
// Check the operation status every 2 seconds (for up to 30 seconds)
Operation detailedUpdateOperation = WaitForLongRunningOperation(updateOperationId, 2, 30).Result;
// Check if the operation succeeded (the project was created) or failed
if (detailedUpdateOperation.Status == OperationStatus.Succeeded)
{
Console.WriteLine();
Console.WriteLine("Project description change from:\n {1}\nto\n {2}", project.Name, project.Description, updatedProject.Description);
return true;
}
else
{
Console.WriteLine();
Console.WriteLine("Unable to change the description for project {0}", project.Name);
return false;
}
}
[ClientSampleMethod]
public bool RenameProject()
{
// Use the project created in the earlier "create project" sample method
TeamProject project;
if (!Context.TryGetValue<TeamProject>("$newProject", out project))
{
Console.WriteLine("No previously created project to change the name of.");
return false;
}
// Get a client
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
TeamProject updatedProject = new TeamProject()
{
Name = project.Name + " (renamed)"
};
Console.WriteLine("Queuing project update...");
// Queue the update operation
Guid updateOperationId = projectClient.UpdateProject(project.Id, updatedProject).Result.Id;
ClientSampleHttpLogger.SetSuppressOutput(Context, true);
// Check the operation status every 2 seconds (for up to 30 seconds)
Operation detailedUpdateOperation = WaitForLongRunningOperation(updateOperationId, 2, 30).Result;
if (detailedUpdateOperation.Status == OperationStatus.Succeeded)
{
Console.WriteLine();
Console.WriteLine("Project renamed from:\n {0}\nto\n {1}", project.Name, updatedProject.Name);
return true;
}
else
{
return false;
}
}
[ClientSampleMethod]
public bool DeleteProject()
{
// Use the project created in the earlier "create project" sample method
TeamProject project;
if (!Context.TryGetValue<TeamProject>("$newProject", out project))
{
Console.WriteLine("No previously created project found to delete.");
return false;
}
// Get a client
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
Console.WriteLine("Queuing project delete...");
// Queue the delete operation
Guid operationId = projectClient.QueueDeleteProject(project.Id).Result.Id;
ClientSampleHttpLogger.SetSuppressOutput(Context, true);
// Check the operation status every 2 seconds (for up to 30 seconds)
Operation operationResult = WaitForLongRunningOperation(operationId, 2, 30).Result;
Console.WriteLine();
Console.WriteLine("Delete project operation completed {0}", operationResult.Status);
return operationResult.Status == OperationStatus.Succeeded;
}
/// <summary>
/// List projects by their state. For example, only deleted projects.
/// </summary>
/// <returns></returns>
[ClientSampleMethod]
public IEnumerable<TeamProjectReference> ListProjectsByState()
{
ProjectState state = ProjectState.Deleting;
VssConnection connection = Context.Connection;
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
// Get a list of all the projects with a state of "deleting"
IEnumerable<TeamProjectReference> deletedProjects = projectClient.GetProjects(state).Result;
foreach (var project in deletedProjects)
{
Console.WriteLine(" " + project.Name);
}
if (deletedProjects.Count() == 0)
{
Console.WriteLine("No projects with the state {0}", state);
}
return deletedProjects;
}
}
}