Back

Step by Step Guide to Building an Azure DevOps API Integration in C#

Aug 2, 20247 minute read

Introduction

Hey there, fellow dev! Ready to dive into the world of Azure DevOps API integration? Buckle up, because we're about to embark on a journey that'll supercharge your DevOps workflow. We'll be using the Microsoft.TeamFoundationServer.Client package, so get ready for some serious API action.

Prerequisites

Before we jump in, make sure you've got these essentials:

  • Visual Studio (or your IDE of choice)
  • .NET Core SDK
  • An Azure DevOps account with a Personal Access Token (PAT)

Got all that? Great! Let's roll.

Setting up the project

First things first, let's get our project up and running:

  1. Fire up Visual Studio and create a new C# console application.
  2. Now, let's add some magic. Open up the Package Manager Console and run:
Install-Package Microsoft.TeamFoundationServer.Client

This'll give us all the tools we need to interact with Azure DevOps.

Connecting to Azure DevOps

Alright, time to establish our connection to Azure DevOps. Here's how:

using Microsoft.TeamFoundation.Core.WebApi; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.WebApi; var organizationUrl = "https://dev.azure.com/YourOrganization"; var personalAccessToken = "YourPATHere"; VssConnection connection = new VssConnection(new Uri(organizationUrl), new VssBasicCredential(string.Empty, personalAccessToken));

Just replace YourOrganization and YourPATHere with your actual details, and you're good to go!

Working with Azure DevOps API

Now that we're connected, let's do some cool stuff:

Get project information

var projectClient = connection.GetClient<ProjectHttpClient>(); var projects = await projectClient.GetProjects(); foreach (var project in projects) { Console.WriteLine($"Project Name: {project.Name}"); }

Retrieve work items

var witClient = connection.GetClient<WorkItemTrackingHttpClient>(); var workItems = await witClient.GetWorkItemsAsync(new List<int> { 1, 2, 3 }); // Replace with actual work item IDs foreach (var workItem in workItems) { Console.WriteLine($"Work Item Title: {workItem.Fields["System.Title"]}"); }

Create new work items

var newWorkItem = new JsonPatchDocument(); newWorkItem.Add(new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = "New work item created via API" }); var createdWorkItem = await witClient.CreateWorkItemAsync(newWorkItem, "YourProjectName", "Task"); Console.WriteLine($"Created Work Item ID: {createdWorkItem.Id}");

Update existing work items

var updateWorkItem = new JsonPatchDocument(); updateWorkItem.Add(new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.State", Value = "Doing" }); var updatedWorkItem = await witClient.UpdateWorkItemAsync(updateWorkItem, 123); // Replace with actual work item ID Console.WriteLine($"Updated Work Item State: {updatedWorkItem.Fields["System.State"]}");

Error handling and best practices

Don't forget to wrap your API calls in try-catch blocks. Azure DevOps can be a bit temperamental sometimes, so it's always good to be prepared:

try { // Your API calls here } catch (Exception ex) { Console.WriteLine($"Oops! Something went wrong: {ex.Message}"); }

Also, keep an eye on those rate limits. Azure DevOps isn't a fan of being bombarded with requests, so play nice!

Sample use case: Automating work item creation

Let's put it all together with a real-world example. Here's how you might automate creating a bunch of tasks:

var taskTitles = new List<string> { "Design UI", "Implement backend", "Write tests", "Deploy to staging" }; foreach (var title in taskTitles) { var newTask = new JsonPatchDocument(); newTask.Add(new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = title }); try { var createdTask = await witClient.CreateWorkItemAsync(newTask, "YourProjectName", "Task"); Console.WriteLine($"Created task: {createdTask.Id} - {title}"); } catch (Exception ex) { Console.WriteLine($"Failed to create task '{title}': {ex.Message}"); } }

Testing the integration

Once you've run your code, hop over to the Azure DevOps portal and check out your handiwork. You should see your newly created or updated work items right there in your project.

Conclusion

And there you have it! You've just built a solid Azure DevOps API integration using C#. Pretty cool, right? This is just the tip of the iceberg, though. There's so much more you can do with this API, so don't be afraid to experiment and push the boundaries.

Additional resources

Want to dive deeper? Check out these resources:

Now go forth and automate all the things! Happy coding!