Skip to content

Commit a521dfd

Browse files
committed
Refresh article
1 parent d7ed5ce commit a521dfd

File tree

1 file changed

+93
-98
lines changed

1 file changed

+93
-98
lines changed

docs/service-hooks/create-subscription.md

Lines changed: 93 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,33 @@
11
---
2-
title: Create a service hook subscription programmatically
3-
description: Use service hooks to set up actions to take when specific events occur in Azure DevOps.
2+
title: Create a Service Hook Subscription Programmatically
3+
description: Find out how to programmatically create a service hook subscription that configures an action to take when a specific event occurs in Azure DevOps.
44
ms.assetid: 0614F217-4F4E-45DC-A50C-B9FF81F8A5BD
55
ms.custom: engagement-fy23
66
ms.subservice: azure-devops-service-hooks
7-
ms.topic: conceptual
7+
ms.topic: how-to
88
ms.author: chcomley
99
author: chcomley
1010
monikerRange: '<= azure-devops'
11-
ms.date: 10/14/2022
11+
ms.date: 06/25/2025
12+
# customer intent: As a developer, I want to create a service hook subscription programmatically so that I can automate tasks in other services when events happen in my Azure DevOps project.
1213
---
1314

1415
# Create a service hook subscription programmatically
1516

16-
[!INCLUDE [version-lt-eq-azure-devops](../includes/version-lt-eq-azure-devops.md)]
17+
[!INCLUDE [Azure DevOps Services | Azure DevOps Server 2022 | Azure DevOps Server 2020](../includes/version-gt-eq-2020.md)]
1718

18-
You can use a subscription to perform an action on an external or consumer service when a specific event occurs in an Azure DevOps project. For example, a subscription can notify your service when a build fails. To create a subscription programmatically, you can use the [Subscriptions REST APIs](/rest/api/azure/devops/hooks/).
19+
You can use a subscription to perform an action on an external or consumer service when a specific event occurs in an Azure DevOps project. For example, a subscription can notify your service when a build fails.
20+
21+
To create a subscription programmatically, you can use the [Subscriptions REST APIs](/rest/api/azure/devops/hooks/). This article provides a sample request and sample code for creating a subscription.
22+
23+
## Prerequisites
24+
25+
| Category | Requirements |
26+
|--------------|-------------|
27+
|**Project access**| [Project member](../organizations/security/add-users-team-project.md). |
28+
|**Data**|- Project ID. Use the [Project REST API](/rest/api/azure/devops/core/projects) to get the project ID.<br>- Event ID and settings. See [Service hook events](events.md).<br>- Consumer and action IDs and settings. See [Service hook consumers](consumers.md).|
29+
30+
## Supported events
1931

2032
Azure DevOps provides support for numerous trigger events. Examples include the following events:
2133

@@ -25,22 +37,16 @@ Azure DevOps provides support for numerous trigger events. Examples include the
2537
- Code checked in (for Team Foundation Version Control projects)
2638
- Work item created, updated, deleted, restored, or commented on
2739

28-
To control which events trigger an action, you can configure filters on your subscriptions. For example, you can filter the build completed event based on the build status. For a complete set of supported events and filter options, see [Service hook events](./events.md).
40+
To control which events trigger an action, you can configure filters on your subscriptions. For example, you can filter the build completed event based on the build status.
2941

30-
For a complete set of supported consumer services and actions, see [Service hook consumers](./consumers.md).
42+
- For a complete set of supported events and filter options, see [Service hook events](events.md).
43+
- For a complete set of supported consumer services and actions, see [Service hook consumers](consumers.md).
3144

32-
## Prerequisites
45+
## Create a request
3346

34-
| Category | Requirements |
35-
|--------------|-------------|
36-
|**Project access**| [Project member](../organizations/security/add-users-team-project.md). |
37-
|**Data**|- Project ID. Use the [Project REST API](/rest/api/azure/devops/core/projects) to get the project ID.<br>- Event ID and settings. See [Service hook events](./events.md).<br>- Consumer and action IDs and settings. See [Service hook consumers](./consumers.md).|
47+
When you create a subscription, you use the body of an HTTP POST request to specify the project ID, event, consumer, action, and related settings.
3848

