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");
            }
        }
        public void Update(ApplicationTask task, IBuildDefinition buildDefinition, ICollection <IBuildController> availableBuildControllers, ICollection <IProcessTemplate> availableProcessTemplates)
        {
            if (buildDefinition == null)
            {
                return;
            }

            // General Properties
            if (UpdateBuildControllerName)
            {
                var selectedBuildController = availableBuildControllers.FirstOrDefault(c => string.Equals(c.Name, this.BuildControllerName, StringComparison.OrdinalIgnoreCase));
                if (selectedBuildController == null)
                {
                    task.SetWarning(string.Format(CultureInfo.CurrentCulture, "The build controller could not be set to \"{0}\" because a build controller with this name is not registered.", this.BuildControllerName));
                }
                else
                {
                    buildDefinition.BuildController = selectedBuildController;
                }
            }
            if (UpdateDefaultDropLocation)
            {
                // To disable the drop location, do not set to null but always use an empty string (null only works for TFS 2010 and before, an empty string always works).
                buildDefinition.DefaultDropLocation = this.DefaultDropLocation ?? string.Empty;
            }
            if (UpdateTriggerType)
            {
                buildDefinition.TriggerType = this.TriggerType;
            }
            if (UpdateQueueStatus)
            {
                buildDefinition.QueueStatus = this.QueueStatus;
            }
            if (UpdateProcessTemplate)
            {
                var selectedProcessTemplate = availableProcessTemplates.FirstOrDefault(p => string.Equals(p.ServerPath, this.ProcessTemplate, StringComparison.OrdinalIgnoreCase));
                if (selectedProcessTemplate == null)
                {
                    task.SetWarning(string.Format(CultureInfo.CurrentCulture, "The process template could not be set to \"{0}\" because a process template with this server path is not registered.", this.ProcessTemplate));
                }
                else
                {
                    buildDefinition.Process = selectedProcessTemplate;
                }
            }
            if (UpdateContinuousIntegrationQuietPeriod)
            {
                buildDefinition.ContinuousIntegrationQuietPeriod = this.ContinuousIntegrationQuietPeriod;
            }
            if (UpdateBatchSize)
            {
                buildDefinition.BatchSize = this.BatchSize;
            }
        }
Beispiel #3
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();
        }
Beispiel #4
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 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 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 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 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();
        }
Beispiel #10
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 static void PerformUserAction(ApplicationTask task, IIdentityManagementService ims, string userName, Action <TeamFoundationIdentity> action)
        {
            // Look up the user by account name.
            var userIdentity = ims.ReadIdentity(IdentitySearchFactor.AccountName, userName, MembershipQuery.None, ReadIdentityOptions.IncludeReadFromSource);

            if (userIdentity == null)
            {
                task.SetWarning("The requested user was not found: \"{0}\". Please make sure to use the account name, not the display name (which can be ambiguous).".FormatCurrent(userName));
            }
            else
            {
                action(userIdentity);
            }
        }
        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();
        }
Beispiel #13
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");
            }
        }
Beispiel #14
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");
            }
        }
Beispiel #15
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);
                    }
                }
            }
        }
        private void OnStatusEvent(StatusEventArgs message)
        {
            var task = message.Task;

            if (task == null)
            {
                task = new ApplicationTask(message.EventType.ToString());
                if (message.Details != null)
                {
                    task.Status = message.Details;
                }
                if (message.Exception != null)
                {
                    task.SetError(message.Exception);
                }
                else if (message.EventType <= TraceEventType.Error)
                {
                    task.SetError();
                }
                else if (message.EventType == TraceEventType.Warning)
                {
                    task.SetWarning();
                }
                task.SetComplete(message.Message);
            }
            this.executingTasksLock.EnterWriteLock();
            try
            {
                this.ExecutingTasks.Insert(0, new ApplicationTaskViewModel(task, this.Logger));
            }
            finally
            {
                this.executingTasksLock.ExitWriteLock();
            }
            this.removeTasksTimer.Enabled = true;
            task.StatusChanged           += new EventHandler <EventArgs>(OnTaskStatusChanged);
            UpdateStatus();
        }
