Example #1
0
 public static void Export(ILogger logger, ApplicationTask task, IList <WorkItemConfigurationItemExport> workItemConfigurationItems)
 {
     if (workItemConfigurationItems.Count > 0)
     {
         var step = 0;
         foreach (var workItemConfigurationItem in workItemConfigurationItems)
         {
             task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Exporting {0} from Team Project \"{1}\"", workItemConfigurationItem.Item.DisplayName, workItemConfigurationItem.TeamProject.Name));
             try
             {
                 if (!string.IsNullOrEmpty(workItemConfigurationItem.SaveAsFileName))
                 {
                     Directory.CreateDirectory(Path.GetDirectoryName(workItemConfigurationItem.SaveAsFileName));
                     workItemConfigurationItem.Item.XmlDefinition.Save(workItemConfigurationItem.SaveAsFileName);
                 }
             }
             catch (Exception exc)
             {
                 var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while exporting {0}", workItemConfigurationItem.Item.DisplayName);
                 logger.Log(message, exc);
                 task.SetError(message, exc);
             }
             if (task.IsCanceled)
             {
                 task.Status = "Canceled";
                 break;
             }
         }
     }
 }
Example #2
0
        private void Compare(object argument)
        {
            var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
            var sources          = this.ComparisonSources.ToList();
            var ignoreCase       = this.IgnoreCase;
            var task             = new ApplicationTask("Comparing work item configurations", teamProjectNames.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var step   = 0;
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();

                var results = new List <TeamProjectComparisonResult>();
                foreach (var teamProjectName in teamProjectNames)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                    try
                    {
                        var project = store.Projects[teamProjectName];
                        var target  = WorkItemConfiguration.FromTeamProject(tfs, project);

                        var sourceComparisonResults = new List <WorkItemConfigurationComparisonResult>();
                        foreach (var source in sources)
                        {
                            sourceComparisonResults.Add(WorkItemConfigurationComparer.Compare(this.SelectedTeamProjectCollection.TeamFoundationServer.MajorVersion, source, target, ignoreCase));
                        }
                        results.Add(new TeamProjectComparisonResult(teamProjectName, sourceComparisonResults));
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = results;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while comparing work item configurations", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.ComparisonResults = (ICollection <TeamProjectComparisonResult>)e.Result;
                    task.SetComplete("Done");
                }
            };
            worker.RunWorkerAsync();
        }