39-
## Create the request
40-
41-
When you create a subscription, the body of your HTTP POST request specifies the project ID, event, consumer, action, and related settings.
42-
43-
You can use the following request to create a subscription for a build completed event. It sends a POST request to `https://myservice/event` when the `WebSite.CI` build fails.
49+
You can use the following request to create a subscription for a build completed event. In this example, when the `WebSite.CI` build fails, the subscription sends a POST request to `https://myservice/event`.
4450

4551
**Request**
4652

@@ -116,103 +122,92 @@ You can specify the version of the resource that you want to send to the consume
116122
The resource version is the same as the [API version](../integrate/concepts/rest-api-versioning.md). If you don't specify a resource version, the latest version, `latest released`, is used. To help ensure a consistent event payload over time, always specify a resource version.
117123

118124
## FAQs
125+
119126
### Q: Are there services that I can subscribe to manually?
120127

121128
A: Yes. For more information about the services that you can subscribe to from a project administration page, see [Integrate with service hooks](overview.md).
122129

123130
### Q: Are there C# libraries that I can use to create subscriptions?
124131

125-
A: No, but here's a sample to help you get started.
132+
A: No, but here's a sample to help you get started. For authentication to Azure DevOps, the following code uses a personal access token (PAT) that's stored in Azure Key Vault. In a production environment, use a more secure authentication method. For more information, see [Choose the right authentication mechanism](../integrate/get-started/authentication/authentication-guidance.md).
126133

127-
```cs
128-
using System;
129-
using System.Collections.Generic;
130-
using System.Linq;
131-
using System.Net;
132-
using System.Net.Http;
133-
using System.Web.Mvc;
134+
```csharp
135+
using Azure.Identity;
136+
using Azure.Security.KeyVault.Secrets;
137+
using Microsoft.VisualStudio.Services.Common;
138+
using Microsoft.VisualStudio.Services.ServiceHooks.WebApi;
139+
using Microsoft.VisualStudio.Services.WebApi;
134140

