private void RegisterBuildProcessTemplate(object argument)
 {
     var result = MessageBoxResult.Yes;
     if (!this.Simulate)
     {
         result = MessageBox.Show("This will update all selected Team Projects. Are you sure you want to continue?", "Confirm Update", MessageBoxButton.YesNo, MessageBoxImage.Warning);
     }
     if (result == MessageBoxResult.Yes)
     {
         var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
         var task = new ApplicationTask((this.Simulate ? "Simulating registering build process template" : "Registering build process template"), teamProjectNames.Count, true);
         PublishStatus(new StatusEventArgs(task));
         var worker = new BackgroundWorker();
         worker.DoWork += (sender, e) =>
         {
             var tfs = GetSelectedTfsTeamProjectCollection();
             var buildServer = tfs.GetService<IBuildServer>();
             Tasks.RegisterBuildProcessTemplate(task, buildServer, teamProjectNames, this.TemplateServerPath, this.TemplateType, true, this.UnregisterAllOtherTemplates, this.UnregisterAllOtherTemplatesIncludesUpgradeTemplate, this.Simulate);
         };
         worker.RunWorkerCompleted += (sender, e) =>
         {
             if (e.Error != null)
             {
                 Logger.Log("An unexpected exception occurred while registering build process template", e.Error);
                 task.SetError(e.Error);
                 task.SetComplete("An unexpected exception occurred");
             }
             else
             {
                 task.SetComplete("Done");
             }
         };
         worker.RunWorkerAsync();
     }
 }
        private void GetBuildProcessTemplates(object argument)
        {
            var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
            var task             = new ApplicationTask("Retrieving build process templates", teamProjectNames.Count, true);

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

            worker.DoWork += (sender, e) =>
            {
                var tfs         = GetSelectedTfsTeamProjectCollection();
                var buildServer = tfs.GetService <IBuildServer>();
                e.Result = Tasks.GetBuildProcessTemplates(task, buildServer, teamProjectNames);
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving build process templates", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    var buildProcessTemplates = (IList <BuildProcessTemplateInfo>)e.Result;
                    this.BuildProcessTemplates = buildProcessTemplates;
                    RefreshBuildProcessHierarchy();
                    task.SetComplete("Retrieved " + buildProcessTemplates.Count().ToCountString("build process template"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void PerformImport(Dictionary <TeamProjectInfo, List <WorkItemConfigurationItem> > teamProjectsWithProcessConfigurations, ImportOptions options)
        {
            var numberOfSteps = teamProjectsWithProcessConfigurations.Aggregate(0, (a, p) => a += p.Value.Count);
            var task          = new ApplicationTask("Importing process configurations", numberOfSteps, true);

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

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();
                WorkItemConfigurationItemImportExport.Import(this.Logger, task, true, store, teamProjectsWithProcessConfigurations, options);
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while importing process configurations", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete(task.IsError ? "Failed" : (task.IsWarning ? "Succeeded with warnings" : "Succeeded"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void DeleteSelectedBuildProcessTemplates(object argument)
        {
            var result = MessageBox.Show("This will unregister the selected build process templates. Are you sure you want to continue?" + Environment.NewLine + Environment.NewLine + "Note that the XAML files will not be deleted from Source Control, they will only be unregistered as build process templates.", "Confirm Unregister", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                var buildProcessTemplates = this.SelectedBuildProcessTemplates.Select(p => p.ProcessTemplate).ToList();
                var task = new ApplicationTask("Unregistering build process templates", buildProcessTemplates.Count, true);
                PublishStatus(new StatusEventArgs(task));
                var worker = new BackgroundWorker();
                worker.DoWork += (sender, e) =>
                {
                    Tasks.UnregisterBuildProcessTemplates(task, buildProcessTemplates);
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Logger.Log("An unexpected exception occurred while unregistering build process template", e.Error);
                        task.SetError(e.Error);
                        task.SetComplete("An unexpected exception occurred");
                    }
                    else
                    {
                        task.SetComplete("Unregistered " + buildProcessTemplates.Count.ToCountString("build process template"));
                    }

                    // Refresh the list.
                    GetBuildProcessTemplates(null);
                };
                worker.RunWorkerAsync();
            }
        }
Пример #5
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();
        }
 private void RefreshTeamProjects(bool forceRefresh)
 {
     if (forceRefresh || (this.SelectedTeamProjectCollection != null && this.SelectedTeamProjectCollection.TeamFoundationServer == null && this.SelectedTeamProjectCollection.TeamProjects == null))
     {
         var teamProjectCollectionToRefresh = this.SelectedTeamProjectCollection;
         this.SelectedTeamProjectCollection = null;
         var task = new ApplicationTask(string.Format(CultureInfo.CurrentCulture, "Retrieving team projects for \"{0}\"", teamProjectCollectionToRefresh.Name));
         SetInfoMessage("Loading...", null);
         this.PublishStatus(new StatusEventArgs(task));
         this.IsTeamProjectsLoadComplete = false;
         this.TeamProjectsVisibility     = Visibility.Collapsed;
         var worker = new BackgroundWorker();
         worker.DoWork += (sender, e) =>
         {
             var tfs          = GetTfsTeamProjectCollection(teamProjectCollectionToRefresh.Uri);
             var tfsInfo      = GetTeamFoundationServerInfo(tfs, this.Logger);
             var store        = tfs.GetService <ICommonStructureService>();
             var teamProjects = store.ListAllProjects().Where(p => p.Status == Microsoft.TeamFoundation.Core.WebApi.ProjectState.WellFormed).Select(p => new TeamProjectInfo(teamProjectCollectionToRefresh, p.Name, new Uri(p.Uri), this.Logger)).OrderBy(p => p.Name).ToList();
             e.Result = new Tuple <TeamFoundationServerInfo, ICollection <TeamProjectInfo> >(tfsInfo, teamProjects);
         };
         worker.RunWorkerCompleted += (sender, e) =>
         {
             if (e.Error != null)
             {
                 this.Logger.Log("An unexpected exception occurred while retrieving team projects", e.Error);
                 SetInfoMessage("Could not connect", e.Error.Message);
                 task.SetError(e.Error);
                 task.SetComplete("An unexpected exception occurred");
             }
             else
             {
                 var result = (Tuple <TeamFoundationServerInfo, ICollection <TeamProjectInfo> >)e.Result;
                 teamProjectCollectionToRefresh.TeamFoundationServer = result.Item1;
                 teamProjectCollectionToRefresh.TeamProjects         = result.Item2;
                 this.SelectedTeamProjectCollection = teamProjectCollectionToRefresh;
                 task.SetComplete("Retrieved " + teamProjectCollectionToRefresh.TeamProjects.Count.ToCountString("team project"));
             }
             this.IsTeamProjectsLoadComplete = true;
             CommandManager.InvalidateRequerySuggested();
         };
         worker.RunWorkerAsync();
     }
     else
     {
         if (this.SelectedTeamProjectCollection == null)
         {
             SetInfoMessage(InfoMessageProperty.DefaultValue, null);
             this.TeamProjectsVisibility = Visibility.Collapsed;
         }
         else
         {
             var infoMessage = "Connected to {0}".FormatCurrent(this.SelectedTeamProjectCollection.TeamFoundationServer.ShortDisplayVersion);
             var toolTip     = "Connected to {0}".FormatCurrent(this.SelectedTeamProjectCollection.TeamFoundationServer.DisplayVersion);
             SetInfoMessage(infoMessage, toolTip);
             this.TeamProjectsVisibility = Visibility.Visible;
         }
         this.EventAggregator.GetEvent <TeamProjectCollectionSelectionChangedEvent>().Publish(new TeamProjectCollectionSelectionChangedEventArgs(this.SelectedTeamProjectCollection));
     }
     ShowAllTeamProjects(null);
 }
        private void ExportSelectedSecurityGroupPermissions(object argument)
        {
            var exportRequests = new List <SecurityGroupPermissionExportRequest>();
            var securityGroups = this.SelectedSecurityGroups;

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

            if (exportRequests.Any())
            {
                var task = new ApplicationTask("Exporting " + exportRequests.Count.ToCountString("security group permission"), exportRequests.Count, true);
                PublishStatus(new StatusEventArgs(task));
                var worker = new BackgroundWorker();
                worker.DoWork += (sender, e) =>
                {
                    SecurityManager.ExportPermissions(this.Logger, task, this.GetSelectedTfsTeamProjectCollection(), this.SelectedTeamProjectCollection.TeamFoundationServer.MajorVersion, exportRequests);
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Logger.Log("An unexpected exception occurred while exporting security group permission", e.Error);
                        task.SetError(e.Error);
                        task.SetComplete("An unexpected exception occurred");
                    }
                    else
                    {
                        task.SetComplete("Exported " + exportRequests.Count.ToCountString("security group permission"));
                    }
                };
                worker.RunWorkerAsync();
            }
        }
        private void ExportSelectedWorkItemTypes(object argument)
        {
            var workItemTypesToExport = new List <WorkItemConfigurationItemExport>();
            var workItemTypes         = this.SelectedWorkItemTypes;

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

            if (workItemTypesToExport.Any())
            {
                var task = new ApplicationTask("Exporting " + workItemTypesToExport.Count.ToCountString("work item type"), workItemTypesToExport.Count, true);
                PublishStatus(new StatusEventArgs(task));
                var worker = new BackgroundWorker();
                worker.DoWork += (sender, e) =>
                {
                    WorkItemConfigurationItemImportExport.Export(this.Logger, task, workItemTypesToExport);
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Logger.Log("An unexpected exception occurred while exporting work item types", e.Error);
                        task.SetError(e.Error);
                        task.SetComplete("An unexpected exception occurred");
                    }
                    else
                    {
                        task.SetComplete("Exported " + workItemTypesToExport.Count.ToCountString("work item type"));
                    }
                };
                worker.RunWorkerAsync();
            }
        }
Пример #9
0
        private async Task GetBuildDefinitions(object argument)
        {
            var teamProjects = this.SelectedTeamProjects.ToList();
            var task         = new ApplicationTask("Retrieving build definitions", teamProjects.Count, true);

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

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

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

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

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

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

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

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

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

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

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

                var step = 0;
                foreach (var teamProject in teamProjects)
                {
                    task.Status = "Processing Team Project \"{0}\"".FormatCurrent(teamProject.Name);
                    foreach (var taskGroup in taskGroups)
                    {
                        try
                        {
                            task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Importing task group \"{0}\" into Team Project \"{1}\"", taskGroup.Name, teamProject.Name));
                            await taskAgentClient.AddTaskGroupAsync(teamProject.Guid, taskGroup);
                        }
                        catch (MetaTaskDefinitionExistsException)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "The task group \"{0}\" already exists in Team Project \"{1}\"", taskGroup.Name, teamProject.Name));
                        }
                        catch (Exception exc)
                        {
                            task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while importing task group \"{0}\" into Team Project \"{1}\"", taskGroup.Name, teamProject.Name), exc);
                        }
                        if (task.IsCanceled)
                        {
                            break;
                        }
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                task.SetComplete("Imported " + taskGroups.Length.ToCountString("task group"));
            }
            catch (Exception exc)
            {
                Logger.Log("An unexpected exception occurred while importing task groups", exc);
                task.SetError(exc);
                task.SetComplete("An unexpected exception occurred");
            }
        }
        private 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 UpdateSourceControlSettings(object argument)
        {
            var result = MessageBox.Show("This will update the source control settings in all selected Team Projects. Are you sure you want to continue?", "Confirm Update", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
                var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
                var settings         = this.SelectedSourceControlSettings;
                var task             = new ApplicationTask("Updating source control settings", teamProjectNames.Count, true);
                this.PublishStatus(new StatusEventArgs(task));
                var worker = new BackgroundWorker();
                worker.DoWork += (sender, e) =>
                {
                    var step = 0;
                    var tfs  = GetSelectedTfsTeamProjectCollection();
                    var vcs  = tfs.GetService <VersionControlServer>();
                    foreach (var teamProjectName in teamProjectNames)
                    {
                        task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                        try
                        {
                            var project = vcs.GetTeamProject(teamProjectName);
                            project.ExclusiveCheckout   = !settings.EnableMultipleCheckout;
                            project.GetLatestOnCheckout = settings.EnableGetLatestOnCheckout;
                            var checkinNoteFields = settings.CheckinNoteFields.Select(f => new CheckinNoteFieldDefinition(f.Name, f.Required, f.DisplayOrder)).ToArray();
                            project.SetCheckinNoteFields(checkinNoteFields);
                        }
                        catch (Exception exc)
                        {
                            task.SetError(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                        }
                        if (task.IsCanceled)
                        {
                            task.Status = "Canceled";
                            break;
                        }
                    }
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                    {
                        Logger.Log("An unexpected exception occurred while updating source control settings", e.Error);
                        task.SetError(e.Error);
                        task.SetComplete("An unexpected exception occurred");
                    }
                    else
                    {
                        task.SetComplete("Done");
                    }
                };
                worker.RunWorkerAsync();
            }
        }
        private void ImportWorkItemCategoryList(object argument)
        {
            var result = MessageBox.Show("This will import the work item category list to all selected Team Projects. Certain applications like Microsoft Test Manager rely on categories so modifying them can reduce their functionality. Are you sure you want to continue?", "Confirm Import", MessageBoxButton.YesNo, MessageBoxImage.Warning);

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

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

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

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

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

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

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

                e.Result = buildDefinitions;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving build definitions", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.BuildDefinitions = (ICollection <BuildDefinitionInfo>)e.Result;
                    task.SetComplete("Retrieved " + this.BuildDefinitions.Count.ToCountString("build definition"));
                }
            };
            worker.RunWorkerAsync();
        }