Beispiel #18
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);
        }
Beispiel #19
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;
                    }
                }
            }
        }
        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 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();
        }
        private void GetWorkItemTypes(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving work item types", 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 <WorkItemTypeInfo>();
                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];
                        var categoriesXml = WorkItemConfigurationItemImportExport.GetCategoriesXml(project);
                        var categoryList  = WorkItemCategoryList.Load(categoriesXml);

                        foreach (WorkItemType workItemType in project.WorkItemTypes)
                        {
                            var parameters = new Dictionary <string, object>()
                            {
                                { "WorkItemType", workItemType.Name },
                                { "TeamProject", workItemType.Project.Name }
                            };
                            var workItemCount          = store.QueryCount("SELECT [System.Id] FROM WorkItems WHERE [System.WorkItemType] = @WorkItemType AND [System.TeamProject] = @TeamProject", parameters);
                            var referencingCategories  = categoryList.Categories.Where(c => c.WorkItemTypes.Concat(new WorkItemTypeReference[] { c.DefaultWorkItemType }).Any(w => string.Equals(w.Name, workItemType.Name, StringComparison.OrdinalIgnoreCase))).Select(c => c.Name);
                            var workItemTypeDefinition = WorkItemTypeDefinition.FromXml(workItemType.Export(false));
                            results.Add(new WorkItemTypeInfo(teamProject, workItemType.Name, workItemType.Description, workItemCount, referencingCategories.ToList(), workItemTypeDefinition));
                        }
                    }
                    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 work item types", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.WorkItemTypes = (ICollection <WorkItemTypeInfo>)e.Result;
                    task.SetComplete("Retrieved " + this.WorkItemTypes.Count.ToCountString("work item type"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void Search(object argument)
        {
            var searchText                   = this.SearchText;
            var searchUsesExactMatch         = this.SearchUsesExactMatch;
            var searchIncludesWorkItemFields = this.SearchIncludesWorkItemFields;
            var teamProjectNames             = this.SelectedTeamProjects.Select(p => p.Name).ToList();
            var task = new ApplicationTask(string.Format(CultureInfo.CurrentCulture, "Searching for \"{0}\"", searchText), 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 <SearchResult>();
                foreach (var teamProjectName in teamProjectNames)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                    try
                    {
                        var project = store.Projects[teamProjectName];
                        foreach (WorkItemType workItemType in project.WorkItemTypes)
                        {
                            if (Matches(searchText, searchUsesExactMatch, workItemType.Name))
                            {
                                results.Add(new SearchResult(teamProjectName, "Work Item", workItemType.Name, string.Format(CultureInfo.CurrentCulture, "Matching work item name: \"{0}\"", workItemType.Name)));
                            }
                            else if (Matches(searchText, searchUsesExactMatch, workItemType.Description))
                            {
                                results.Add(new SearchResult(teamProjectName, "Work Item", workItemType.Name, string.Format(CultureInfo.CurrentCulture, "Matching work item description: \"{0}\"", workItemType.Description)));
                            }
                            if (searchIncludesWorkItemFields)
                            {
                                foreach (FieldDefinition field in workItemType.FieldDefinitions)
                                {
                                    if (Matches(searchText, searchUsesExactMatch, field.Name))
                                    {
                                        results.Add(new SearchResult(teamProjectName, "Work Item Field", string.Concat(workItemType.Name, ".", field.Name), string.Format(CultureInfo.CurrentCulture, "Matching field name: \"{0}\"", field.Name)));
                                    }
                                    else if (Matches(searchText, searchUsesExactMatch, field.ReferenceName))
                                    {
                                        results.Add(new SearchResult(teamProjectName, "Work Item Field", string.Concat(workItemType.Name, ".", field.Name), string.Format(CultureInfo.CurrentCulture, "Matching field reference name: \"{0}\"", field.ReferenceName)));
                                    }
                                    else if (Matches(searchText, searchUsesExactMatch, field.HelpText))
                                    {
                                        results.Add(new SearchResult(teamProjectName, "Work Item Field", string.Concat(workItemType.Name, ".", field.Name), string.Format(CultureInfo.CurrentCulture, "Matching field help text: \"{0}\"", field.HelpText)));
                                    }
                                }
                            }
                            if (task.IsCanceled)
                            {
                                break;
                            }
                        }
                    }
                    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 searching", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.SearchResults = (ICollection <SearchResult>)e.Result;
                    task.SetComplete("Found " + this.SearchResults.Count.ToCountString("result"));
                }
            };
            worker.RunWorkerAsync();
        }
Beispiel #24
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();
        }