135-
namespace Microsoft.Samples.VisualStudioOnline
141+
namespace CreateServiceHookSubscription
136142
{
137-
public class ServiceHookEventController : Controller
143+
internal class Program
138144
{
145+
// Create a service hook subscription to send a message to an Azure Service Bus queue when code is pushed to a Git repository.
139146
140-
// POST: /ServiceHookEvent/workitemcreated
141-
[HttpPost]
142-
public HttpResponseMessage WorkItemCreated(Content workItemEvent)
147+
static async Task Main(string[] args)
143148
{
144-
//Grabbing the title for the new workitem
145-
var value = RetrieveFieldValue("System.field", workItemEvent.Resource.Fields);
146-
147-
//Acknowledge event receipt
148-
return new HttpResponseMessage(HttpStatusCode.OK);
149+
// Get the secrets from the key vault.
150+
string keyVaultURI = "https://<key-vault-name>.vault.azure.net/";
151+
var secretClient = new SecretClient(new Uri(keyVaultURI), new DefaultAzureCredential());
152+
string personalAccessTokenSecretName = "<personal-access-token-secret-name>";
153+
string serviceBusConnectionStringSecretName = "<Service-Bus-connection-string-secret-name>";
154+
KeyVaultSecret personalAccessTokenSecret = await secretClient.GetSecretAsync(personalAccessTokenSecretName);
155+
KeyVaultSecret serviceBusConnectionStringSecret = await secretClient.GetSecretAsync(serviceBusConnectionStringSecretName);
156+
157+
// Set up the connection parameters for Azure DevOps.
158+
var azureDevOpsOrganizationURL = new Uri("https://dev.azure.com/<Azure-DevOps-organization-name>/");
159+
string azureDevOpsTeamProjectID = "<Azure-DevOps-team-project-ID>";
160+
string azureDevOpsPersonalAccessToken = personalAccessTokenSecret.Value;
161+
162+
// Set up the event parameters.
163+
string eventPublisherID = "tfs";
164+
string eventID = "git.push";
165+
string eventDescription = "Any stage in any release";
166+
string resourceVersion = "1.0";
167+
168+
// Set up the consumer parameters.
169+
string consumerID = "azureServiceBus";
170+
string consumerActionID = "serviceBusQueueSend";
171+
string serviceBusNamespace = "<Service-Bus-namespace>";
172+
string serviceBusQueueName = "<Service-Bus-queue-name>";
173+
string consumerActionDescription = $"Send a message to the Service Bus {serviceBusQueueName} queue in the {serviceBusNamespace} namespace.";
174+
string serviceBusConnectionString = serviceBusConnectionStringSecret.Value;
175+
176+
// Configure the subscription.
177+
var subscription = new Subscription()
178+
{
179+
PublisherId = eventPublisherID,
180+
PublisherInputs = new Dictionary<string, string>
181+
{
182+
["projectId"] = azureDevOpsTeamProjectID
183+
},
184+
EventType = eventID,
185+
EventDescription = eventDescription,
186+
ResourceVersion = resourceVersion,
187+
ActionDescription = consumerActionDescription,
188+
ConsumerActionId = consumerActionID,
189+
ConsumerId = consumerID,
190+
ConsumerInputs = new Dictionary<string, string>
191+
{
192+
["connectionString"] = serviceBusConnectionString,
193+
["queueName"] = serviceBusQueueName
194+
}
195+
};
196+
197+
// Connect to the Azure DevOps organization and get a service hook client.
198+
var azureDevOpsCredentials = new VssBasicCredential(azureDevOpsPersonalAccessToken, string.Empty);
199+
var azureDevOpsConnection = new VssConnection(azureDevOpsOrganizationURL, azureDevOpsCredentials);
200+
var serviceHookClient = azureDevOpsConnection.GetClient<ServiceHooksPublisherHttpClient>();
201+
202+
// Create the subscription.
203+
var createdSubscription = await serviceHookClient.CreateSubscriptionAsync(subscription);
204+
Console.WriteLine($"A subscription was created that has ID {createdSubscription.Id}.");
149205
}
150-
151-
/// <summary>
152-
/// Gets the value for a specified work item field.
153-
/// </summary>
154-
/// <param name="key">Key used to retrieve matching value</param>
155-
/// <param name="fields">List of fields for a work item</param>
156-
/// <returns></returns>
157-
public String RetrieveFieldValue(String key, IList<FieldInfo> fields)
158-
{
159-
if (String.IsNullOrEmpty(key))
160-
return String.Empty;
161-
162-
var result = fields.Single(s => s.Field.RefName == key);
163-
164-
return result.Value;
165-
}
166-
167-
}
168-
169-
public class Content
170-
{
171-
public String SubscriptionId { get; set; }
172-
173-
public int NotificationId { get; set; }
174-
175-
public String EventType { get; set; }
176-
177-
public WorkItemResource Resource { get; set; }
178-
179-
}
180-
181-
public class WorkItemResource
182-
{
183-
public String UpdatesUrl { get; set; }
184-
185-
public IList<FieldInfo> Fields { get; set;}
186-
187-
public int Id { get; set; }
188-
189-
public int Rev { get; set; }
190-
191-
public String Url { get; set; }
192-
193-
public String WebUrl { get; set; }
194-
}
195-
196-
public class FieldInfo
197-
{
198-
public FieldDetailedInfo Field { get; set; }
199-
200-
public String Value { get; set; }
201-
202-
}
203-
204-
public class FieldDetailedInfo
205-
{
206-
public int Id { get; set; }
207-
208-
public String Name { get; set; }
209-
210-
public String RefName { get; set; }
211206
}
212207
}
213208
```
214209

215-
## Related articles
210+
## Related content
216211

217212
- [Manage authorization of services to access Azure DevOps](authorize.md)
218213
- [Service hooks events](events.md)

0 commit comments

Comments
 (0)