Пример #18
0
        private async Task DeleteSelectedServiceEndpoints(object argument)
        {
            var result = MessageBox.Show("This will delete the selected service endpoints. Are you sure you want to continue?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

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

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

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

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

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

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

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

            worker.DoWork += (sender, e) =>
            {
                var settings = new ObservableCollection <SourceControlSettings>();
                var step     = 0;
                var tfs      = GetSelectedTfsTeamProjectCollection();
                var vcs      = tfs.GetService <VersionControlServer>();
                foreach (var teamProjectName in teamProjectNames)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Processing Team Project \"{0}\"", teamProjectName));
                    try
                    {
                        var projectSettings = GetSourceControlSettings(vcs, teamProjectName);
                        settings.Add(projectSettings);
                    }
                    catch (Exception exc)
                    {
                        task.SetWarning(string.Format(CultureInfo.CurrentCulture, "An error occurred while processing Team Project \"{0}\"", teamProjectName), exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = settings;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving source control settings", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    this.SourceControlSettings = (ObservableCollection <SourceControlSettings>)e.Result;
                    task.SetComplete("Done");
                }
            };
            worker.RunWorkerAsync();
        }
Пример #20
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");
            }
        }
        private void ViewBranchHierarchies(object argument)
        {
            var teamProjectNames = this.SelectedTeamProjects.Select(p => p.Name).ToList();
            var task             = new ApplicationTask("Retrieving branch hierarchies", null, true);

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

            worker.DoWork += (sender, e) =>
            {
                var tfs = GetSelectedTfsTeamProjectCollection();
                var vcs = tfs.GetService <VersionControlServer>();
                var teamProjectRootPaths = teamProjectNames.Select(t => string.Concat("$/", t, "/")).ToArray();
                var branchHierarchies    = new List <BranchInfo>();
                foreach (var rootBranch in vcs.QueryRootBranchObjects(RecursionType.OneLevel).Where(b => !teamProjectRootPaths.Any() || teamProjectRootPaths.Any(t => (b.Properties.RootItem.Item + "/").StartsWith(t, StringComparison.OrdinalIgnoreCase))).OrderBy(b => b.Properties.RootItem.Item))
                {
                    branchHierarchies.Add(GetBranchInfo(rootBranch, null, vcs, task));
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
                e.Result = branchHierarchies;
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while retrieving branch hierarchies", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                    this.BranchHierarchiesInfoMessage = null;
                }
                else
                {
                    this.BranchHierarchies = (IList <BranchInfo>)e.Result;
                    var totalBranchCount = this.BranchHierarchies.Count + this.BranchHierarchies.Sum(b => b.RecursiveChildCount);
                    var maxTreeDepth     = this.BranchHierarchies.Any() ? this.BranchHierarchies.Max(b => b.MaxTreeDepth) : 0;
                    var infoMessage      = "Retrieved {0} with a total of {1} and a maximum depth of {2}".FormatCurrent(this.BranchHierarchies.Count.ToCountString("branch hierarchy"), totalBranchCount.ToCountString("branch"), maxTreeDepth);
                    task.SetComplete(infoMessage);
                    this.BranchHierarchiesInfoMessage = infoMessage;
                }
            };
            worker.RunWorkerAsync();
        }
        private void LoadWorkItemCategoryList(object argument)
        {
            using (var dialog = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false))
            {
                var result = dialog.ShowDialog(Application.Current.MainWindow.GetIWin32Window());
                if (result == System.Windows.Forms.DialogResult.OK && dialog.SelectedProjects != null && dialog.SelectedProjects.Length > 0)
                {
                    var teamProjectCollection = dialog.SelectedTeamProjectCollection;
                    var teamProject           = dialog.SelectedProjects.First();

                    var task = new ApplicationTask("Loading work item category list");
                    PublishStatus(new StatusEventArgs(task));
                    var worker = new BackgroundWorker();
                    worker.DoWork += (sender, e) =>
                    {
                        var tfs           = GetTfsTeamProjectCollection(teamProjectCollection.Uri);
                        var store         = tfs.GetService <WorkItemStore>();
                        var project       = store.Projects[teamProject.Name];
                        var categoriesXml = WorkItemConfigurationItemImportExport.GetCategoriesXml(project);
                        var selectedWorkItemCategoryList    = WorkItemCategoryList.Load(categoriesXml);
                        var availableWorkItemTypeReferences = project.WorkItemTypes.Cast <WorkItemType>().Select(w => new WorkItemTypeReference {
                            Name = w.Name
                        }).ToList();
                        e.Result = new Tuple <WorkItemCategoryList, ICollection <WorkItemTypeReference> >(selectedWorkItemCategoryList, availableWorkItemTypeReferences);
                    };
                    worker.RunWorkerCompleted += (sender, e) =>
                    {
                        if (e.Error != null)
                        {
                            Logger.Log("An unexpected exception occurred while importing the work item category list", e.Error);
                            task.SetError(e.Error);
                            task.SetComplete("An unexpected exception occurred");
                        }
                        else
                        {
                            var loadResult = (Tuple <WorkItemCategoryList, ICollection <WorkItemTypeReference> >)e.Result;
                            this.SelectedWorkItemCategoryList    = loadResult.Item1;
                            this.AvailableWorkItemTypeReferences = loadResult.Item2;
                            this.SelectedWorkItemCategory        = this.SelectedWorkItemCategoryList.Categories.FirstOrDefault();
                            task.SetComplete("Done");
                        }
                    };
                    worker.RunWorkerAsync();
                }
            }
        }