Beispiel #25
0
        private async Task UpdateSelectedBuildDefinitions(object argument)
        {
            var buildDefinitionsToUpdate = this.SelectedBuildDefinitions;
            var dialog = new BuildDefinitionUpdateDialog("Updating " + buildDefinitionsToUpdate.Count.ToCountString("build definition"));

            dialog.Owner = Application.Current.MainWindow;
            var dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                var task = new ApplicationTask("Updating build definitions", buildDefinitionsToUpdate.Count, true);
                PublishStatus(new StatusEventArgs(task));
                try
                {
                    var tfs                = GetSelectedTfsTeamProjectCollection();
                    var buildServer        = tfs.GetClient <BuildHttpClient>();
                    var taskAgentClient    = tfs.GetClient <TaskAgentHttpClient>();
                    var update             = dialog.BuildDefinitionUpdate;
                    var step               = 0;
                    var count              = 0;
                    var projectAgentQueues = new Dictionary <Guid, List <TaskAgentQueue> >();
                    foreach (var buildDefinitionToUpdate in buildDefinitionsToUpdate)
                    {
                        task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Updating build definition \"{0}\" in Team Project \"{1}\"", buildDefinitionToUpdate.Name, buildDefinitionToUpdate.Project.Name));
                        try
                        {
                            if (update.UpdateBuildNumberFormat)
                            {
                                buildDefinitionToUpdate.BuildNumberFormat = update.BuildNumberFormat;
                            }
                            if (update.UpdatePath)
                            {
                                buildDefinitionToUpdate.Path = update.Path;
                            }
                            if (update.UpdateAgentQueue)
                            {
                                if (!projectAgentQueues.ContainsKey(buildDefinitionToUpdate.Project.Id))
                                {
                                    projectAgentQueues[buildDefinitionToUpdate.Project.Id] = await taskAgentClient.GetAgentQueuesAsync(project : buildDefinitionToUpdate.Project.Id);
                                }
                                var agentQueues = projectAgentQueues[buildDefinitionToUpdate.Project.Id];
                                var agentQueue  = agentQueues.FirstOrDefault(q => string.Equals(q.Name, update.AgentQueueName, StringComparison.CurrentCultureIgnoreCase));
                                if (agentQueue == null)
                                {
                                    task.SetWarning($"An agent queue named \"{update.AgentQueueName}\" was not found in Team Project \"{buildDefinitionToUpdate.Project.Name}\"");
                                }
                                else
                                {
                                    buildDefinitionToUpdate.Queue = new AgentPoolQueue {
                                        Id = agentQueue.Id
                                    };
                                }
                            }
                            await buildServer.UpdateDefinitionAsync(buildDefinitionToUpdate);

                            count++;
                        }
                        catch (Exception exc)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while updating build definition \"{0}\" in Team Project \"{1}\"", buildDefinitionToUpdate.Name, buildDefinitionToUpdate.Project.Name), exc);
                        }
                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }
                    task.SetComplete("Updated " + count.ToCountString("build definition"));

                    // Refresh the list.
                    await GetBuildDefinitions(null);
                }
                catch (Exception exc)
                {
                    Logger.Log("An unexpected exception occurred while updating build definitions", exc);
                    task.SetError(exc);
                    task.SetComplete("An unexpected exception occurred");
                }
            }
        }
        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();
        }
