├── media ├── web-hooks-1.png └── web-hooks-2.png ├── src ├── AutoStateTransitionsTest │ ├── AutoStateTransitionsTest.cs │ ├── Controllers │ │ └── ReceiverControllerTests.cs │ ├── AutoStateTransitionsTest.csproj │ └── Samples │ │ ├── post-task.json │ │ └── post-userstory.json ├── AutoStateTransitions │ ├── Repos │ │ ├── Interfaces │ │ │ ├── IRulesRepo.cs │ │ │ └── IWorkItemRepo.cs │ │ ├── RulesRepo.cs │ │ └── WorkItemRepo.cs │ ├── ViewModels │ │ ├── BaseViewModel.cs │ │ └── PayloadViewModel.cs │ ├── appsettings.json │ ├── Models │ │ ├── AppSettings.cs │ │ ├── StandardResponseObjectResult.cs │ │ └── RulesModel.cs │ ├── Rules │ │ ├── rules.task.json │ │ └── rules.user story.json │ ├── Misc │ │ └── Helper.cs │ ├── AutoStateTransitions.csproj │ ├── Program.cs │ ├── Startup.cs │ └── Controllers │ │ └── ReceiverController.cs └── azure-boards-automate-state-transitions.sln ├── CODE_OF_CONDUCT.md ├── .github └── workflows │ └── main-ci.yml ├── LICENSE ├── .vscode ├── tasks.json └── launch.json ├── SECURITY.md ├── README.md └── .gitignore /media/web-hooks-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/azure-boards-automate-state-transitions/HEAD/media/web-hooks-1.png -------------------------------------------------------------------------------- /media/web-hooks-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/azure-boards-automate-state-transitions/HEAD/media/web-hooks-2.png -------------------------------------------------------------------------------- /src/AutoStateTransitionsTest/AutoStateTransitionsTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | 3 | namespace AutoStateTransitionsTest 4 | { 5 | [TestClass] 6 | public class UnitTest1 7 | { 8 | [TestMethod] 9 | public void TestMethod1() 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Repos/Interfaces/IRulesRepo.cs: -------------------------------------------------------------------------------- 1 | using AutoStateTransitions.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | namespace AutoStateTransitions.Repos.Interfaces 7 | { 8 | public interface IRulesRepo 9 | { 10 | Task ListRules(string wit); 11 | } 12 | } -------------------------------------------------------------------------------- /src/AutoStateTransitions/ViewModels/BaseViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace AutoStateTransitions.ViewModels 7 | { 8 | public class BaseViewModel 9 | { 10 | public string organization { get; set; } 11 | public string pat { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*", 8 | "AppSettings": { 9 | "PersonalAccessToken": "", 10 | "Organization": "", 11 | "SourceForRules": "https://raw.githubusercontent.com/microsoft/azure-boards-automate-state-transitions/master/src/AutoStateTransitions/Rules" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Models/AppSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace AutoStateTransitions.Models 7 | { 8 | public class AppSettings 9 | { 10 | public string PersonalAccessToken { get; set; } 11 | public string Organization { get; set; } 12 | public string SourceForRules { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Models/StandardResponseObjectResult.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoStateTransitions.Models 8 | { 9 | public class StandardResponseObjectResult : ObjectResult 10 | { 11 | public StandardResponseObjectResult(object value, int statusCode) : base(value) 12 | { 13 | StatusCode = statusCode; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Rules/rules.task.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "Task", 3 | "rules": [ 4 | { 5 | "ifChildState": "Active", 6 | "notParentStates": [ "Active", "Resolved" ], 7 | "setParentStateTo": "Active", 8 | "allChildren": false 9 | }, 10 | { 11 | "ifChildState": "New", 12 | "notParentStates": [ "Active", "Resolved", "New" ], 13 | "setParentStateTo": "Active", 14 | "allChildren": false 15 | }, 16 | { 17 | "ifChildState": "Closed", 18 | "notParentStates": [], 19 | "setParentStateTo": "Closed", 20 | "allChildren": true 21 | } 22 | ] 23 | } -------------------------------------------------------------------------------- /src/AutoStateTransitionsTest/Controllers/ReceiverControllerTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | using Moq; 7 | using AutoStateTransitions.Repos; 8 | using AutoStateTransitions.Misc; 9 | using AutoStateTransitions.Repos.Interfaces; 10 | 11 | namespace AutoStateTransitionsTest.Controllers 12 | { 13 | [TestClass] 14 | public class ReceiverControllerTests 15 | { 16 | private Mock _mockWorkItemRepo; 17 | private Mock _mockRulesRepo; 18 | private Mock _mockHelper; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/main-ci.yml: -------------------------------------------------------------------------------- 1 | name: Automate State Transitions CI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Setup .NET Core 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 3.1.300 19 | 20 | - name: Restore with dotnet 21 | run: dotnet restore src 22 | 23 | - name: Build with dotnet 24 | run: dotnet build src --configuration Release 25 | 26 | - name: Test with dotnet 27 | run: dotnet test src --configuration Release 28 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Misc/Helper.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Linq; 3 | using System; 4 | 5 | 6 | namespace AutoStateTransitions.Misc 7 | { 8 | public class Helper : IHelper 9 | { 10 | public Int32 GetWorkItemIdFromUrl(string url) 11 | { 12 | Int32 lastIndexOf = url.LastIndexOf("/"); 13 | Int32 size = url.Length - (lastIndexOf + 1); 14 | 15 | string value = url.Substring(lastIndexOf + 1, size); 16 | 17 | return Convert.ToInt32(value); 18 | } 19 | } 20 | 21 | public interface IHelper 22 | { 23 | Int32 GetWorkItemIdFromUrl(string url); 24 | 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Repos/Interfaces/IWorkItemRepo.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models; 2 | using Microsoft.VisualStudio.Services.WebApi; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | namespace AutoStateTransitions.Repos.Interfaces 9 | { 10 | public interface IWorkItemRepo 11 | { 12 | Task GetWorkItem(VssConnection connection, int id); 13 | Task> ListChildWorkItemsForParent(VssConnection connection, WorkItem parentWorkItem); 14 | Task UpdateWorkItemState(VssConnection connection, WorkItem workItem, string state); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/ViewModels/PayloadViewModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace AutoStateTransitions.ViewModels 7 | { 8 | public class PayloadViewModel : BaseViewModel 9 | { 10 | public int workItemId { get; set; } 11 | public string workItemType { get; set; } 12 | public int parentId { get; set; } 13 | public int parentUrl { get; set; } 14 | public string eventType { get; set; } 15 | public int rev { get; set; } 16 | public string teamProject { get; set; } 17 | public string url { get; set; } 18 | public string state { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/AutoStateTransitions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | InProcess 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | Always 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace AutoStateTransitions 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseStartup(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Rules/rules.user story.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "User Story", 3 | "rules": [ 4 | { 5 | "ifChildState": "Active", 6 | "notParentStates": [ "Active", "Resolved" ], 7 | "setParentStateTo": "Active", 8 | "allChildren": false 9 | }, 10 | { 11 | "ifChildState": "New", 12 | "notParentStates": [ "Active", "Resolved", "New" ], 13 | "setParentStateTo": "Active", 14 | "allChildren": false 15 | }, 16 | { 17 | "ifChildState": "Resolved", 18 | "notParentStates": [], 19 | "setParentStateTo": "Resolved", 20 | "allChildren": true 21 | }, 22 | { 23 | "ifChildState": "Closed", 24 | "notParentStates": [], 25 | "setParentStateTo": "Closed", 26 | "allChildren": true 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /src/AutoStateTransitionsTest/AutoStateTransitionsTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | PreserveNewest 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Models/RulesModel.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoStateTransitions.Models 8 | { 9 | public class RulesModel 10 | { 11 | [JsonProperty(PropertyName = "type")] 12 | public string Type { get; set; } 13 | 14 | [JsonProperty(PropertyName = "rules")] 15 | public Rule[] Rules { get; set; } 16 | } 17 | 18 | public class Rule 19 | { 20 | [JsonProperty(PropertyName = "ifChildState")] 21 | public string IfChildState { get; set; } 22 | 23 | [JsonProperty(PropertyName = "notParentStates")] 24 | public string[] NotParentStates { get; set; } 25 | 26 | [JsonProperty(PropertyName = "setParentStateTo")] 27 | public string SetParentStateTo { get; set; } 28 | 29 | [JsonProperty(PropertyName = "allChildren")] 30 | public bool AllChildren { get; set; } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/src/AutoStateTransitions/AutoStateTransitions.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/src/AutoStateTransitions/AutoStateTransitions.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/src/AutoStateTransitions/AutoStateTransitions.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/src/AutoStateTransitions/bin/Debug/netcoreapp2.2/AutoStateTransitions.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/src/AutoStateTransitions", 16 | "stopAtEntry": false, 17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser 18 | "serverReadyAction": { 19 | "action": "openExternally", 20 | "pattern": "^\\s*Now listening on:\\s+(https?://\\S+)" 21 | }, 22 | "env": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | }, 25 | "sourceFileMap": { 26 | "/Views": "${workspaceFolder}/Views" 27 | } 28 | }, 29 | { 30 | "name": ".NET Core Attach", 31 | "type": "coreclr", 32 | "request": "attach", 33 | "processId": "${command:pickProcess}" 34 | } 35 | ] 36 | } -------------------------------------------------------------------------------- /src/azure-boards-automate-state-transitions.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29215.179 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoStateTransitions", "AutoStateTransitions\AutoStateTransitions.csproj", "{54ED1158-23C3-4493-AB2B-3DA956C83CDE}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoStateTransitionsTest", "AutoStateTransitionsTest\AutoStateTransitionsTest.csproj", "{F8D21D5A-5372-49A6-8939-B3B1C8D95A09}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {54ED1158-23C3-4493-AB2B-3DA956C83CDE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {54ED1158-23C3-4493-AB2B-3DA956C83CDE}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {54ED1158-23C3-4493-AB2B-3DA956C83CDE}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {54ED1158-23C3-4493-AB2B-3DA956C83CDE}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {F8D21D5A-5372-49A6-8939-B3B1C8D95A09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {F8D21D5A-5372-49A6-8939-B3B1C8D95A09}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {F8D21D5A-5372-49A6-8939-B3B1C8D95A09}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {F8D21D5A-5372-49A6-8939-B3B1C8D95A09}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {36E30DF4-62D7-43F5-BED8-E2DF65203271} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Repos/RulesRepo.cs: -------------------------------------------------------------------------------- 1 | using AutoStateTransitions.Misc; 2 | using AutoStateTransitions.Models; 3 | using AutoStateTransitions.Repos.Interfaces; 4 | using Microsoft.Extensions.Options; 5 | using Newtonsoft.Json; 6 | using System; 7 | using System.Collections; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Net.Http; 11 | using System.Threading.Tasks; 12 | 13 | namespace AutoStateTransitions.Repos 14 | { 15 | public class RulesRepo : IRulesRepo, IDisposable 16 | { 17 | private IOptions _appSettings; 18 | private IHelper _helper; 19 | private HttpClient _httpClient; 20 | 21 | public RulesRepo(IOptions appSettings, IHelper helper, HttpClient httpClient) 22 | { 23 | _appSettings = appSettings; 24 | _helper = helper; 25 | _httpClient = httpClient; 26 | } 27 | 28 | public async Task ListRules(string wit) 29 | { 30 | string src = _appSettings.Value.SourceForRules; 31 | 32 | var json = await _httpClient.GetStringAsync(src + "/rules." + wit.ToLower() + ".json"); 33 | RulesModel rules = JsonConvert.DeserializeObject(json); 34 | 35 | return rules; 36 | 37 | } 38 | 39 | public void Dispose() 40 | { 41 | Dispose(true); 42 | GC.SuppressFinalize(this); 43 | } 44 | 45 | ~RulesRepo() 46 | { 47 | // Finalizer calls Dispose(false) 48 | Dispose(false); 49 | } 50 | 51 | protected virtual void Dispose(bool disposing) 52 | { 53 | if (disposing) 54 | { 55 | _appSettings = null; 56 | _helper = null; 57 | } 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [many more](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets Microsoft's [definition](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)) of a security vulnerability, please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** Instead, please report them to the Microsoft Security Response Center at [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://technet.microsoft.com/en-us/security/dn606155). 12 | 13 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 14 | 15 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 16 | 17 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 18 | * Full paths of source file(s) related to the manifestation of the issue 19 | * The location of the affected source code (tag/branch/commit or direct URL) 20 | * Any special configuration required to reproduce the issue 21 | * Step-by-step instructions to reproduce the issue 22 | * Proof-of-concept or exploit code (if possible) 23 | * Impact of the issue, including how an attacker might exploit the issue 24 | 25 | This information will help us triage your report more quickly. 26 | 27 | ## Preferred Languages 28 | 29 | We prefer all communications to be in English. 30 | 31 | ## Policy 32 | 33 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). 34 | 35 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Startup.cs: -------------------------------------------------------------------------------- 1 | 2 | using AutoStateTransitions.Misc; 3 | using AutoStateTransitions.Models; 4 | using AutoStateTransitions.Repos; 5 | using AutoStateTransitions.Repos.Interfaces; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Hosting; 12 | using Microsoft.OpenApi.Models; 13 | 14 | namespace AutoStateTransitions 15 | { 16 | public class Startup 17 | { 18 | public Startup(IWebHostEnvironment env, IConfiguration config) 19 | { 20 | var builder = new ConfigurationBuilder() 21 | .SetBasePath(env.ContentRootPath) 22 | .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 23 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 24 | .AddEnvironmentVariables(); 25 | 26 | Configuration = config; 27 | HostingEnvironment = env; 28 | } 29 | 30 | public IConfiguration Configuration { get; } 31 | public IWebHostEnvironment HostingEnvironment { get; } 32 | 33 | // This method gets called by the runtime. Use this method to add services to the container. 34 | public void ConfigureServices(IServiceCollection services) 35 | { 36 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); 37 | 38 | services.AddSwaggerGen(c => 39 | { 40 | c.SwaggerDoc("v1", new OpenApiInfo { Title = "Azure DevOps - Automate State Transitions", Version = "v1" }); 41 | }); 42 | 43 | services.Configure(Configuration.GetSection("AppSettings")); 44 | services.AddTransient(); 45 | 46 | services.AddTransient(); 47 | services.AddTransient(); 48 | 49 | services.AddControllersWithViews(); 50 | services.AddHealthChecks(); 51 | 52 | } 53 | 54 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 55 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 56 | { 57 | if (env.IsDevelopment()) 58 | { 59 | app.UseDeveloperExceptionPage(); 60 | } 61 | else 62 | { 63 | app.UseHsts(); 64 | } 65 | 66 | app.UseSwagger(); 67 | app.UseSwaggerUI(c => 68 | { 69 | c.SwaggerEndpoint("/swagger/v1/swagger.json", "Azure DevOps - Automate State Transitions"); 70 | }); 71 | 72 | app.UseHttpsRedirection(); 73 | 74 | app.UseRouting(); 75 | app.UseAuthentication(); 76 | app.UseAuthorization(); 77 | app.UseCors(); 78 | app.UseEndpoints(endpoints => { 79 | endpoints.MapHealthChecks("/health"); 80 | endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); 81 | }); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Repos/WorkItemRepo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | using Microsoft.VisualStudio.Services.WebApi.Patch.Json; 6 | using Microsoft.VisualStudio.Services.WebApi.Patch; 7 | using Microsoft.Extensions.Options; 8 | using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models; 9 | using Microsoft.VisualStudio.Services.WebApi; 10 | 11 | using AutoStateTransitions.Misc; 12 | using AutoStateTransitions.Models; 13 | using Microsoft.TeamFoundation.WorkItemTracking.WebApi; 14 | using System.Threading.Tasks; 15 | using AutoStateTransitions.Repos.Interfaces; 16 | 17 | namespace AutoStateTransitions.Repos 18 | { 19 | public class WorkItemRepo : IWorkItemRepo, IDisposable 20 | { 21 | private IOptions _appSettings; 22 | private IHelper _helper; 23 | 24 | public WorkItemRepo(IOptions appSettings, IHelper helper) 25 | { 26 | _appSettings = appSettings; 27 | _helper = helper; 28 | } 29 | 30 | public async Task GetWorkItem(VssConnection connection, int id) 31 | { 32 | using (WorkItemTrackingHttpClient client = connection.GetClient()) 33 | { 34 | 35 | try 36 | { 37 | return await client.GetWorkItemAsync(id, null, null, WorkItemExpand.Relations); 38 | 39 | } 40 | catch (Exception) 41 | { 42 | return null; 43 | } 44 | } 45 | } 46 | 47 | public async Task> ListChildWorkItemsForParent(VssConnection connection, WorkItem parentWorkItem) 48 | { 49 | List list = new List(); 50 | using (WorkItemTrackingHttpClient client = connection.GetClient()) 51 | { 52 | // get all the related child work item links 53 | IEnumerable children = parentWorkItem.Relations.Where(x => x.Rel.Equals("System.LinkTypes.Hierarchy-Forward")); 54 | IList Ids = new List(); 55 | 56 | // loop through children and extract the id's the from the url 57 | foreach (var child in children) 58 | { 59 | Ids.Add(_helper.GetWorkItemIdFromUrl(child.Url)); 60 | } 61 | 62 | // in this case we only care about the state of the child work items 63 | string[] fields = new string[] { "System.State" }; 64 | 65 | // go get the full list of child work items with the desired fields 66 | return await client.GetWorkItemsAsync(Ids, fields); 67 | } 68 | 69 | } 70 | 71 | public async Task UpdateWorkItemState(VssConnection connection, WorkItem workItem, string state) 72 | { 73 | JsonPatchDocument patchDocument = new JsonPatchDocument(); 74 | 75 | patchDocument.Add( 76 | new JsonPatchOperation() 77 | { 78 | Operation = Operation.Test, 79 | Path = "/rev", 80 | Value = workItem.Rev.ToString() 81 | } 82 | ); 83 | 84 | patchDocument.Add( 85 | new JsonPatchOperation() 86 | { 87 | Operation = Operation.Add, 88 | Path = "/fields/System.State", 89 | Value = state 90 | } 91 | ); 92 | 93 | WorkItem result = null; 94 | 95 | using (WorkItemTrackingHttpClient client = connection.GetClient()) 96 | { 97 | 98 | try 99 | { 100 | result = await client.UpdateWorkItemAsync(patchDocument, Convert.ToInt32(workItem.Id)); 101 | } 102 | catch (Exception) 103 | { 104 | result = null; 105 | } 106 | } 107 | 108 | return result; 109 | } 110 | 111 | public void Dispose() 112 | { 113 | Dispose(true); 114 | GC.SuppressFinalize(this); 115 | } 116 | 117 | ~WorkItemRepo() 118 | { 119 | // Finalizer calls Dispose(false) 120 | Dispose(false); 121 | } 122 | 123 | protected virtual void Dispose(bool disposing) 124 | { 125 | if (disposing) 126 | { 127 | _appSettings = null; 128 | _helper = null; 129 | } 130 | } 131 | } 132 | 133 | 134 | } 135 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Automate State Transitions CI](https://github.com/microsoft/azure-boards-automate-state-transitions/workflows/Automate%20State%20Transitions%20CI/badge.svg?branch=master) 2 | 3 | # Azure Boards - Automate State Transitions 4 | 5 | This project was created to help automate the updating of parent state transitions depending on the state of the child work items. 6 | 7 | This API receives an Azure Boards work item update web hook event. The API will load the work item, check against a series of rules, and update it's parent work item accordingly. 8 | 9 | For example, if your User Story is New and you create a task and set that task to active, the User Story should automatically be set to Active. 10 | 11 | # Setup 12 | 13 | 1. Create a new Azure DevOps [Personal Access Token](https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate) 14 | 15 | 2. Include the Personal Access Token into the appsettings.json file 16 | 17 | ``` 18 | "AppSettings": { 19 | "PersonalAccessToken": "", 20 | "Organization": "", 21 | "SourceForRules": "https://raw.githubusercontent.com/microsoft/azure-boards-automate-state-transitions/master/src/AutoStateTransitions/Rules/" 22 | ``` 23 | 24 | 3. Deploy the project so that it is available from the Azure DevOps instance. Be sure to check if DotNetCore 3 is available (either by using the Azure WebApp Extension, or by deploying it with the package (see [blog on self-contained](https://timheuer.com/blog/archive/2019/10/03/deploy-aspnet-core-applications-using-self-contained-dotnet-core.aspx) )) 25 | 26 | 4. Create a new web hook for the child work item types. In this example we are just setting up web hooks for when Task work items are updated. The web hook should send when the state field is changed. 27 | 28 | ![](./media/web-hooks-1.png) 29 | 30 | Populate the URL Field with the url from the deployed instance carried out in previous step along with /api/receiver/webhook/workitem/update appened. 31 | 32 | ![](./media/web-hooks-2.png) 33 | 34 | 5. Update the rules in the JSON configuration file for each child work item type. In this example we are going to update the Task (rule.task.json). You will need an entry for each state. 35 | 36 | ``` 37 | { 38 | "type": "Task", 39 | "rules": [ 40 | { 41 | "ifChildState": "Active", 42 | "notParentStates": [ "Active", "Resolved" ], 43 | "setParentStateTo": "Active", 44 | "allChildren": false 45 | }, 46 | { 47 | "ifChildState": "New", 48 | "notParentStates": [ "Active", "Resolved", "New" ], 49 | "setParentStateTo": "Active", 50 | "allChildren": false 51 | }, 52 | { 53 | "ifChildState": "Closed", 54 | "notParentStates": [], 55 | "setParentStateTo": "Closed", 56 | "allChildren": true 57 | } 58 | ] 59 | } 60 | ``` 61 | 62 | **ifChildStates**: If the the work item status is this 63 | 64 | **notParentStates**: If the parent state is not one of these 65 | 66 | **setParentStateTo**: Then set the parent state to this 67 | 68 | **allChildren**: If true, then all child items need to be this state to update the parent 69 | 70 | #### Example 1 71 | 72 | User Story is set to New and it has 4 Tasks that are also new. As soon as a task is set to "Active" then set the User Story to "Active". 73 | 74 | ``` 75 | { 76 | "ifChildState": "Active", 77 | "notParentStates": [ "Active", "Resolved" ], 78 | "setParentStateTo": "Active", 79 | "allChildren": false 80 | }, 81 | ``` 82 | 83 | #### Example 2 84 | 85 | If User Story is "Active" and all the child Tasks are set to "Closed". Then lets set the User Story to "Closed" 86 | 87 | ``` 88 | { 89 | "ifChildState": "Closed", 90 | "notParentStates": [], 91 | "setParentStateTo": "Closed", 92 | "allChildren": false 93 | }, 94 | ``` 95 | 96 | 6. Point to the correct url for your rules files. By default the rules files are [stored in this location](https://raw.githubusercontent.com/microsoft/azure-boards-automate-state-transitions/master/src/AutoStateTransitions/Rules/). You can edit the location in the [appsettings.json](https://github.com/microsoft/azure-boards-automate-state-transitions/blob/master/src/AutoStateTransitions/appsettings.json) file. 97 | 98 | ``` 99 | "AppSettings": { 100 | "PersonalAccessToken": "", 101 | "Organization": "", 102 | "SourceForRules": "https://raw.githubusercontent.com/microsoft/azure-boards-automate-state-transitions/master/src/AutoStateTransitions/Rules/" 103 | ``` 104 | 105 | **_Note: Rule files have only been setup for User Story and Task._** 106 | 107 | # Contributing 108 | 109 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 110 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 111 | the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. 112 | 113 | When you submit a pull request, a CLA bot will automatically determine whether you need to provide 114 | a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions 115 | provided by the bot. You will only need to do this once across all repos using our CLA. 116 | 117 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 118 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 119 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 120 | -------------------------------------------------------------------------------- /src/AutoStateTransitionsTest/Samples/post-task.json: -------------------------------------------------------------------------------- 1 | { 2 | "subscriptionId": "2ea3f99e-4f4e-40ba-8711-8777c5002913", 3 | "notificationId": 1, 4 | "id": "2332bb4d-4d26-4f37-b577-b06153c2a838", 5 | "eventType": "workitem.updated", 6 | "publisherId": "tfs", 7 | "message": null, 8 | "detailedMessage": null, 9 | "resource": { 10 | "id": 8, 11 | "workItemId": 197, 12 | "rev": 8, 13 | "revisedBy": { 14 | "id": "a3643d15-6656-41b5-828f-10bb956cca26", 15 | "name": "Dan Hellem ", 16 | "displayName": "Dan Hellem", 17 | "url": "https://spsprodcus3.vssps.visualstudio.com/A1b3e9b27-3208-4ac4-b4e8-6c4f63b735f0/_apis/Identities/a3643d15-6656-41b5-828f-10bb956cca26", 18 | "_links": { 19 | "avatar": { 20 | "href": "https://dev.azure.com/basicprocess/_apis/GraphProfile/MemberAvatars/msa.OTgzNGQ5YmItZTNkOS03YjU3LWI2NjMtZGQ2OWMwNjc1ZjRh" 21 | } 22 | }, 23 | "uniqueName": "dan_hellem@hotmail.com", 24 | "imageUrl": "https://dev.azure.com/basicprocess/_apis/GraphProfile/MemberAvatars/msa.OTgzNGQ5YmItZTNkOS03YjU3LWI2NjMtZGQ2OWMwNjc1ZjRh", 25 | "descriptor": "msa.OTgzNGQ5YmItZTNkOS03YjU3LWI2NjMtZGQ2OWMwNjc1ZjRh" 26 | }, 27 | "revisedDate": "9999-01-01T00:00:00Z", 28 | "fields": { 29 | "System.Rev": { 30 | "oldValue": 7, 31 | "newValue": 8 32 | }, 33 | "System.AuthorizedDate": { 34 | "oldValue": "2019-08-27T15:07:29.56Z", 35 | "newValue": "2019-08-27T15:15:36.57Z" 36 | }, 37 | "System.RevisedDate": { 38 | "oldValue": "2019-08-27T15:15:36.57Z", 39 | "newValue": "9999-01-01T00:00:00Z" 40 | }, 41 | "System.State": { 42 | "oldValue": "New", 43 | "newValue": "Active" 44 | }, 45 | "System.Reason": { 46 | "oldValue": "Work halted", 47 | "newValue": "Work started" 48 | }, 49 | "System.ChangedDate": { 50 | "oldValue": "2019-08-27T15:07:29.56Z", 51 | "newValue": "2019-08-27T15:15:36.57Z" 52 | }, 53 | "System.Watermark": { 54 | "oldValue": 606, 55 | "newValue": 608 56 | }, 57 | "Microsoft.VSTS.Common.StateChangeDate": { 58 | "oldValue": "2019-08-27T15:07:29.56Z", 59 | "newValue": "2019-08-27T15:15:36.57Z" 60 | }, 61 | "Microsoft.VSTS.Common.ActivatedDate": { 62 | "newValue": "2019-08-27T15:15:36.57Z" 63 | }, 64 | "Microsoft.VSTS.Common.ActivatedBy": { 65 | "newValue": "Dan Hellem " 66 | } 67 | }, 68 | "_links": { 69 | "self": { 70 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197/updates/8" 71 | }, 72 | "workItemUpdates": { 73 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197/updates" 74 | }, 75 | "parent": { 76 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197" 77 | }, 78 | "html": { 79 | "href": "https://dev.azure.com/basicprocess/web/wi.aspx?pcguid=5086bf88-dcd7-4e57-9e07-04c5b5baa818&id=197" 80 | } 81 | }, 82 | "url": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197/updates/8", 83 | "revision": { 84 | "id": 197, 85 | "rev": 8, 86 | "fields": { 87 | "System.AreaPath": "Franciscos", 88 | "System.TeamProject": "Franciscos", 89 | "System.IterationPath": "Franciscos\\Iteration 1", 90 | "System.WorkItemType": "Task", 91 | "System.State": "Active", 92 | "System.Reason": "Work started", 93 | "System.AssignedTo": "Dan Hellem ", 94 | "System.CreatedDate": "2019-08-27T14:58:06.843Z", 95 | "System.CreatedBy": "Dan Hellem ", 96 | "System.ChangedDate": "2019-08-27T15:15:36.57Z", 97 | "System.ChangedBy": "Dan Hellem ", 98 | "System.CommentCount": 0, 99 | "System.Title": "Test Task 2", 100 | "Microsoft.VSTS.Common.StateChangeDate": "2019-08-27T15:15:36.57Z", 101 | "Microsoft.VSTS.Common.ActivatedDate": "2019-08-27T15:15:36.57Z", 102 | "Microsoft.VSTS.Common.ActivatedBy": "Dan Hellem ", 103 | "Microsoft.VSTS.Common.Priority": 2 104 | }, 105 | "relations": [ 106 | { 107 | "rel": "System.LinkTypes.Hierarchy-Reverse", 108 | "url": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/193", 109 | "attributes": { 110 | "isLocked": false, 111 | "name": "Parent" 112 | } 113 | } 114 | ], 115 | "_links": { 116 | "self": { 117 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197/revisions/8" 118 | }, 119 | "workItemRevisions": { 120 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197/revisions" 121 | }, 122 | "parent": { 123 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197" 124 | } 125 | }, 126 | "url": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/197/revisions/8" 127 | } 128 | }, 129 | "resourceVersion": "1.0", 130 | "resourceContainers": { 131 | "collection": { 132 | "id": "5086bf88-dcd7-4e57-9e07-04c5b5baa818", 133 | "baseUrl": "https://dev.azure.com/basicprocess/" 134 | }, 135 | "account": { 136 | "id": "1b3e9b27-3208-4ac4-b4e8-6c4f63b735f0", 137 | "baseUrl": "https://dev.azure.com/basicprocess/" 138 | }, 139 | "project": { 140 | "id": "60c8b0ff-04c3-45a8-a4be-69b01cfe6da2", 141 | "baseUrl": "https://dev.azure.com/basicprocess/" 142 | } 143 | }, 144 | "createdDate": "2019-08-27T15:15:43.7000788Z" 145 | } 146 | -------------------------------------------------------------------------------- /src/AutoStateTransitionsTest/Samples/post-userstory.json: -------------------------------------------------------------------------------- 1 | { 2 | "subscriptionId": "d4fbcfeb-ef5d-4819-bdb2-89943d09a528", 3 | "notificationId": 1, 4 | "id": "be278bbc-652a-4fbc-ab62-cd646490884e", 5 | "eventType": "workitem.updated", 6 | "publisherId": "tfs", 7 | "message": null, 8 | "detailedMessage": null, 9 | "resource": { 10 | "id": 2, 11 | "workItemId": 194, 12 | "rev": 2, 13 | "revisedBy": { 14 | "id": "a3643d15-6656-41b5-828f-10bb956cca26", 15 | "name": "Dan Hellem ", 16 | "displayName": "Dan Hellem", 17 | "url": "https://spsprodcus3.vssps.visualstudio.com/A1b3e9b27-3208-4ac4-b4e8-6c4f63b735f0/_apis/Identities/a3643d15-6656-41b5-828f-10bb956cca26", 18 | "_links": { 19 | "avatar": { 20 | "href": "https://dev.azure.com/basicprocess/_apis/GraphProfile/MemberAvatars/msa.OTgzNGQ5YmItZTNkOS03YjU3LWI2NjMtZGQ2OWMwNjc1ZjRh" 21 | } 22 | }, 23 | "uniqueName": "dan_hellem@hotmail.com", 24 | "imageUrl": "https://dev.azure.com/basicprocess/_apis/GraphProfile/MemberAvatars/msa.OTgzNGQ5YmItZTNkOS03YjU3LWI2NjMtZGQ2OWMwNjc1ZjRh", 25 | "descriptor": "msa.OTgzNGQ5YmItZTNkOS03YjU3LWI2NjMtZGQ2OWMwNjc1ZjRh" 26 | }, 27 | "revisedDate": "9999-01-01T00:00:00Z", 28 | "fields": { 29 | "System.Rev": { 30 | "oldValue": 1, 31 | "newValue": 2 32 | }, 33 | "System.AuthorizedDate": { 34 | "oldValue": "2019-08-26T14:42:54.673Z", 35 | "newValue": "2019-09-05T15:28:05.557Z" 36 | }, 37 | "System.RevisedDate": { 38 | "oldValue": "2019-09-05T15:28:05.557Z", 39 | "newValue": "9999-01-01T00:00:00Z" 40 | }, 41 | "System.State": { 42 | "oldValue": "New", 43 | "newValue": "Active" 44 | }, 45 | "System.Reason": { 46 | "oldValue": "New", 47 | "newValue": "Implementation started" 48 | }, 49 | "System.AssignedTo": { 50 | "newValue": "Dan Hellem " 51 | }, 52 | "System.ChangedDate": { 53 | "oldValue": "2019-08-26T14:42:54.673Z", 54 | "newValue": "2019-09-05T15:28:05.557Z" 55 | }, 56 | "System.Watermark": { 57 | "oldValue": 595, 58 | "newValue": 629 59 | }, 60 | "System.BoardColumn": { 61 | "oldValue": "New", 62 | "newValue": "Active" 63 | }, 64 | "Microsoft.VSTS.Common.StateChangeDate": { 65 | "oldValue": "2019-08-26T14:42:54.673Z", 66 | "newValue": "2019-09-05T15:28:05.557Z" 67 | }, 68 | "Microsoft.VSTS.Common.ActivatedDate": { 69 | "newValue": "2019-09-05T15:28:05.557Z" 70 | }, 71 | "Microsoft.VSTS.Common.ActivatedBy": { 72 | "newValue": "Dan Hellem " 73 | }, 74 | "WEF_2D808B8B1E8846A892636188CD38BC17_Kanban.Column": { 75 | "oldValue": "New", 76 | "newValue": "Active" 77 | } 78 | }, 79 | "_links": { 80 | "self": { 81 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194/updates/2" 82 | }, 83 | "workItemUpdates": { 84 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194/updates" 85 | }, 86 | "parent": { 87 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194" 88 | }, 89 | "html": { 90 | "href": "https://dev.azure.com/basicprocess/web/wi.aspx?pcguid=5086bf88-dcd7-4e57-9e07-04c5b5baa818&id=194" 91 | } 92 | }, 93 | "url": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194/updates/2", 94 | "revision": { 95 | "id": 194, 96 | "rev": 2, 97 | "fields": { 98 | "System.AreaPath": "Franciscos", 99 | "System.TeamProject": "Franciscos", 100 | "System.IterationPath": "Franciscos\\Iteration 1", 101 | "System.WorkItemType": "User Story", 102 | "System.State": "Active", 103 | "System.Reason": "Implementation started", 104 | "System.AssignedTo": "Dan Hellem ", 105 | "System.CreatedDate": "2019-08-26T14:42:54.673Z", 106 | "System.CreatedBy": "Dan Hellem ", 107 | "System.ChangedDate": "2019-09-05T15:28:05.557Z", 108 | "System.ChangedBy": "Dan Hellem ", 109 | "System.CommentCount": 0, 110 | "System.Title": "User Story 2", 111 | "System.BoardColumn": "Active", 112 | "System.BoardColumnDone": false, 113 | "Microsoft.VSTS.Common.StateChangeDate": "2019-09-05T15:28:05.557Z", 114 | "Microsoft.VSTS.Common.ActivatedDate": "2019-09-05T15:28:05.557Z", 115 | "Microsoft.VSTS.Common.ActivatedBy": "Dan Hellem ", 116 | "Microsoft.VSTS.Common.Priority": 2, 117 | "Microsoft.VSTS.Common.ValueArea": "Business", 118 | "WEF_2D808B8B1E8846A892636188CD38BC17_Kanban.Column": "Active", 119 | "WEF_2D808B8B1E8846A892636188CD38BC17_Kanban.Column.Done": false 120 | }, 121 | "relations": [ 122 | { 123 | "rel": "System.LinkTypes.Hierarchy-Reverse", 124 | "url": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/159", 125 | "attributes": { 126 | "isLocked": false, 127 | "name": "Parent" 128 | } 129 | } 130 | ], 131 | "_links": { 132 | "self": { 133 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194/revisions/2" 134 | }, 135 | "workItemRevisions": { 136 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194/revisions" 137 | }, 138 | "parent": { 139 | "href": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194" 140 | } 141 | }, 142 | "url": "https://dev.azure.com/basicprocess/60c8b0ff-04c3-45a8-a4be-69b01cfe6da2/_apis/wit/workItems/194/revisions/2" 143 | } 144 | }, 145 | "resourceVersion": "1.0", 146 | "resourceContainers": { 147 | "collection": { 148 | "id": "5086bf88-dcd7-4e57-9e07-04c5b5baa818", 149 | "baseUrl": "https://dev.azure.com/basicprocess/" 150 | }, 151 | "account": { 152 | "id": "1b3e9b27-3208-4ac4-b4e8-6c4f63b735f0", 153 | "baseUrl": "https://dev.azure.com/basicprocess/" 154 | }, 155 | "project": { 156 | "id": "60c8b0ff-04c3-45a8-a4be-69b01cfe6da2", 157 | "baseUrl": "https://dev.azure.com/basicprocess/" 158 | } 159 | }, 160 | "createdDate": "2019-09-05T15:28:12.4629579Z" 161 | } 162 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | /src/AutoStateTransitions/appsettings.Development.json 332 | -------------------------------------------------------------------------------- /src/AutoStateTransitions/Controllers/ReceiverController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Newtonsoft.Json.Linq; 7 | using Microsoft.VisualStudio.Services.WebApi.Patch.Json; 8 | using Microsoft.VisualStudio.Services.WebApi.Patch; 9 | using Microsoft.TeamFoundation.Common; 10 | using Microsoft.Extensions.Primitives; 11 | using Microsoft.Extensions.Options; 12 | using Microsoft.AspNetCore.Http; 13 | using System.Text; 14 | 15 | using AutoStateTransitions.Models; 16 | using AutoStateTransitions.Repos; 17 | using AutoStateTransitions.ViewModels; 18 | using Microsoft.VisualStudio.Services.Common; 19 | using Microsoft.VisualStudio.Services.WebApi; 20 | using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models; 21 | using AutoStateTransitions.Misc; 22 | using System.Security.Cryptography.X509Certificates; 23 | using AutoStateTransitions.Repos.Interfaces; 24 | 25 | namespace AutoStateTransitions.Controllers 26 | { 27 | [Route("api/receiver")] 28 | [ApiController] 29 | public class ReceiverController : ControllerBase 30 | { 31 | private readonly IWorkItemRepo _workItemRepo; 32 | private readonly IRulesRepo _rulesRepo; 33 | private readonly IOptions _appSettings; 34 | private readonly IHelper _helper; 35 | 36 | public ReceiverController(IWorkItemRepo workItemRepo, IRulesRepo rulesRepo, IHelper helper, IOptions appSettings) 37 | { 38 | _workItemRepo = workItemRepo; 39 | _rulesRepo = rulesRepo; 40 | _appSettings = appSettings; 41 | _helper = helper; 42 | } 43 | 44 | [HttpPost] 45 | [Route("webhook/workitem/update")] 46 | public async Task Post([FromBody] JObject payload) 47 | { 48 | PayloadViewModel vm = BuildPayloadViewModel(payload); 49 | 50 | //make sure pat is not empty, if it is, pull from appsettings 51 | vm.pat = _appSettings.Value.PersonalAccessToken; 52 | 53 | //if the event type is something other the updated, then lets just return an ok 54 | if (vm.eventType != "workitem.updated") return new OkResult(); 55 | 56 | // create our azure devops connection 57 | Uri baseUri = new Uri("https://dev.azure.com/" + vm.organization); 58 | 59 | VssCredentials clientCredentials = new VssCredentials(new VssBasicCredential("username", vm.pat)); 60 | VssConnection vssConnection = new VssConnection(baseUri, clientCredentials); 61 | 62 | // load the work item posted 63 | WorkItem workItem = await _workItemRepo.GetWorkItem(vssConnection, vm.workItemId); 64 | 65 | // this should never happen, but if we can't load the work item from the id, then exit with error 66 | if (workItem == null) return new StandardResponseObjectResult("Error loading workitem '" + vm.workItemId + "'", StatusCodes.Status500InternalServerError); 67 | 68 | // get the related parent 69 | WorkItemRelation parentRelation = workItem.Relations.Where(x => x.Rel.Equals("System.LinkTypes.Hierarchy-Reverse")).FirstOrDefault(); 70 | 71 | // if we don't have any parents to worry about, then just abort 72 | if (parentRelation == null) return new OkResult(); 73 | 74 | Int32 parentId = _helper.GetWorkItemIdFromUrl(parentRelation.Url); 75 | WorkItem parentWorkItem = await _workItemRepo.GetWorkItem(vssConnection, parentId); 76 | 77 | if (parentWorkItem == null) return new StandardResponseObjectResult("Error loading parent work item '" + parentId.ToString() + "'", StatusCodes.Status500InternalServerError); 78 | 79 | string parentState = parentWorkItem.Fields["System.State"] == null ? string.Empty : parentWorkItem.Fields["System.State"].ToString(); 80 | 81 | // load rules for updated work item 82 | RulesModel rulesModel = await _rulesRepo.ListRules(vm.workItemType); 83 | 84 | //loop through each rule 85 | foreach (var rule in rulesModel.Rules) 86 | { 87 | if (rule.IfChildState.Equals(vm.state)) 88 | { 89 | if (!rule.AllChildren) 90 | { 91 | if (!rule.NotParentStates.Contains(parentState)) 92 | { 93 | await _workItemRepo.UpdateWorkItemState(vssConnection, parentWorkItem, rule.SetParentStateTo); 94 | return new OkResult(); 95 | } 96 | } 97 | else 98 | { 99 | // get a list of all the child items to see if they are all closed or not 100 | List childWorkItems = await _workItemRepo.ListChildWorkItemsForParent(vssConnection, parentWorkItem); 101 | 102 | // check to see if any of the child items are not closed, if so, we will get a count > 0 103 | int count = childWorkItems.Where(x => !x.Fields["System.State"].ToString().Equals(rule.IfChildState)).ToList().Count; 104 | 105 | if (count.Equals(0)) 106 | await _workItemRepo.UpdateWorkItemState(vssConnection, parentWorkItem, rule.SetParentStateTo); 107 | 108 | return new OkResult(); 109 | } 110 | 111 | } 112 | } 113 | 114 | return new StandardResponseObjectResult("success", StatusCodes.Status200OK); 115 | } 116 | 117 | private PayloadViewModel BuildPayloadViewModel(JObject body) 118 | { 119 | PayloadViewModel vm = new PayloadViewModel(); 120 | 121 | string url = body["resource"]["url"] == null ? null : body["resource"]["url"].ToString(); 122 | string org = GetOrganization(url); 123 | 124 | vm.workItemId = body["resource"]["workItemId"] == null ? -1 : Convert.ToInt32(body["resource"]["workItemId"].ToString()); 125 | vm.workItemType = body["resource"]["revision"]["fields"]["System.WorkItemType"] == null ? null : body["resource"]["revision"]["fields"]["System.WorkItemType"].ToString(); 126 | vm.eventType = body["eventType"] == null ? null : body["eventType"].ToString(); 127 | vm.rev = body["resource"]["rev"] == null ? -1 : Convert.ToInt32(body["resource"]["rev"].ToString()); 128 | vm.url = body["resource"]["url"] == null ? null : body["resource"]["url"].ToString(); 129 | vm.organization = org; 130 | vm.teamProject = body["resource"]["fields"]["System.AreaPath"] == null ? null : body["resource"]["fields"]["System.AreaPath"].ToString(); 131 | vm.state = body["resource"]["fields"]["System.State"]["newValue"] == null ? null : body["resource"]["fields"]["System.State"]["newValue"].ToString(); 132 | 133 | return vm; 134 | } 135 | 136 | private string GetOrganization(string url) 137 | { 138 | url = url.Replace("http://", string.Empty); 139 | url = url.Replace("https://", string.Empty); 140 | 141 | if (url.Contains(value: "visualstudio.com")) 142 | { 143 | string[] split = url.Split('.'); 144 | return split[0].ToString(); 145 | } 146 | 147 | if (url.Contains("dev.azure.com")) 148 | { 149 | url = url.Replace("dev.azure.com/", string.Empty); 150 | string[] split = url.Split('/'); 151 | return split[0].ToString(); 152 | } 153 | 154 | return string.Empty; 155 | } 156 | } 157 | } 158 | --------------------------------------------------------------------------------