Пример #23
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");
            }
        }
Пример #24
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 void LoadSourceControlSettings(object argument)
        {
            using (var dialog = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false))
            {
                var result = dialog.ShowDialog(Application.Current.MainWindow.GetIWin32Window());
                if (result == System.Windows.Forms.DialogResult.OK && dialog.SelectedProjects != null && dialog.SelectedProjects.Length > 0)
                {
                    var teamProjectCollection = dialog.SelectedTeamProjectCollection;
                    var teamProject           = dialog.SelectedProjects.First();

                    var task = new ApplicationTask("Loading source control settings");
                    PublishStatus(new StatusEventArgs(task));
                    var worker = new BackgroundWorker();
                    worker.DoWork += (sender, e) =>
                    {
                        var tfs             = GetSelectedTfsTeamProjectCollection();
                        var vcs             = tfs.GetService <VersionControlServer>();
                        var projectSettings = GetSourceControlSettings(vcs, teamProject.Name);
                        e.Result = projectSettings;
                    };
                    worker.RunWorkerCompleted += (sender, e) =>
                    {
                        if (e.Error != null)
                        {
                            Logger.Log("An unexpected exception occurred while loading source control settings", e.Error);
                            task.SetError(e.Error);
                            task.SetComplete("An unexpected exception occurred");
                        }
                        else
                        {
                            this.SelectedSourceControlSettings = (SourceControlSettings)e.Result;
                            task.SetComplete("Done");
                        }
                    };
                    worker.RunWorkerAsync();
                }
            }
        }
        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();
        }
        private void ExportSelectedWorkItemQueries(object argument)
        {
            var workItemQueriesToExport = new List <WorkItemQueryExport>();
            var workItemQueries         = this.SelectedWorkItemQueries;

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

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

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

            worker.DoWork += (sender, e) =>
            {
                var step = 0;
                foreach (var workItemQueryToExport in workItemQueriesToExport)
                {
                    task.SetProgress(step++, string.Format(CultureInfo.CurrentCulture, "Exporting \"{0}\" from Team Project \"{1}\"", workItemQueryToExport.Query.Name, workItemQueryToExport.Query.TeamProject));
                    try
                    {
                        if (!string.IsNullOrEmpty(workItemQueryToExport.SaveAsFileName))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(workItemQueryToExport.SaveAsFileName));
                            workItemQueryToExport.WrapInXmlDocument().Save(workItemQueryToExport.SaveAsFileName);
                        }
                    }
                    catch (Exception exc)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while exporting \"{0}\"", workItemQueryToExport.Query.Name);
                        this.Logger.Log(message, exc);
                        task.SetError(message, exc);
                    }
                    if (task.IsCanceled)
                    {
                        task.Status = "Canceled";
                        break;
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while exporting work item queries", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete("Exported " + workItemQueriesToExport.Count.ToCountString("work item query"));
                }
            };
            worker.RunWorkerAsync();
        }
        private void DeleteSelectedWorkItemQueries(object argument)
        {
            var result = MessageBox.Show("This will delete the selected work item queries. Are you sure you want to continue?", "Confirm Delete", MessageBoxButton.YesNo, MessageBoxImage.Warning);

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

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

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

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

                // Refresh the list.
                GetWorkItemQueries(null);
            };
            worker.RunWorkerAsync();
        }
        private void 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 PerformImport(Dictionary <string, List <WorkItemQueryInfo> > teamProjectsWithQueries)
        {
            var numberOfSteps = teamProjectsWithQueries.Aggregate(0, (a, p) => a += p.Value.Count);
            var task          = new ApplicationTask("Importing work item queries", numberOfSteps, true);

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

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

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

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

                        ImportQuery(query, project.QueryHierarchy);

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

                    if (!task.IsCanceled)
                    {
                        try
                        {
                            project.QueryHierarchy.Save();
                        }
                        catch (Exception exc)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, "An error occurred while saving changes to \"{0}\"", teamProject);
                            this.Logger.Log(message, exc);
                            task.SetError(message, exc);
                        }
                    }
                }
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while importing work item queries", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete(task.IsError ? "Failed" : (task.IsWarning ? "Succeeded with warnings" : "Succeeded"));
                }
            };
            worker.RunWorkerAsync();
        }