Beispiel #27
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");
            }
        }
Beispiel #28
0
        public static void RegisterBuildProcessTemplate(ApplicationTask task, IBuildServer buildServer, IEnumerable <string> teamProjectNames, string templateServerPath, ProcessTemplateType templateType, bool registerIfTemplateDoesNotExist, bool unregisterAllOtherTemplates, bool unregisterAllOtherTemplatesIncludesUpgradeTemplate, bool simulate)
        {
            var step = 0;

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

                    var allTemplates      = buildServer.QueryProcessTemplates(teamProjectName);
                    var matchingTemplates = allTemplates.Where(t => t.ServerPath.Equals(templateServerPath, StringComparison.OrdinalIgnoreCase)).ToList();

                    if (unregisterAllOtherTemplates)
                    {
                        var templatesToUnregister = allTemplates.Except(matchingTemplates);
                        if (!unregisterAllOtherTemplatesIncludesUpgradeTemplate)
                        {
                            templatesToUnregister = templatesToUnregister.Where(t => t.TemplateType != ProcessTemplateType.Upgrade);
                        }
                        foreach (var templateToUnregister in templatesToUnregister)
                        {
                            task.Status = string.Format(CultureInfo.CurrentCulture, "Unregistering existing build process template \"{0}\"", templateToUnregister.ServerPath);
                            var buildDefinitions = buildServer.QueryBuildDefinitions(teamProjectName, QueryOptions.Process);
                            foreach (var buildDefinition in buildDefinitions)
                            {
                                if (buildDefinition.Process != null && BuildProcessTemplateInfo.AreEquivalent(buildDefinition.Process, templateToUnregister))
                                {
                                    task.SetWarning(string.Format(CultureInfo.CurrentCulture, "WARNING - The build \"{0}\" uses the build process template \"{1}\" that is being unregistered", buildDefinition.Name, templateToUnregister.ServerPath));
                                }
                            }
                            if (!simulate)
                            {
                                templateToUnregister.Delete();
                            }
                        }
                    }
                    if (!(unregisterAllOtherTemplates && unregisterAllOtherTemplatesIncludesUpgradeTemplate))
                    {
                        if (templateType == ProcessTemplateType.Default || templateType == ProcessTemplateType.Upgrade)
                        {
                            // There can be only one upgrade or default template for a team project.
                            // Make sure there isn't already a template with that type.
                            foreach (var template in allTemplates.Except(matchingTemplates).Where(t => t.TemplateType == templateType))
                            {
                                task.Status = string.Format(CultureInfo.CurrentCulture, "Changing type of existing build process template \"{0}\" from \"{1}\" to \"{2}\"", template.ServerPath, template.TemplateType.ToString(), ProcessTemplateType.Custom.ToString());
                                if (!simulate)
                                {
                                    template.TemplateType = ProcessTemplateType.Custom;
                                    template.Save();
                                }
                            }
                        }
                    }

                    if (registerIfTemplateDoesNotExist && !matchingTemplates.Any())
                    {
                        task.Status = string.Format(CultureInfo.CurrentCulture, "Registering new build process template \"{0}\" as type \"{1}\"", templateServerPath, templateType.ToString());
                        if (!simulate)
                        {
                            var template = buildServer.CreateProcessTemplate(teamProjectName, templateServerPath);
                            template.TemplateType = templateType;
                            template.Save();
                        }
                    }
                    else
                    {
                        foreach (var template in matchingTemplates.Where(t => t.TemplateType != templateType))
                        {
                            task.Status = string.Format(CultureInfo.CurrentCulture, "Changing type of existing build process template \"{0}\" from \"{1}\" to \"{2}\"", template.ServerPath, template.TemplateType.ToString(), templateType.ToString());
                            if (!simulate)
                            {
                                template.TemplateType = templateType;
                                template.Save();
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while registering the build process template \"{0}\" for Team Project \"{1}\"", templateServerPath, teamProjectName), 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 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();
        }