Example #3
0
        private async Task GetBuildDefinitions(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving build definitions", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            try
            {
                var tfsVersion  = this.SelectedTeamProjectCollection.TeamFoundationServer.MajorVersion;
                var tfs         = GetSelectedTfsTeamProjectCollection();
                var buildServer = tfs.GetClient <BuildHttpClient>();

                var step             = 0;
                var buildDefinitions = new List <BuildDefinition>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        if (tfsVersion == TfsMajorVersion.TeamServices)
                        {
                            // Use a single API call if available.
                            var projectBuildDefinitions = await buildServer.GetFullDefinitionsAsync(project : teamProject.Name);

                            buildDefinitions.AddRange(projectBuildDefinitions);
                        }
                        else
                        {
                            // Otherwise get the base info first and then individual details.
                            var baseBuildDefinitions = await buildServer.GetDefinitionsAsync(project : teamProject.Name);

                            foreach (var baseBuildDefinition in baseBuildDefinitions)
                            {
                                var buildDefinition = await buildServer.GetDefinitionAsync(teamProject.Guid, baseBuildDefinition.Id);

                                buildDefinitions.Add(buildDefinition);
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                this.BuildDefinitions = buildDefinitions;
                task.SetComplete("Retrieved " + this.BuildDefinitions.Count.ToCountString("build definition"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while retrieving build definitions", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
        private void DeleteSelectedSecurityGroups(object argument)
        {
            var result = MessageBox.Show("This will delete the selected security groups. Are you sure you want to continue?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                var securityGroupsToDelete = this.SelectedSecurityGroups.ToList();
                var task = new ApplicationTask("Deleting security groups", securityGroupsToDelete.Count, true);
                PublishStatus(new StatusEventArgs(task));
                var worker = new BackgroundWorker();
                worker.DoWork += (sender, e) =>
                {
                    var tfs             = GetSelectedTfsTeamProjectCollection();
                    var securityService = tfs.GetService <IIdentityManagementService>();

                    var step  = 0;
                    var count = 0;
                    foreach (var securityGroup in securityGroupsToDelete)
                    {
                        task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Deleting security group \"{0}\" in Team Project \"{1}\"", securityGroup.Name, securityGroup.TeamProject.Name));
                        try
                        {
                            securityService.DeleteApplicationGroup(IdentityHelper.CreateTeamFoundationDescriptor(securityGroup.Sid));
                            count++;
                        }
                        catch (Exception exc)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while deleting security group \"{0}\" in Team Project \"{1}\"", securityGroup.Name, securityGroup.TeamProject.Name), exc);
                        }
                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }

                    e.Result = count;
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Logger.Log("An unexpected exception occurred while deleting security groups", e.Error);
                        task.SetError(e.Error);
                        task.SetComplete("An unexpected exception occurred");
                    }
                    else
                    {
                        var count = (int)e.Result;
                        task.SetComplete("Deleted " + count.ToCountString("security group"));
                    }

                    // Refresh the list.
                    GetSecurityGroups(null);
                };
                worker.RunWorkerAsync();
            }
        }
        private async Task ImportTaskGroups(object argument)
        {
            var result = MessageBox.Show("This will import the selected task groups. Are you sure you want to continue?", "Confirm Import", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            var teamProjects = this.SelectedTeamProjects.ToList();
            var taskGroups   = this.TaskGroupsToImport.ToArray();
            var task         = new ApplicationTask("Importing task groups", teamProjects.Count * taskGroups.Length, true);

            PublishStatus(new StatusEventArgs(task));
            try
            {
                var tfs             = GetSelectedTfsTeamProjectCollection();
                var taskAgentClient = tfs.GetClient <TaskAgentHttpClient>();

                var step = 0;
                foreach (var teamProject in teamProjects)
                {
                    task.Status = "Processing Team Project \"{0}\"".FormatCurrent(teamProject.Name);
                    foreach (var taskGroup in taskGroups)
                    {
                        try
                        {
                            task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Importing task group \"{0}\" into Team Project \"{1}\"", taskGroup.Name, teamProject.Name));
                            await taskAgentClient.AddTaskGroupAsync(teamProject.Guid, taskGroup);
                        }
                        catch (MetaTaskDefinitionExistsException)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "The task group \"{0}\" already exists in Team Project \"{1}\"", taskGroup.Name, teamProject.Name));
                        }
                        catch (Exception exc)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while importing task group \"{0}\" into Team Project \"{1}\"", taskGroup.Name, teamProject.Name), exc);
                        }
                        if (task.IsCanceled)
                        {
                            break;
                        }
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                task.SetComplete("Imported " + taskGroups.Length.ToCountString("task group"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while importing task groups", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
        private void GetWorkItemCategories(object argument)
        {
            var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
            var task             = new ApplicationTask("Retrieving work item categories", teamProjectNames.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var step   = 0;
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();

                var results = new List <WorkItemCategoryInfo>();
                foreach (var teamProjectName in teamProjectNames)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                    try
                    {
                        var project       = store.Projects[teamProjectName];
                        var categoriesXml = WorkItemConfigurationItemImportExport.GetCategoriesXml(project);
                        var categoryList  = WorkItemCategoryList.Load(categoriesXml);
                        foreach (var category in categoryList.Categories)
                        {
                            results.Add(new WorkItemCategoryInfo(teamProjectName, categoryList, category));
                        }
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = results;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving work item categories", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.WorkItemCategories = (ICollection <WorkItemCategoryInfo>)e.Result;
                    task.SetComplete("Retrieved " + this.WorkItemCategories.Count.ToCountString("work item category"));
                }
            };
            worker.RunWorkerAsync();
        }
        private async Task Import(object argument)
        {
            var result = MessageBox.Show("This will import the specified build templates. Are you sure you want to continue?", "Confirm Import", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            var teamProjects   = this.SelectedTeamProjects.ToList();
            var buildTemplates = this.BuildTemplatesToImport.ToArray();
            var task           = new ApplicationTask("Importing build templates", teamProjects.Count * buildTemplates.Length, true);

            PublishStatus(new StatusEventArgs(task));
            try
            {
                var tfs         = GetSelectedTfsTeamProjectCollection();
                var buildServer = tfs.GetClient <BuildHttpClient>();

                var step = 0;
                foreach (var teamProject in teamProjects)
                {
                    task.Status = "Processing Team Project \"{0}\"".FormatCurrent(teamProject.Name);
                    foreach (var buildTemplate in buildTemplates)
                    {
                        try
                        {
                            task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Importing build template \"{0}\" into Team Project \"{1}\"", buildTemplate.Name, teamProject.Name));
                            buildTemplate.Template.Project = new TeamProjectReference {
                                Name = teamProject.Name, Id = teamProject.Guid
                            };
                            await buildServer.SaveTemplateAsync(buildTemplate, teamProject.Name, buildTemplate.Id);
                        }
                        catch (Exception exc)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while importing build template \"{0}\" into Team Project \"{1}\"", buildTemplate.Name, teamProject.Name), exc);
                        }
                        if (task.IsCanceled)
                        {
                            break;
                        }
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                task.SetComplete("Imported " + buildTemplates.Length.ToCountString("build template"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while importing build templates", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
        private void AddOrUpdateSecurityGroup(object argument)
        {
            var result = MessageBox.Show("This will add a new security group to all selected Team Projects, or update the existing group if it already exists. Are you sure you want to continue?", "Confirm Add", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                var teamProjects = this.SelectedTeamProjects.ToList();
                var task         = new ApplicationTask("Adding / updating security groups", teamProjects.Count, true);
                PublishStatus(new StatusEventArgs(task));
                var worker = new BackgroundWorker();
                worker.DoWork += (sender, e) =>
                {
                    var tfs        = GetSelectedTfsTeamProjectCollection();
                    var tfsVersion = this.SelectedTeamProjectCollection.TeamFoundationServer.MajorVersion;

                    var step  = 0;
                    var count = 0;
                    foreach (var teamProject in teamProjects)
                    {
                        task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Adding / updating security group \"{0}\" for Team Project \"{1}\"", this.SecurityGroupChange.Name, teamProject.Name));
                        try
                        {
                            SecurityManager.Apply(task, tfs, tfsVersion, teamProject.Name, this.SecurityGroupChange);
                            count++;
                        }
                        catch (Exception exc)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while adding / updating security group \"{0}\" for Team Project \"{1}\"", this.SecurityGroupChange.Name, teamProject.Name), exc);
                        }
                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }

                    e.Result = count;
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Logger.Log("An unexpected exception occurred while adding / updating security groups", e.Error);
                        task.SetError(e.Error);
                        task.SetComplete("An unexpected exception occurred");
                    }
                    else
                    {
                        var count = (int)e.Result;
                        task.SetComplete("Added / updated " + count.ToCountString("security group"));
                    }
                };
                worker.RunWorkerAsync();
            }
        }
        private void ImportWorkItemCategoryList(object argument)
        {
            var result = MessageBox.Show("This will import the work item category list to all selected Team Projects. Certain applications like Microsoft Test Manager rely on categories so modifying them can reduce their functionality. Are you sure you want to continue?", "Confirm Import", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            var task = new ApplicationTask("Importing work item category list", this.SelectedTeamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var step   = 0;
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs           = GetSelectedTfsTeamProjectCollection();
                var store         = tfs.GetService <WorkItemStore>();
                var categoriesXml = this.SelectedWorkItemCategoryList.Save();
                foreach (var teamProject in this.SelectedTeamProjects)
                {
                    try
                    {
                        task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Importing work item category list in Team Project \"{0}\"", teamProject.Name));
                        var project = store.Projects[teamProject.Name];
                        WorkItemConfigurationItemImportExport.SetCategories(project, categoriesXml);
                    }
                    catch (Exception exc)
                    {
                        task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while importing the work item category list for Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while importing the work item category list", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete(task.IsError ? "Failed" : (task.IsWarning ? "Succeeded with warnings" : "Succeeded"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void GetBuildDefinitions(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving build definitions", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs         = GetSelectedTfsTeamProjectCollection();
                var buildServer = tfs.GetService <IBuildServer>();

                var step             = 0;
                var buildDefinitions = new List <BuildDefinitionInfo>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        foreach (var buildDefinition in buildServer.QueryBuildDefinitions(teamProject.Name, QueryOptions.All))
                        {
                            buildDefinitions.Add(new BuildDefinitionInfo(teamProject.Name, buildDefinition));
                        }
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }

                e.Result = buildDefinitions;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving build definitions", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.BuildDefinitions = (ICollection <BuildDefinitionInfo>)e.Result;
                    task.SetComplete("Retrieved " + this.BuildDefinitions.Count.ToCountString("build definition"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void UpdateSourceControlSettings(object argument)
        {
            var result = MessageBox.Show("This will update the source control settings in all selected Team Projects. Are you sure you want to continue?", "Confirm Update", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
                var settings         = this.SelectedSourceControlSettings;
                var task             = new ApplicationTask("Updating source control settings", teamProjectNames.Count, true);
                this.PublishStatus(new StatusEventArgs(task));
                var worker = new BackgroundWorker();
                worker.DoWork += (sender, e) =>
                {
                    var step = 0;
                    var tfs  = GetSelectedTfsTeamProjectCollection();
                    var vcs  = tfs.GetService <VersionControlServer>();
                    foreach (var teamProjectName in teamProjectNames)
                    {
                        task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                        try
                        {
                            var project = vcs.GetTeamProject(teamProjectName);
                            project.ExclusiveCheckout   = !settings.EnableMultipleCheckout;
                            project.GetLatestOnCheckout = settings.EnableGetLatestOnCheckout;
                            var checkinNoteFields = settings.CheckinNoteFields.Select(f => new CheckinNoteFieldDefinition(f.Name, f.Required, f.DisplayOrder)).ToArray();
                            project.SetCheckinNoteFields(checkinNoteFields);
                        }
                        catch (Exception exc)
                        {
                            task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                        }
                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Logger.Log("An unexpected exception occurred while updating source control settings", e.Error);
                        task.SetError(e.Error);
                        task.SetComplete("An unexpected exception occurred");
                    }
                    else
                    {
                        task.SetComplete("Done");
                    }
                };
                worker.RunWorkerAsync();
            }
        }
Example #12
0
        private async Task DeleteSelectedServiceEndpoints(object argument)
        {
            var result = MessageBox.Show("This will delete the selected service endpoints. Are you sure you want to continue?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            var serviceEndpointsToDelete = this.SelectedServiceEndpoints;
            var task = new ApplicationTask("Deleting service endpoints", serviceEndpointsToDelete.Count, true);

            PublishStatus(new StatusEventArgs(task));
            try
            {
                var tfs             = GetSelectedTfsTeamProjectCollection();
                var taskAgentClient = tfs.GetClient <TaskAgentHttpClient>();

                var step  = 0;
                var count = 0;
                foreach (var serviceEndpointToDelete in serviceEndpointsToDelete)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Deleting service endpoint \"{0}\" in Team Project \"{1}\"", serviceEndpointToDelete.ServiceEndpoint.Name, serviceEndpointToDelete.TeamProject.Name));
                    try
                    {
                        // Delete the service endpoints one by one to avoid one failure preventing the other ones from being deleted.
                        await taskAgentClient.DeleteServiceEndpointAsync(serviceEndpointToDelete.TeamProject.Guid, serviceEndpointToDelete.ServiceEndpoint.Id);

                        count++;
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while deleting service endpoints \"{0}\" in Team Project \"{1}\"", serviceEndpointToDelete.ServiceEndpoint.Name, serviceEndpointToDelete.TeamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                task.SetComplete("Deleted " + count.ToCountString("service endpoint"));

                // Refresh the list.
                await GetServiceEndpoints(null);
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while deleting service endpoints", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
        private void GetSourceControlSettings(object argument)
        {
            var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
            var task             = new ApplicationTask("Retrieving source control settings", teamProjectNames.Count, true);

            this.PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var settings = new ObservableCollection <SourceControlSettings>();
                var step     = 0;
                var tfs      = GetSelectedTfsTeamProjectCollection();
                var vcs      = tfs.GetService <VersionControlServer>();
                foreach (var teamProjectName in teamProjectNames)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                    try
                    {
                        var projectSettings = GetSourceControlSettings(vcs, teamProjectName);
                        settings.Add(projectSettings);
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = settings;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving source control settings", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.SourceControlSettings = (ObservableCollection <SourceControlSettings>)e.Result;
                    task.SetComplete("Done");
                }
            };
            worker.RunWorkerAsync();
        }
Example #14
0
        private async Task AddServiceEndpoint(object argument)
        {
            var result = MessageBox.Show("This will add the service endpoint to all selected Team Projects. Are you sure you want to continue?", "Confirm Service Endpoint", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Adding service endpoint", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            try
            {
                var tfs             = GetSelectedTfsTeamProjectCollection();
                var taskAgentClient = tfs.GetClient <TaskAgentHttpClient>();
                var serviceEndpoint = this.GenericServiceEndpoint.ToServiceEndpoint();

                var step  = 0;
                var count = 0;
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        await taskAgentClient.CreateServiceEndpointAsync(teamProject.Guid, serviceEndpoint);

                        count++;
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                task.SetComplete("Added service endpoint to " + count.ToCountString("Team Project"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while adding service endpoint", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
Example #15
0
        private async Task GetBuildDefinitions(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving build definitions", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));

            try
            {
                var tfs         = GetSelectedTfsTeamProjectCollection();
                var buildServer = tfs.GetClient <BuildHttpClient>();

                var step             = 0;
                var buildDefinitions = new List <BuildDefinition>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        var projectBuildDefinitions = await buildServer.GetFullDefinitionsAsync(project : teamProject.Name);//.ConfigureAwait(false);

                        buildDefinitions.AddRange(projectBuildDefinitions);
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                this.BuildDefinitions = buildDefinitions;
                task.SetComplete("Retrieved " + this.BuildDefinitions.Count.ToCountString("build definition"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while retrieving build definitions", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
Example #16
0
        private async Task GetServiceEndpoints(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving service endpoints", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            try
            {
                var tfs             = GetSelectedTfsTeamProjectCollection();
                var taskAgentClient = tfs.GetClient <TaskAgentHttpClient>();

                var step             = 0;
                var serviceEndpoints = new List <ServiceEndpointInfo>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        var projectServiceEndpoints = await taskAgentClient.GetServiceEndpointsAsync(project : teamProject.Name);

                        serviceEndpoints.AddRange(projectServiceEndpoints.Select(p => new ServiceEndpointInfo(teamProject, p)));
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                this.ServiceEndpoints = serviceEndpoints;
                task.SetComplete("Retrieved " + this.ServiceEndpoints.Count.ToCountString("service endpoint"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while retrieving service endpoints", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
        private static void DeleteBuildsForDefinition(ApplicationTask task, IBuildServer buildServer, int step, BuildDefinitionInfo buildDefinition)
        {
            var buildDetailSpec = buildServer.CreateBuildDetailSpec(new[] { buildDefinition.Uri, });
            var buildsToDelete  = buildServer.QueryBuilds(buildDetailSpec).Builds;

            if (buildsToDelete.Any())
            {
                task.SetProgress(step, string.Format(CultureInfo.CurrentCulture, "Deleting {0} builds for definition \"{1}\" in Team Project \"{2}\"", buildsToDelete.Count(), buildDefinition.Name, buildDefinition.TeamProject));
                foreach (var buildToDelete in buildsToDelete)
                {
                    try
                    {
                        buildToDelete.Delete(DeleteOptions.All);
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while deleting build number \"{0}\" for definition \"{1}\" in Team Project \"{2}\"", buildToDelete.BuildNumber, buildDefinition.Name, buildDefinition.TeamProject), exc);
                    }
                }
            }
        }
Example #18
0
        public static void UnregisterBuildProcessTemplates(ApplicationTask task, IEnumerable <IProcessTemplate> buildProcessTemplates)
        {
            var step = 0;

            foreach (var buildProcessTemplate in buildProcessTemplates)
            {
                try
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Unregistering build process template \"{0}\"", buildProcessTemplate.ServerPath));
                    buildProcessTemplate.Delete();
                }
                catch (Exception exc)
                {
                    task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while unregistering the build process template \"{0}\" for Team Project \"{1}\"", buildProcessTemplate.ServerPath, buildProcessTemplate.TeamProject), exc);
                }
                if (task.IsCanceled)
                {
                    task.Status = "Canceled";
                    break;
                }
            }
        }
Example #19
0
        public static IList <BuildProcessTemplateInfo> GetBuildProcessTemplates(ApplicationTask task, IBuildServer buildServer, IEnumerable <string> teamProjectNames)
        {
            var processTemplates = new List <BuildProcessTemplateInfo>();
            var step             = 0;

            foreach (var teamProjectName in teamProjectNames)
            {
                task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                try
                {
                    var teamProjectBuildDefinitions = buildServer.QueryBuildDefinitions(teamProjectName, QueryOptions.Process);

                    foreach (var processTemplate in buildServer.QueryProcessTemplates(teamProjectName))
                    {
                        var processTemplateBuildDefinitions = new List <IBuildDefinition>();
                        foreach (var teamProjectBuildDefinition in teamProjectBuildDefinitions)
                        {
                            if (teamProjectBuildDefinition.Process != null && BuildProcessTemplateInfo.AreEquivalent(teamProjectBuildDefinition.Process, processTemplate))
                            {
                                processTemplateBuildDefinitions.Add(teamProjectBuildDefinition);
                            }
                        }
                        processTemplates.Add(new BuildProcessTemplateInfo(processTemplate, processTemplateBuildDefinitions));
                    }
                }
                catch (Exception exc)
                {
                    task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                }
                if (task.IsCanceled)
                {
                    task.Status = "Canceled";
                    break;
                }
            }
            return(processTemplates);
        }
        private void PerformImport(Dictionary <string, List <WorkItemQueryInfo> > teamProjectsWithQueries)
        {
            var numberOfSteps = teamProjectsWithQueries.Aggregate(0, (a, p) => a += p.Value.Count);
            var task          = new ApplicationTask("Importing work item queries", numberOfSteps, true);

            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();

                var step = 0;
                foreach (var teamProjectWithQueries in teamProjectsWithQueries)
                {
                    var teamProject = teamProjectWithQueries.Key;
                    var queries     = teamProjectWithQueries.Value;
                    var project     = store.Projects[teamProject];

                    foreach (var query in queries)
                    {
                        task.SetProgress(step++, "Importing work item query \"{0}\" for Team Project \"{1}\"".FormatCurrent(query.Name, teamProject));

                        ImportQuery(query, project.QueryHierarchy);

                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }

                    if (!task.IsCanceled)
                    {
                        try
                        {
                            project.QueryHierarchy.Save();
                        }
                        catch (Exception exc)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while saving changes to \"{0}\"", teamProject);
                            this.Logger.Log(message, exc);
                            task.SetError(message, exc);
                        }
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while importing work item queries", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete(task.IsError ? "Failed" : (task.IsWarning ? "Succeeded with warnings" : "Succeeded"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void DeleteSelectedWorkItemQueries(object argument)
        {
            var result = MessageBox.Show("This will delete the selected work item queries. Are you sure you want to continue?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result != MessageBoxResult.Yes)
            {
                return;
            }

            var workItemQueries = this.SelectedWorkItemQueries.ToList();
            var task            = new ApplicationTask("Deleting " + workItemQueries.Count.ToCountString("work item query"), workItemQueries.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();
                var step  = 0;
                var queryHierarchiesToSave = new List <QueryHierarchy>();
                foreach (var workItemQuery in workItemQueries)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Deleting \"{0}\" from Team Project \"{1}\"", workItemQuery.Name, workItemQuery.TeamProject));
                    try
                    {
                        var project    = store.Projects[workItemQuery.TeamProject];
                        var rootFolder = project.QueryHierarchy;
                        if (!queryHierarchiesToSave.Contains(rootFolder))
                        {
                            queryHierarchiesToSave.Add(rootFolder);
                        }
                        var query = rootFolder.Find(workItemQuery.Id);
                        if (query == null)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, "The work item query \"{0}\" could not be found", workItemQuery.Name);
                            this.Logger.Log(message, TraceEventType.Warning);
                            task.SetWarning(message);
                        }
                        else
                        {
                            query.Delete();
                        }
                    }
                    catch (Exception exc)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while deleting \"{0}\"", workItemQuery.Name);
                        this.Logger.Log(message, exc);
                        task.SetError(message, exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                foreach (var queryHierarchyToSave in queryHierarchiesToSave)
                {
                    if (!task.IsCanceled)
                    {
                        try
                        {
                            queryHierarchyToSave.Save();
                        }
                        catch (Exception exc)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while saving changes to \"{0}\"", queryHierarchyToSave.Project.Name);
                            this.Logger.Log(message, exc);
                            task.SetError(message, exc);
                        }
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while deleting work item queries", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete("Deleted " + workItemQueries.Count.ToCountString("work item query"));
                }

                // Refresh the list.
                GetWorkItemQueries(null);
            };
            worker.RunWorkerAsync();
        }
        private void ExportSelectedWorkItemQueries(object argument)
        {
            var workItemQueriesToExport = new List <WorkItemQueryExport>();
            var workItemQueries         = this.SelectedWorkItemQueries;

            if (workItemQueries.Count == 1)
            {
                // Export to single file.
                var workItemQuery = workItemQueries.Single();
                var dialog        = new SaveFileDialog();
                dialog.FileName = workItemQuery.Name + ".wiq";
                dialog.Filter   = "Work Item Query Files (*.wiq)|*.wiq";
                var result = dialog.ShowDialog(Application.Current.MainWindow);
                if (result == true)
                {
                    workItemQueriesToExport.Add(new WorkItemQueryExport(workItemQuery, dialog.FileName));
                }
            }
            else
            {
                // Export to a directory structure.
                var dialog = new System.Windows.Forms.FolderBrowserDialog();
                dialog.Description = "Please select the path where to export the Work Item Query files (*.wiq). They will be stored in a folder per Team Project.";
                var result = dialog.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    var rootFolder = dialog.SelectedPath;
                    foreach (var workItemQuery in workItemQueries)
                    {
                        var fileName = Path.Combine(rootFolder, workItemQuery.TeamProject, workItemQuery.Path, workItemQuery.Name + ".wiq");
                        workItemQueriesToExport.Add(new WorkItemQueryExport(workItemQuery, fileName));
                    }
                }
            }

            var task = new ApplicationTask("Exporting " + workItemQueriesToExport.Count.ToCountString("work item query"), workItemQueriesToExport.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var step = 0;
                foreach (var workItemQueryToExport in workItemQueriesToExport)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Exporting \"{0}\" from Team Project \"{1}\"", workItemQueryToExport.Query.Name, workItemQueryToExport.Query.TeamProject));
                    try
                    {
                        if (!string.IsNullOrEmpty(workItemQueryToExport.SaveAsFileName))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(workItemQueryToExport.SaveAsFileName));
                            workItemQueryToExport.WrapInXmlDocument().Save(workItemQueryToExport.SaveAsFileName);
                        }
                    }
                    catch (Exception exc)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while exporting \"{0}\"", workItemQueryToExport.Query.Name);
                        this.Logger.Log(message, exc);
                        task.SetError(message, exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while exporting work item queries", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete("Exported " + workItemQueriesToExport.Count.ToCountString("work item query"));
                }
            };
            worker.RunWorkerAsync();
        }
Example #23
0
        public static void Import(ILogger logger, ApplicationTask task, bool setTaskProgress, WorkItemStore store, Dictionary <TeamProjectInfo, List <WorkItemConfigurationItem> > teamProjectsWithConfigurationItems, ImportOptions options)
        {
            // Replace any macros.
            if (!task.IsCanceled)
            {
                foreach (var teamProject in teamProjectsWithConfigurationItems.Keys.ToArray())
                {
                    var transformedList = new List <WorkItemConfigurationItem>();
                    foreach (var workItemConfigurationItem in teamProjectsWithConfigurationItems[teamProject])
                    {
                        // Clone the item so that any callers aren't affected by a changed XML definitions.
                        var clone = workItemConfigurationItem.Clone();
                        ReplaceTeamProjectMacros(clone.XmlDefinition, teamProject);
                        transformedList.Add(clone);
                    }
                    teamProjectsWithConfigurationItems[teamProject] = transformedList;
                }
            }

            // Save a temporary copy for troubleshooting if requested.
            if (!task.IsCanceled && options.HasFlag(ImportOptions.SaveCopy))
            {
                foreach (var teamProjectWithConfigurationItems in teamProjectsWithConfigurationItems)
                {
                    var teamProject = teamProjectWithConfigurationItems.Key;
                    foreach (var workItemConfigurationItem in teamProjectWithConfigurationItems.Value)
                    {
                        var directoryName = Path.Combine(Path.GetTempPath(), Constants.ApplicationName, teamProject.Name);
                        Directory.CreateDirectory(directoryName);
                        var fileName = Path.Combine(directoryName, workItemConfigurationItem.Name + ".xml");
                        using (var writer = XmlWriter.Create(fileName, new XmlWriterSettings {
                            Indent = true
                        }))
                        {
                            workItemConfigurationItem.XmlDefinition.WriteTo(writer);
                        }
                        var message = "{0} for Team Project \"{1}\" was saved to \"{2}\"".FormatCurrent(workItemConfigurationItem.DisplayName, teamProject.Name, fileName);
                        logger.Log(message, TraceEventType.Verbose);
                        task.Status = message;
                    }
                }
            }

            var step = 0;

            foreach (var teamProjectWithConfigurationItems in teamProjectsWithConfigurationItems)
            {
                var teamProject        = teamProjectWithConfigurationItems.Key;
                var configurationItems = teamProjectWithConfigurationItems.Value;
                var project            = store.Projects[teamProjectWithConfigurationItems.Key.Name];

                // First apply all work item types in batch.
                var workItemTypes = configurationItems.Where(t => t.Type == WorkItemConfigurationItemType.WorkItemType).Cast <WorkItemTypeDefinition>().ToList();
                if (workItemTypes.Any())
                {
                    var teamProjectsWithWorkItemTypes = new Dictionary <TeamProjectInfo, List <WorkItemTypeDefinition> >()
                    {
                        { teamProject, workItemTypes }
                    };
                    ImportWorkItemTypes(logger, task, setTaskProgress, ref step, options, store, teamProjectsWithWorkItemTypes);
                }

                // Then apply the other configuration items.
                foreach (var configurationItem in configurationItems.Where(w => w.Type != WorkItemConfigurationItemType.WorkItemType))
                {
                    if (options.HasFlag(ImportOptions.Simulate))
                    {
                        var status = "Simulating import of {0} in Team Project \"{1}\"".FormatCurrent(configurationItem.DisplayName, teamProject.Name);
                        if (setTaskProgress)
                        {
                            task.SetProgress(step++, status);
                        }
                        else
                        {
                            task.Status = status;
                        }
                    }
                    else
                    {
                        var status = "Importing {0} in Team Project \"{1}\"".FormatCurrent(configurationItem.DisplayName, teamProject.Name);
                        if (setTaskProgress)
                        {
                            task.SetProgress(step++, status);
                        }
                        else
                        {
                            task.Status = status;
                        }
                        try
                        {
                            switch (configurationItem.Type)
                            {
                            case WorkItemConfigurationItemType.Categories:
                                SetCategories(project, configurationItem);
                                break;

                            case WorkItemConfigurationItemType.CommonConfiguration:
                                SetCommonConfiguration(project, configurationItem);
                                break;

                            case WorkItemConfigurationItemType.AgileConfiguration:
                                SetAgileConfiguration(project, configurationItem);
                                break;

                            case WorkItemConfigurationItemType.ProcessConfiguration:
                                SetProcessConfiguration(project, configurationItem);
                                break;

                            default:
                                throw new ArgumentException("The Work Item Configuration Item Type is unknown: " + configurationItem.Type.ToString());
                            }
                        }
                        catch (Exception exc)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while importing {0} in Team Project \"{1}\"", configurationItem.DisplayName, teamProjectWithConfigurationItems.Key.Name);
                            logger.Log(message, exc);
                            task.SetError(message, exc);
                        }
                    }
                }
                if (task.IsCanceled)
                {
                    task.Status = "Canceled";
                    break;
                }
            }
        }
        private void GetSecurityGroups(object argument)
        {
            var teamProjects   = this.SelectedTeamProjects.ToList();
            var membershipMode = this.MembershipMode;
            var task           = new ApplicationTask("Retrieving security groups", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs = GetSelectedTfsTeamProjectCollection();
                var ims = tfs.GetService <IIdentityManagementService>();

                var step           = 0;
                var securityGroups = new List <SecurityGroupInfo>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        foreach (var applicationGroup in ims.ListApplicationGroups(teamProject.Uri.ToString(), ReadIdentityOptions.None).Where(g => g.IsActive).OrderBy(g => g.DisplayName))
                        {
                            var members = new List <string>();
                            if (membershipMode != MembershipQuery.None)
                            {
                                var applicationGroupWithMembers = ims.ReadIdentity(applicationGroup.Descriptor, membershipMode, ReadIdentityOptions.None);
                                if (applicationGroupWithMembers.Members != null && applicationGroupWithMembers.Members.Any())
                                {
                                    members.AddRange(ims.ReadIdentities(applicationGroupWithMembers.Members, membershipMode, ReadIdentityOptions.None).Where(m => m != null).Select(m => m.DisplayName));
                                }
                            }
                            var description   = applicationGroup.GetAttribute("Description", null);
                            var securityGroup = new SecurityGroupInfo(teamProject, applicationGroup.Descriptor.Identifier, applicationGroup.DisplayName, description, members);
                            securityGroups.Add(securityGroup);
                            if (task.IsCanceled)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }

                e.Result = securityGroups;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving security groups", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.SecurityGroups = (ICollection <SecurityGroupInfo>)e.Result;
                    task.SetComplete("Retrieved " + this.SecurityGroups.Count().ToCountString("security group"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void GetProcessConfigurations(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving process configurations", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var step   = 0;
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();

                var results = new List <WorkItemConfigurationItemExport>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        var project = store.Projects[teamProject.Name];
                        if (this.SelectedTeamProjectCollection.TeamFoundationServer.MajorVersion >= TfsMajorVersion.V12)
                        {
                            var processConfiguration = WorkItemConfigurationItemImportExport.GetProcessConfiguration(project);
                            if (processConfiguration != null)
                            {
                                results.Add(new WorkItemConfigurationItemExport(teamProject, processConfiguration));
                            }
                        }
                        else
                        {
                            var commonConfiguration = WorkItemConfigurationItemImportExport.GetCommonConfiguration(project);
                            if (commonConfiguration != null)
                            {
                                results.Add(new WorkItemConfigurationItemExport(teamProject, commonConfiguration));
                            }
                            var agileConfiguration = WorkItemConfigurationItemImportExport.GetAgileConfiguration(project);
                            if (agileConfiguration != null)
                            {
                                results.Add(new WorkItemConfigurationItemExport(teamProject, agileConfiguration));
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = results;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving process configurations", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.ProcessConfigurations = (ICollection <WorkItemConfigurationItemExport>)e.Result;
                    task.SetComplete("Retrieved " + this.ProcessConfigurations.Count.ToCountString("process configuration"));
                }
            };
            worker.RunWorkerAsync();
        }
Example #26
0
        private static void ImportWorkItemTypes(ILogger logger, ApplicationTask task, bool setTaskProgress, ref int step, ImportOptions options, WorkItemStore store, Dictionary <TeamProjectInfo, List <WorkItemTypeDefinition> > teamProjectsWithWorkItemTypes)
        {
            var importValidationFailed            = false;
            ImportEventHandler importEventHandler = (sender, e) =>
            {
                if (e.Severity == ImportSeverity.Error)
                {
                    importValidationFailed = true;
                    var message = e.Message;
                    var schemaValidationException = e.Exception as XmlSchemaValidationException;
                    if (schemaValidationException != null)
                    {
                        message = string.Format("XML validation error at row {0}, column {1}: {2}", schemaValidationException.LineNumber, schemaValidationException.LinePosition, message);
                    }
                    task.SetError(message);
                }
                else if (e.Severity == ImportSeverity.Warning)
                {
                    task.SetWarning(e.Message);
                }
            };

            // Validate.
            if (!task.IsCanceled)
            {
                WorkItemType.ValidationEventHandler += importEventHandler;
                try
                {
                    foreach (var teamProjectWithWorkItemTypes in teamProjectsWithWorkItemTypes)
                    {
                        var teamProject = teamProjectWithWorkItemTypes.Key;
                        var project     = store.Projects[teamProject.Name];
                        foreach (var workItemTypeFile in teamProjectWithWorkItemTypes.Value)
                        {
                            task.Status = string.Format("Validating {0} for Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                            try
                            {
                                WorkItemType.Validate(project, workItemTypeFile.XmlDefinition.OuterXml);
                            }
                            catch (Exception exc)
                            {
                                var message = string.Format("An error occurred while validating {0} for Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                logger.Log(message, exc);
                                task.SetError(message, exc);
                            }
                            if (task.IsCanceled)
                            {
                                break;
                            }
                        }
                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }
                }
                finally
                {
                    WorkItemType.ValidationEventHandler -= importEventHandler;
                }
            }

            // Import.
            if (!task.IsCanceled && !importValidationFailed)
            {
                foreach (var teamProjectWithWorkItemTypes in teamProjectsWithWorkItemTypes)
                {
                    var teamProject = teamProjectWithWorkItemTypes.Key;
                    var project     = store.Projects[teamProject.Name];
                    project.WorkItemTypes.ImportEventHandler += importEventHandler;
                    try
                    {
                        foreach (var workItemTypeFile in teamProjectWithWorkItemTypes.Value)
                        {
                            if (options.HasFlag(ImportOptions.Simulate))
                            {
                                var status = string.Format("Simulating import of {0} in Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                if (setTaskProgress)
                                {
                                    task.SetProgress(step++, status);
                                }
                                else
                                {
                                    task.Status = status;
                                }
                            }
                            else
                            {
                                var status = string.Format("Importing {0} in Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                if (setTaskProgress)
                                {
                                    task.SetProgress(step++, status);
                                }
                                else
                                {
                                    task.Status = status;
                                }
                                try
                                {
                                    project.WorkItemTypes.Import(workItemTypeFile.XmlDefinition.DocumentElement);
                                }
                                catch (Exception exc)
                                {
                                    var message = string.Format("An error occurred while importing {0} in Team Project \"{1}\"", workItemTypeFile.DisplayName, teamProject.Name);
                                    logger.Log(message, exc);
                                    task.SetError(message, exc);
                                }
                            }
                            if (task.IsCanceled)
                            {
                                break;
                            }
                        }
                    }
                    finally
                    {
                        project.WorkItemTypes.ImportEventHandler -= importEventHandler;
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            }
        }
Example #27
0
        private void GetActivity(object argument)
        {
            var componentTypes     = GetComponentTypes();
            var numberOfActivities = this.NumberOfActivities;
            var commentExclusions  = (string.IsNullOrEmpty(this.SourceControlCommentExclusions) ? new string[0] : this.SourceControlCommentExclusions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            var userExclusions     = (string.IsNullOrEmpty(this.UserExclusions) ? new string[0] : this.UserExclusions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));

            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving activity", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs         = GetSelectedTfsTeamProjectCollection();
                var buildServer = tfs.GetService <IBuildServer>();
                var wit         = tfs.GetService <WorkItemStore>();
                var vcs         = tfs.GetService <VersionControlServer>();

                var step     = 0;
                var activity = new List <TeamProjectActivityInfo>();
                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        var sourceControlActivities = new List <ComponentActivityInfo>();
                        if (!task.IsCanceled && componentTypes.HasFlag(ActivityComponentTypes.SourceControl))
                        {
                            // Get the latest source control activity.
                            var         foundChangesetsForProject = 0;
                            VersionSpec versionTo = null;
                            while (foundChangesetsForProject < numberOfActivities && !task.IsCanceled)
                            {
                                const int pageCount = 10;
                                var       history   = vcs.QueryHistory("$/" + teamProject.Name, VersionSpec.Latest, 0, RecursionType.Full, null, null, versionTo, pageCount, false, false, false).Cast <Changeset>().ToList();
                                foreach (Changeset changeset in history)
                                {
                                    if ((string.IsNullOrEmpty(changeset.Comment) || !commentExclusions.Any(x => changeset.Comment.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0)) && !userExclusions.Any(x => changeset.Owner.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0 || changeset.OwnerDisplayName.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
                                    {
                                        foundChangesetsForProject++;
                                        var commentSuffix = string.IsNullOrEmpty(changeset.Comment) ? null : ": " + changeset.Comment.Trim();
                                        sourceControlActivities.Add(new ComponentActivityInfo("Source Control", changeset.CreationDate, changeset.CommitterDisplayName, string.Format(CultureInfo.CurrentCulture, "Changeset {0}{1}", changeset.ChangesetId, commentSuffix)));
                                        if (foundChangesetsForProject == numberOfActivities)
                                        {
                                            break;
                                        }
                                    }
                                }
                                if (history.Count == pageCount)
                                {
                                    versionTo = new ChangesetVersionSpec(history.Last().ChangesetId - 1);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        // Get the latest work item tracking activity.
                        IEnumerable <ComponentActivityInfo> workItemActivities = null;
                        if (!task.IsCanceled && componentTypes.HasFlag(ActivityComponentTypes.WorkItemTracking))
                        {
                            var parameters = new Dictionary <string, object>()
                            {
                                { "TeamProject", teamProject.Name }
                            };
                            var queryBuilder = new StringBuilder();
                            queryBuilder.Append("SELECT [System.Id], [System.ChangedDate], [System.Title] FROM WorkItems WHERE [System.TeamProject] = @TeamProject");
                            for (var userExclusionIndex = 0; userExclusionIndex < userExclusions.Length; userExclusionIndex++)
                            {
                                var userParameterName = "User" + userExclusionIndex;
                                queryBuilder.AppendFormat(" AND [System.ChangedBy] NOT CONTAINS @{0}", userParameterName);
                                parameters.Add(userParameterName, userExclusions[userExclusionIndex]);
                            }
                            queryBuilder.Append(" ORDER BY [System.ChangedDate] DESC");
                            var workItemsQuery = wit.Query(queryBuilder.ToString(), parameters);
                            var workItems      = workItemsQuery.Cast <WorkItem>().Take(numberOfActivities).ToList();
                            workItemActivities = workItems.Select(w => new ComponentActivityInfo("Work Item Tracking", w.ChangedDate, w.ChangedBy, string.Format(CultureInfo.CurrentCulture, "{0} {1}: {2}", w.Type.Name, w.Id, w.Title))).ToList();
                        }

                        // Get the latest builds.
                        var teamBuildActivities = new List <ComponentActivityInfo>();
                        if (!task.IsCanceled && componentTypes.HasFlag(ActivityComponentTypes.TeamBuild))
                        {
                            // Retrieve at least 2 builds to get the "manual paging" system working.
                            var          pageSize           = Math.Max(2, numberOfActivities);
                            IBuildDetail lastRetrievedBuild = null;
                            while (true)
                            {
                                var spec = buildServer.CreateBuildDetailSpec(teamProject.Name);
                                spec.QueryOptions           = QueryOptions.Definitions | QueryOptions.BatchedRequests;
                                spec.QueryOrder             = BuildQueryOrder.StartTimeDescending;
                                spec.MaxBuildsPerDefinition = pageSize;
                                spec.QueryDeletedOption     = QueryDeletedOption.IncludeDeleted;
                                if (lastRetrievedBuild != null)
                                {
                                    // There is no paging API for build queries, so we page the results manually by
                                    // limiting on the max finish time as being the finish time of the last returned result.
                                    // This will yield an overlap of 1 build per page which we can filter out.
                                    spec.MaxFinishTime = lastRetrievedBuild.FinishTime;
                                }
                                var pagedBuilds = buildServer.QueryBuilds(spec).Builds.Where(b => lastRetrievedBuild == null || b.Uri != lastRetrievedBuild.Uri).ToArray();
                                lastRetrievedBuild = pagedBuilds.LastOrDefault();
                                teamBuildActivities.AddRange(pagedBuilds.Where(b => string.IsNullOrEmpty(b.RequestedFor) || !userExclusions.Any(x => b.RequestedFor.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0)).OrderByDescending(b => b.StartTime).Take(numberOfActivities).Select(b => new ComponentActivityInfo("Team Build", b.StartTime, b.RequestedFor, string.Format(CultureInfo.CurrentCulture, "Build Number \"{0}\" from Build Definition \"{1}\"", b.BuildNumber, b.BuildDefinition.Name))));
                                if (!pagedBuilds.Any() || teamBuildActivities.Count >= numberOfActivities)
                                {
                                    break;
                                }
                            }
                        }

                        // Assemble the complete activity details.
                        activity.Add(new TeamProjectActivityInfo(teamProject.Name, numberOfActivities, sourceControlActivities, workItemActivities, teamBuildActivities));
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }

                e.Result = activity;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving activity", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.Activities = (ICollection <TeamProjectActivityInfo>)e.Result;
                    task.SetComplete("Retrieved " + this.Activities.Count.ToCountString("activity result"));
                }
            };
            worker.RunWorkerAsync();
        }
Example #28
0
        private async Task GetActivity(object argument)
        {
            var componentTypes     = GetComponentTypes();
            var numberOfActivities = this.NumberOfActivities;
            var commentExclusions  = (string.IsNullOrEmpty(this.SourceControlCommentExclusions) ? new string[0] : this.SourceControlCommentExclusions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            var userExclusions     = (string.IsNullOrEmpty(this.UserExclusions) ? new string[0] : this.UserExclusions.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
            var teamProjects       = this.SelectedTeamProjects.ToList();
            var steps = teamProjects.Count * componentTypes.Count;
            var task  = new ApplicationTask("Retrieving activity", steps, true);

            PublishStatus(new StatusEventArgs(task));
            try
            {
                var tfs        = GetSelectedTfsTeamProjectCollection();
                var step       = 0;
                var activities = new List <TeamProjectActivityInfo>();
                foreach (var teamProject in teamProjects)
                {
                    task.Status = string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name);
                    var componentActivities = new List <ComponentActivityInfo>();
                    try
                    {
                        if (!task.IsCanceled && componentTypes.Any(c => c == ActivityComponentType.Tfvc))
                        {
                            task.SetProgress(step++, "Retrieving TFVC activity");
                            componentActivities.AddRange(await GetTfvcActivityAsync(task, tfs, teamProject, numberOfActivities, userExclusions, commentExclusions));
                        }
                        if (!task.IsCanceled && componentTypes.Any(c => c == ActivityComponentType.Git))
                        {
                            task.SetProgress(step++, "Retrieving Git activity");
                            componentActivities.AddRange(await GetGitActivityAsync(task, tfs, teamProject, numberOfActivities, userExclusions, commentExclusions));
                        }
                        if (!task.IsCanceled && componentTypes.Any(c => c == ActivityComponentType.WorkItemTracking))
                        {
                            task.SetProgress(step++, "Retrieving Work Item Tracking activity");
                            componentActivities.AddRange(await GetWorkItemTrackingActivityAsync(task, tfs, teamProject, numberOfActivities, userExclusions));
                        }
                        if (!task.IsCanceled && componentTypes.Any(c => c == ActivityComponentType.Build))
                        {
                            task.SetProgress(step++, "Retrieving Build activity");
                            componentActivities.AddRange(await GetBuildActivityAsync(task, tfs, teamProject, numberOfActivities, userExclusions));
                        }
                        if (!task.IsCanceled && componentTypes.Any(c => c == ActivityComponentType.XamlBuild))
                        {
                            task.SetProgress(step++, "Retrieving XAML Build activity");
                            componentActivities.AddRange(await GetXamlBuildActivityAsync(task, tfs, teamProject, numberOfActivities, userExclusions));
                        }
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    activities.Add(new TeamProjectActivityInfo(teamProject.Name, componentActivities));
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                this.Activities = activities;
                task.SetComplete("Retrieved " + this.Activities.Count.ToCountString("activity result"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while retrieving build definitions", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
        public static void ExportPermissions(ILogger logger, ApplicationTask task, TfsTeamProjectCollection tfs, TfsMajorVersion tfsVersion, IList <SecurityGroupPermissionExportRequest> exportRequests)
        {
            if (exportRequests.Any())
            {
                var step = 0;
                var securityNamespaces = tfs.GetService <ISecurityService>().GetSecurityNamespaces();
                var ims = tfs.GetService <IIdentityManagementService>();
                foreach (var exportRequest in exportRequests)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Exporting \"{0}\" permissions from Team Project \"{1}\"", exportRequest.SecurityGroup.Name, exportRequest.SecurityGroup.TeamProject.Name));
                    try
                    {
                        var identity = ims.ReadIdentity(IdentitySearchFactor.Identifier, exportRequest.SecurityGroup.Sid, MembershipQuery.None, ReadIdentityOptions.None);
                        if (identity == null)
                        {
                            var message = "The security group \"{0}\" could not be retrieved.".FormatCurrent(exportRequest.SecurityGroup.FullName);
                            logger.Log(message, TraceEventType.Warning);
                            task.SetWarning(message);
                        }
                        else
                        {
                            var permissions = new List <PermissionChangePersistenceData>();
                            foreach (var securityNamespace in securityNamespaces)
                            {
                                foreach (var factory in permissionGroupFactories)
                                {
                                    if (factory.AppliesTo(securityNamespace.Description.NamespaceId))
                                    {
                                        var tokens = factory.GetObjectTokens(tfs, tfsVersion, exportRequest.SecurityGroup.TeamProject.Name, exportRequest.SecurityGroup.TeamProject.Uri.ToString());
                                        if (tokens != null)
                                        {
                                            var permissionGroup = factory.GetPermissionGroup(securityNamespace);
                                            foreach (var token in tokens)
                                            {
                                                var acl = securityNamespace.QueryAccessControlList(token, new[] { identity.Descriptor }, false);
                                                foreach (var ace in acl.AccessControlEntries)
                                                {
                                                    foreach (var permission in permissionGroup.Permissions)
                                                    {
                                                        var action = PermissionChangeAction.Inherit;
                                                        if ((permission.PermissionBit & ace.Allow) == permission.PermissionBit)
                                                        {
                                                            action = PermissionChangeAction.Allow;
                                                        }
                                                        else if ((permission.PermissionBit & ace.Deny) == permission.PermissionBit)
                                                        {
                                                            action = PermissionChangeAction.Deny;
                                                        }
                                                        permissions.Add(new PermissionChangePersistenceData(permission.Scope, permission.PermissionConstant, action));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            Directory.CreateDirectory(Path.GetDirectoryName(exportRequest.FileName));
                            PermissionChangePersistenceData.Save(exportRequest.FileName, permissions);
                        }
                    }
                    catch (Exception exc)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while exporting \"{0}\" permissions from Team Project \"{1}\"", exportRequest.SecurityGroup.Name, exportRequest.SecurityGroup.TeamProject.Name);
                        logger.Log(message, exc);
                        task.SetError(message, exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            }
        }
        private void ApplyTransformations(object argument)
        {
            var simulate = this.Simulate;
            var saveCopy = this.SaveCopy;

            if (!simulate)
            {
                var result = MessageBox.Show("This will apply the specified transformations to all selected Team Projects. Are you sure you want to continue?", "Confirm Transformation", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (result != MessageBoxResult.Yes)
                {
                    return;
                }
            }
            var teamProjects    = this.SelectedTeamProjects.ToList();
            var transformations = this.Transformations.ToList();
            var task            = new ApplicationTask("Transforming work item configuration", teamProjects.Count, true);

            PublishStatus(new StatusEventArgs(task));
            var step   = 0;
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();
                var numTransformations = 0;

                foreach (var teamProject in teamProjects)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProject.Name));
                    try
                    {
                        var project = store.Projects[teamProject.Name];

                        // Apply the transformations only if everything succeeded for the Team Project; cache them in the mean time.
                        var transformedItems = new List <WorkItemConfigurationItem>();
                        foreach (var transformation in transformations)
                        {
                            if (transformation.WorkItemConfigurationItemType == WorkItemConfigurationItemType.WorkItemType)
                            {
                                // Apply work item type definition transformation, which can apply to multiple work item type definitions (semicolon separated).
                                // If no work item type names are specified, apply to all work item types in the project.
                                var workItemTypeNames = (string.IsNullOrEmpty(transformation.WorkItemTypeNames) ? project.WorkItemTypes.Cast <WorkItemType>().Select(w => w.Name) : transformation.WorkItemTypeNames.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
                                foreach (var workItemTypeName in workItemTypeNames)
                                {
                                    // If the work item type has already been processed before, continue with that version.
                                    var itemToTransform = transformedItems.FirstOrDefault(w => string.Equals(w.Name, workItemTypeName, StringComparison.OrdinalIgnoreCase));
                                    if (itemToTransform == null)
                                    {
                                        // If the work item type wasn't processed yet, find the one with the specified name (if it exists).
                                        var wit = project.WorkItemTypes.Cast <WorkItemType>().FirstOrDefault(w => string.Equals(w.Name, workItemTypeName, StringComparison.OrdinalIgnoreCase));
                                        if (wit != null)
                                        {
                                            itemToTransform = WorkItemTypeDefinition.FromXml(wit.Export(false));
                                        }
                                    }
                                    if (itemToTransform != null)
                                    {
                                        task.Status = "Transforming " + itemToTransform.DisplayName;
                                        var transformed = WorkItemConfigurationTransformer.Transform(transformation.TransformationType, itemToTransform.XmlDefinition, transformation.TransformationXml);
                                        if (string.Equals(itemToTransform.XmlDefinition.DocumentElement.OuterXml, transformed.DocumentElement.OuterXml))
                                        {
                                            task.Status = "The transformation was applied but did not result in any changes, skipping.";
                                        }
                                        else
                                        {
                                            itemToTransform.XmlDefinition = transformed;
                                            transformedItems.Add(itemToTransform);
                                        }
                                    }
                                    else
                                    {
                                        task.Status = "Skipping \"{0}\": a work item type with this name was not found in the Team Project".FormatCurrent(workItemTypeName);
                                    }
                                }
                            }
                            else if (transformation.WorkItemConfigurationItemType == WorkItemConfigurationItemType.Categories)
                            {
                                var itemToTransform = transformedItems.FirstOrDefault(w => w.Type == WorkItemConfigurationItemType.Categories);
                                if (itemToTransform == null)
                                {
                                    itemToTransform = WorkItemConfigurationItemImportExport.GetCategories(project);
                                }
                                task.Status = "Transforming " + itemToTransform.DisplayName;
                                var transformed = WorkItemConfigurationTransformer.Transform(transformation.TransformationType, itemToTransform.XmlDefinition, transformation.TransformationXml);
                                if (string.Equals(itemToTransform.XmlDefinition.DocumentElement.OuterXml, transformed.DocumentElement.OuterXml))
                                {
                                    task.Status = "The transformation was applied but did not result in any changes, skipping.";
                                }
                                else
                                {
                                    itemToTransform.XmlDefinition = transformed;
                                    transformedItems.Add(itemToTransform);
                                }
                            }
                            else if (transformation.WorkItemConfigurationItemType == WorkItemConfigurationItemType.AgileConfiguration)
                            {
                                var itemToTransform = transformedItems.FirstOrDefault(w => w.Type == WorkItemConfigurationItemType.AgileConfiguration);
                                if (itemToTransform == null)
                                {
                                    itemToTransform = WorkItemConfigurationItemImportExport.GetAgileConfiguration(project);
                                }
                                if (itemToTransform != null)
                                {
                                    task.Status = "Transforming " + itemToTransform.DisplayName;
                                    var transformed = WorkItemConfigurationTransformer.Transform(transformation.TransformationType, itemToTransform.XmlDefinition, transformation.TransformationXml);
                                    if (string.Equals(itemToTransform.XmlDefinition.DocumentElement.OuterXml, transformed.DocumentElement.OuterXml))
                                    {
                                        task.Status = "The transformation was applied but did not result in any changes, skipping.";
                                    }
                                    else
                                    {
                                        itemToTransform.XmlDefinition = transformed;
                                        transformedItems.Add(itemToTransform);
                                    }
                                }
                            }
                            else if (transformation.WorkItemConfigurationItemType == WorkItemConfigurationItemType.CommonConfiguration)
                            {
                                var itemToTransform = transformedItems.FirstOrDefault(w => w.Type == WorkItemConfigurationItemType.CommonConfiguration);
                                if (itemToTransform == null)
                                {
                                    itemToTransform = WorkItemConfigurationItemImportExport.GetCommonConfiguration(project);
                                }
                                if (itemToTransform != null)
                                {
                                    task.Status = "Transforming " + itemToTransform.DisplayName;
                                    var transformed = WorkItemConfigurationTransformer.Transform(transformation.TransformationType, itemToTransform.XmlDefinition, transformation.TransformationXml);
                                    if (string.Equals(itemToTransform.XmlDefinition.DocumentElement.OuterXml, transformed.DocumentElement.OuterXml))
                                    {
                                        task.Status = "The transformation was applied but did not result in any changes, skipping.";
                                    }
                                    else
                                    {
                                        itemToTransform.XmlDefinition = transformed;
                                        transformedItems.Add(itemToTransform);
                                    }
                                }
                            }
                            else if (transformation.WorkItemConfigurationItemType == WorkItemConfigurationItemType.ProcessConfiguration)
                            {
                                var itemToTransform = transformedItems.FirstOrDefault(w => w.Type == WorkItemConfigurationItemType.ProcessConfiguration);
                                if (itemToTransform == null)
                                {
                                    itemToTransform = WorkItemConfigurationItemImportExport.GetProcessConfiguration(project);
                                }
                                if (itemToTransform != null)
                                {
                                    task.Status = "Transforming " + itemToTransform.DisplayName;
                                    var transformed = WorkItemConfigurationTransformer.Transform(transformation.TransformationType, itemToTransform.XmlDefinition, transformation.TransformationXml);
                                    if (string.Equals(itemToTransform.XmlDefinition.DocumentElement.OuterXml, transformed.DocumentElement.OuterXml))
                                    {
                                        task.Status = "The transformation was applied but did not result in any changes, skipping.";
                                    }
                                    else
                                    {
                                        itemToTransform.XmlDefinition = transformed;
                                        transformedItems.Add(itemToTransform);
                                    }
                                }
                            }
                            else
                            {
                                throw new ArgumentException("The Work Item Configuration Item Type is unknown: " + transformation.WorkItemConfigurationItemType.ToString());
                            }
                            if (task.IsCanceled)
                            {
                                break;
                            }
                        }

                        // Only apply the transformations if they all succeeded (i.e. there was no exception).
                        if (task.IsCanceled)
                        {
                            break;
                        }
                        else
                        {
                            var teamProjectsWithConfigurationItems = new Dictionary <TeamProjectInfo, List <WorkItemConfigurationItem> >()
                            {
                                { teamProject, transformedItems }
                            };
                            var options = ImportOptions.None;
                            if (simulate)
                            {
                                options |= ImportOptions.Simulate;
                            }
                            if (saveCopy)
                            {
                                options |= ImportOptions.SaveCopy;
                            }
                            WorkItemConfigurationItemImportExport.Import(this.Logger, task, false, store, teamProjectsWithConfigurationItems, options);
                        }
                        numTransformations += transformedItems.Count;
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProject.Name), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = numTransformations;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while transforming work item configuration", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    var numTransformations = (int)e.Result;
                    task.SetComplete("Applied transformation to " + numTransformations.ToCountString("work item configuration item"));
                }
            };
            worker.RunWorkerAsync();
        }