public void SetTeamQueries(QueryHierarchy sourceQueryCol, string sourceProjectName)
        {
            foreach (QueryFolder queryFolder in sourceQueryCol)
            {
                if (queryFolder.Name == "Team Queries" || queryFolder.Name == "Shared Queries")
                {
                    QueryFolder teamQueriesFolder = null;

                    if (store.Projects[projectName].QueryHierarchy.Contains("Shared Queries"))
                    {
                        teamQueriesFolder = (QueryFolder)store.Projects[projectName].QueryHierarchy["Shared Queries"];
                    }
                    // seems there is no way to get the localized name dynamically
                    if (store.Projects[projectName].QueryHierarchy.Contains("Freigegebene Abfragen"))
                    {
                        teamQueriesFolder = (QueryFolder)store.Projects[projectName].QueryHierarchy["Freigegebene Abfragen"];
                    }

                    if (teamQueriesFolder != null)
                    {
                        SetQueryItem(queryFolder, teamQueriesFolder, sourceProjectName);
                    }

                    // test seems to be unnecessary
                    //QueryFolder test = (QueryFolder)store.Projects[projectName].QueryHierarchy["Shared Queries"];
                }
            }
        }
        internal override void InternalExecute()
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            //////////////////////////////////////////////////
            WorkItemStoreContext targetStore = new WorkItemStoreContext(me.Target, WorkItemStoreFlags.BypassRules);

            TfsQueryContext tfsqc = new TfsQueryContext(targetStore);

            TfsTeamService            teamService = me.Target.Collection.GetService <TfsTeamService>();
            QueryHierarchy            qh          = targetStore.Store.Projects[me.Target.Config.Project].QueryHierarchy;
            List <TeamFoundationTeam> teamList    = teamService.QueryTeams(me.Target.Config.Project).ToList();

            Trace.WriteLine(string.Format("Found {0} teams?", teamList.Count));
            //////////////////////////////////////////////////
            int  current   = teamList.Count;
            int  count     = 0;
            long elapsedms = 0;

            foreach (TeamFoundationTeam team in teamList)
            {
                Stopwatch witstopwatch = Stopwatch.StartNew();

                Trace.Write(string.Format("Processing team {0}", team.Name));
                Regex  r = new Regex(@"^Project - ([a-zA-Z ]*)");
                string path;
                if (r.IsMatch(team.Name))
                {
                    Trace.Write(string.Format(" is a Project"));
                    path = string.Format(@"Projects\{0}", r.Match(team.Name).Groups[1].Value.Replace(" ", "-"));
                }
                else
                {
                    Trace.Write(string.Format(" is a Team"));
                    path = string.Format(@"Teams\{0}", team.Name.Replace(" ", "-"));
                }
                Trace.Write(string.Format(" and new path is {0}", path));
                //me.AddFieldMap("*", new RegexFieldMap("KM.Simulation.Team", "System.AreaPath", @"^Project - ([a-zA-Z ]*)", @"Nemo\Projects\$1"));

                string[] bits = path.Split(char.Parse(@"\"));

                CreateFolderHyerarchy(bits, qh["Shared Queries"]);

                //_me.ApplyFieldMappings(workitem);
                qh.Save();


                witstopwatch.Stop();
                elapsedms = elapsedms + witstopwatch.ElapsedMilliseconds;
                current--;
                count++;
                TimeSpan average   = new TimeSpan(0, 0, 0, 0, (int)(elapsedms / count));
                TimeSpan remaining = new TimeSpan(0, 0, 0, 0, (int)(average.TotalMilliseconds * current));
                Trace.WriteLine("");
                //Trace.WriteLine(string.Format("Average time of {0} per work item and {1} estimated to completion", string.Format(@"{0:s\:fff} seconds", average), string.Format(@"{0:%h} hours {0:%m} minutes {0:s\:fff} seconds", remaining)));
            }
            //////////////////////////////////////////////////
            stopwatch.Stop();
            Console.WriteLine(@"DONE in {0:%h} hours {0:%m} minutes {0:s\:fff} seconds", stopwatch.Elapsed);
        }
 public WorkItemRead(TfsTeamProjectCollection tfs, Project sourceProject)
 {
     this.tfs = tfs;
     projectName = sourceProject.Name;
     store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
     queryCol = store.Projects[sourceProject.Name].QueryHierarchy;
     workItemTypes = store.Projects[sourceProject.Name].WorkItemTypes;
 }
 public WorkItemRead(TfsTeamProjectCollection tfs, Project sourceProject)
 {
     this.tfs      = tfs;
     projectName   = sourceProject.Name;
     store         = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
     queryCol      = store.Projects[sourceProject.Name].QueryHierarchy;
     workItemTypes = store.Projects[sourceProject.Name].WorkItemTypes;
 }
        private static void ImportQuery(WorkItemQueryInfo query, QueryHierarchy queryHierarchy)
        {
            var currentFolder = queryHierarchy.OfType <QueryFolder>().FirstOrDefault(i => !i.IsPersonal);

            if (currentFolder == null)
            {
                throw new InvalidOperationException("The query hierarchy does not contain a shared (non-personal) root folder.");
            }
            var currentFolderNameIndex = 0;
            var pathComponents         = (query.Path ?? string.Empty).Split('/');

            while (currentFolderNameIndex < pathComponents.Length)
            {
                var childFolderName = pathComponents[currentFolderNameIndex];
                if (currentFolder.Contains(childFolderName))
                {
                    var itemWithName = currentFolder[childFolderName];
                    if (itemWithName is QueryDefinition)
                    {
                        throw new ArgumentException("A query folder was requested but a query file with the same name exists at the same location: " + childFolderName);
                    }
                    else
                    {
                        currentFolder = (QueryFolder)itemWithName;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(childFolderName))
                    {
                        // If childFolderName is empty then we import into the root, otherwise create the folder.
                        var newFolder = new QueryFolder(childFolderName);
                        currentFolder.Add(newFolder);
                        currentFolder = newFolder;
                    }
                }
                currentFolderNameIndex++;
            }

            if (currentFolder.Contains(query.Name))
            {
                var itemWithName = currentFolder[query.Name];
                if (itemWithName is QueryFolder)
                {
                    throw new ArgumentException("A query file was requested but a query folder with the same name exists at the same location: " + query.Name);
                }
                else
                {
                    var existingQuery = (QueryDefinition)itemWithName;
                    existingQuery.QueryText = query.Text;
                }
            }
            else
            {
                var newQuery = new QueryDefinition(query.Name, query.Text);
                currentFolder.Add(newQuery);
            }
        }
        public TPWiWrapper(TeamExplorerIntergator teamExpolorer)
        {
            tpCollection    = teamExpolorer.tpCollection;
            teamProjectName = teamExpolorer.tpName;

            wiStore = (WorkItemStore)tpCollection.GetService(typeof(WorkItemStore));
            qh      = wiStore.Projects[teamProjectName].QueryHierarchy;
            wiTypes = wiStore.Projects[teamProjectName].WorkItemTypes;
        }
        public TPWiWrapper(string tpCollectionUrl, string aTeamProjectName)
        {
            tpCollection    = new TfsTeamProjectCollection(new Uri(tpCollectionUrl));
            teamProjectName = aTeamProjectName;

            wiStore = (WorkItemStore)tpCollection.GetService(typeof(WorkItemStore));
            qh      = wiStore.Projects[teamProjectName].QueryHierarchy;
            wiTypes = wiStore.Projects[teamProjectName].WorkItemTypes;
        }
Beispiel #8
0
        /// <summary>
        /// Constructor that takes in the projects URL, grabs the work item store where
        /// the queries are found, as well as the specific project name
        /// </summary>
        /// <param name="tfsUrl"></param>
        /// <param name="projectName"></param>
        public TfsHelperFunctions(string tfsUrl, string projectName)
        {
            _coll = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
                new Uri(tfsUrl));

            Store = new WorkItemStore(_coll);

            MyProject = Store.Projects[projectName];

            QueryHierarchy = Store.Projects[projectName].QueryHierarchy;
        }
 public WorkItemWrite(TfsTeamProjectCollection tfs, Project destinationProject)
 {
     this.tfs = tfs;
     projectName = destinationProject.Name;
     this.destinationProject = destinationProject;
     store = new WorkItemStore(tfs, WorkItemStoreFlags.BypassRules);
     queryCol = store.Projects[destinationProject.Name].QueryHierarchy;
     workItemTypes = store.Projects[destinationProject.Name].WorkItemTypes;
     itemMap = new Hashtable();
     itemMapCIC = new Hashtable();
 }
Beispiel #10
0
 public WorkItemWrite(TfsTeamProjectCollection tfs, Project destinationProject)
 {
     this.tfs                = tfs;
     projectName             = destinationProject.Name;
     this.destinationProject = destinationProject;
     store         = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
     queryCol      = store.Projects[destinationProject.Name].QueryHierarchy;
     workItemTypes = store.Projects[destinationProject.Name].WorkItemTypes;
     itemMap       = new Hashtable();
     itemMapCIC    = new Hashtable();
 }
Beispiel #11
0
        /// <summary>
        /// Constructor that takes in the projects URL, grabs the work item store where
        /// the queries are found, as well as the specific project name
        /// </summary>
        /// <param name="tfsUrl"></param>
        /// <param name="projectName"></param>
        public TfsHelperFunctions(string tfsUrl, string projectName)
        {
            var coll = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
                new Uri(tfsUrl));

            store = new WorkItemStore(coll);

            MyProject = store.Projects[projectName];

            QueryHierarchy = store.Projects[projectName].QueryHierarchy;
        }
 public WorkItemWrite(TfsTeamProjectCollection tfs, Project destinationProject)
 {
     this.tfs = tfs;
     projectName = destinationProject.Name;
     this.destinationProject = destinationProject;
     store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
     queryCol = store.Projects[destinationProject.Name].QueryHierarchy;
     workItemTypes = store.Projects[destinationProject.Name].WorkItemTypes;
     itemMap = new Hashtable();
     itemMapCIC = new Hashtable();
 }
 public WorkItemWrite(TfsTeamProjectCollection tfs, Project destinationProject)
 {
     this.tfs                = tfs;
     projectName             = destinationProject.Name;
     this.destinationProject = destinationProject;
     store         = new WorkItemStore(tfs, WorkItemStoreFlags.BypassRules);
     queryCol      = store.Projects[destinationProject.Name].QueryHierarchy;
     workItemTypes = store.Projects[destinationProject.Name].WorkItemTypes;
     itemMap       = new Hashtable();
     itemMapCIC    = new Hashtable();
 }
        protected override void InternalExecute()
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            //////////////////////////////////////////////////
            TfsTeamService            teamService = Engine.Target.GetService <TfsTeamService>();
            QueryHierarchy            qh          = ((TfsWorkItemMigrationClient)Engine.Target.WorkItems).Store.Projects[Engine.Target.Config.AsTeamProjectConfig().Project].QueryHierarchy;
            List <TeamFoundationTeam> teamList    = teamService.QueryTeams(Engine.Target.Config.AsTeamProjectConfig().Project).ToList();

            Log.LogInformation("Found {0} teams?", teamList.Count);
            //////////////////////////////////////////////////
            int  current   = teamList.Count;
            int  count     = 0;
            long elapsedms = 0;

            foreach (TeamFoundationTeam team in teamList)
            {
                Stopwatch witstopwatch = Stopwatch.StartNew();

                Log.LogTrace("Processing team {0}", team.Name);
                Regex  r = new Regex(@"^Project - ([a-zA-Z ]*)");
                string path;
                if (r.IsMatch(team.Name))
                {
                    Log.LogInformation("{0} is a Project", team.Name);
                    path = string.Format(@"Projects\{0}", r.Match(team.Name).Groups[1].Value.Replace(" ", "-"));
                }
                else
                {
                    Log.LogInformation("{0} is a Team", team.Name);
                    path = string.Format(@"Teams\{0}", team.Name.Replace(" ", "-"));
                }
                Log.LogInformation(" and new path is {0}", path);
                //me.AddFieldMap("*", new RegexFieldMap("KM.Simulation.Team", "System.AreaPath", @"^Project - ([a-zA-Z ]*)", @"Nemo\Projects\$1"));

                string[] bits = path.Split(char.Parse(@"\"));

                CreateFolderHyerarchy(bits, qh["Shared Queries"]);

                //_me.ApplyFieldMappings(workitem);
                qh.Save();

                witstopwatch.Stop();
                elapsedms = elapsedms + witstopwatch.ElapsedMilliseconds;
                current--;
                count++;
                TimeSpan average   = new TimeSpan(0, 0, 0, 0, (int)(elapsedms / count));
                TimeSpan remaining = new TimeSpan(0, 0, 0, 0, (int)(average.TotalMilliseconds * current));
                Log.LogInformation("Average time of {average} per work item and {remaining} estimated to completion", average.ToString("c"), remaining.ToString("c"));
            }
            //////////////////////////////////////////////////
            stopwatch.Stop();
            Log.LogInformation("DONE in {Elapsed} ", stopwatch.Elapsed.ToString("c"));
        }
Beispiel #15
0
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values == null)
            {
                return(DependencyProperty.UnsetValue);
            }
            if (values.Length < 2)
            {
                return(DependencyProperty.UnsetValue);
            }

            QueryFolder     folder     = values[0] as QueryFolder;
            QueryHierarchy  hierarchy  = values[0] as QueryHierarchy;
            QueryDefinition definition = values[0] as QueryDefinition;

            var brush = EnabledBrush;

            bool isEnabled = values[1] is bool?(bool)values[1] : false;

            if (!isEnabled)
            {
                return(DisabledBrush);
            }

            if (definition != null)
            {
                switch (definition.QueryType)
                {
                case QueryType.Invalid:
                    brush = DisabledBrush;
                    break;

                case QueryType.List:
                    brush = DisabledBrush;
                    break;

                case QueryType.OneHop:
                    brush = EnabledBrush;
                    break;

                case QueryType.Tree:
                    brush = EnabledBrush;
                    break;

                default:
                    brush = DisabledBrush;
                    break;
                }
            }

            return(brush);
        }
Beispiel #16
0
        public void SetTeamQueries(QueryHierarchy sourceQueryCol, string sourceProjectName)
        {
            foreach (QueryFolder queryFolder in sourceQueryCol)
            {
                if (queryFolder.Name == "Team Queries" || queryFolder.Name == "Shared Queries")
                {
                    QueryFolder teamQueriesFolder = (QueryFolder)store.Projects[projectName].QueryHierarchy["Shared Queries"];
                    SetQueryItem(queryFolder, teamQueriesFolder, sourceProjectName);

                    QueryFolder test = (QueryFolder)store.Projects[projectName].QueryHierarchy["Shared Queries"];
                }
            }
        }
Beispiel #17
0
        internal static QueryHierarchyWrapper GetInstance()
        {
            QueryHierarchy real = default(QueryHierarchy);

            RealInstanceFactory(ref real);
            var instance = (QueryHierarchyWrapper)QueryHierarchyWrapper.GetWrapper(real);

            InstanceFactory(ref instance);
            if (instance == null)
            {
                Assert.Inconclusive("Could not Create Test Instance");
            }
            return(instance);
        }
Beispiel #18
0
        public static TfsRootFolderQueryItem BuildTreeViewFromTfs(QueryHierarchy queryHierarchy, string header, ICommand command)
        {
            TfsRootFolderQueryItem root = new TfsRootFolderQueryItem(null, header);

            foreach (var queryItem in queryHierarchy)
            {
                if (queryItem is QueryFolder qf)
                {
                    DefineRootFolder(qf, root, command);
                }
            }

            return(root);
        }
Beispiel #19
0
        private QueryItem GetQueryByName(string name, string projectName)
        {
            WorkItemStore workItemStore = (WorkItemStore)Session["WorkItemStore"];
            var           project       = workItemStore.Projects[projectName];

            QueryHierarchy query       = project.QueryHierarchy;
            var            queryFolder = query as QueryFolder;
            QueryItem      queryItem   = queryFolder["Shared Queries"];

            queryFolder = queryItem as QueryFolder;

            IEnumerable queries = GetAllContainedQueriesList(queryFolder);

            return(queries.Cast <QueryItem>().FirstOrDefault(item => item.Name == name));
        }
Beispiel #20
0
        public JsonResult GetSharedQueriesList(string projectName)
        {
            WorkItemStore workItemStore = (WorkItemStore)Session["WorkItemStore"];
            var           project       = workItemStore.Projects[projectName];

            QueryHierarchy query       = project.QueryHierarchy;
            var            queryFolder = query as QueryFolder;
            var            queryItem   = queryFolder["Shared Queries"];

            queryFolder = queryItem as QueryFolder;

            IEnumerable <string> names = (IEnumerable <string>)GetQueriesNames(GetAllContainedQueriesList(queryFolder));

            return(Json(names, JsonRequestBehavior.AllowGet));
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("https://code-inside.visualstudio.com/DefaultCollection"));


            // http://stackoverflow.com/questions/10748412/retrieving-work-items-and-their-linked-work-items-in-a-single-query-using-the-tf/10757338#10757338
            var workItemStore = tfs.GetService <WorkItemStore>();

            var            project        = workItemStore.Projects["Grocerylist"];
            QueryHierarchy queryHierarchy = project.QueryHierarchy;
            var            queryFolder    = queryHierarchy as QueryFolder;
            QueryItem      queryItem      = queryFolder["My Queries"];

            queryFolder = queryItem as QueryFolder;

            if (queryFolder != null)
            {
                Dictionary <string, string> variables = new Dictionary <string, string>();
                variables.Add("project", "Grocerylist");

                var myQuery = queryFolder["New Query 1"] as QueryDefinition;
                if (myQuery != null)
                {
                    var wiCollection = workItemStore.Query(myQuery.QueryText, variables);
                    foreach (WorkItem workItem in wiCollection)
                    {
                        Console.WriteLine("WorkItem -----------------------------");
                        Console.WriteLine(workItem.Title);

                        foreach (Revision rev in workItem.Revisions)
                        {
                            Console.WriteLine("  - Revition: " + rev.Index);

                            foreach (Field f in rev.Fields)
                            {
                                if (!Object.Equals(f.Value, f.OriginalValue))
                                {
                                    Console.WriteLine("  - Changes: {0}: {1} -> {2}", f.Name, f.OriginalValue, f.Value);
                                }
                            }
                            Console.WriteLine("  ------------------");
                        }
                    }

                    Console.ReadLine();
                }
            }
        }
        /// <summary>
        /// Add Query Definition under a specific Query Folder.
        /// </summary>
        /// <param name="targetHierarchy">The object that represents the whole of the target query tree</param>
        /// <param name="query">Query Definition - Contains the Query Details</param>
        /// <param name="QueryFolder">Parent Folder</param>
        void MigrateQuery(QueryHierarchy targetHierarchy, QueryDefinition query, QueryFolder parentFolder)
        {
            if (parentFolder.FirstOrDefault(q => q.Name == query.Name) != null)
            {
                this.totalQueriesSkipped++;
                Trace.WriteLine($"Skipping query '{query.Name}' as already exists");
            }
            else
            {
                // Sort out any path issues in the quertText
                var fixedQueryText = query.QueryText.Replace($"'{Engine.Source.Config.Project}", $"'{Engine.Target.Config.Project}"); // the ' should only items at the start of areapath etc.

                if (config.PrefixProjectToNodes)
                {
                    // we need to inject the team name as a folder in the structure too
                    fixedQueryText = fixedQueryText.Replace($"{Engine.Target.Config.Project}\\", $"{Engine.Target.Config.Project}\\{Engine.Source.Config.Project}\\");
                }

                if (config.SourceToTargetFieldMappings != null)
                {
                    foreach (var sourceField in config.SourceToTargetFieldMappings.Keys)
                    {
                        fixedQueryText = query.QueryText.Replace($"{sourceField}", $"'{config.SourceToTargetFieldMappings[sourceField]}");
                    }
                }

                // you cannot just add an item from one store to another, we need to create a new object
                var queryCopy = new QueryDefinition(query.Name, fixedQueryText);
                this.totalQueriesAttempted++;
                Trace.WriteLine($"Migrating query '{query.Name}'");
                parentFolder.Add(queryCopy);
                try
                {
                    targetHierarchy.Save(); // moved the save here for better error message
                    this.totalQueriesMigrated++;
                }
                catch (Exception ex)
                {
                    this.totalQueryFailed++;
                    Trace.WriteLine($"Error saving query '{query.Name}', probably due to invalid area or iteration paths");
                    Trace.WriteLine($"Source Query: '{query}'");
                    Trace.WriteLine($"Target Query: '{fixedQueryText}'");
                    Trace.WriteLine(ex.Message);
                    targetHierarchy.Refresh(); // get the tree without the last edit
                }
            }
        }
        public void QueryById()
        {
            // Querying by ID doesn't really exist in the WIT model like it does in REST.
            // In this case, we are looking up the query definition by its ID and then creating a new Query with its corresponding wiql

            // Get an existing query and associated ID for proof of concept. If we already have a query guid, we can skip this block.
            QueryHierarchy queryHierarchy  = TeamProject.QueryHierarchy;
            var            queryFolder     = queryHierarchy as QueryFolder;
            QueryItem      queryItem       = queryFolder?.Where(f => f.IsPersonal).FirstOrDefault();
            QueryFolder    myQueriesFolder = queryItem as QueryFolder;

            if (myQueriesFolder != null && myQueriesFolder.Count > 0)
            {
                var queryId = myQueriesFolder.First().Id; // Replace this value with your query id

                // Get the query definition
                var queryDefinitionById = WIStore.GetQueryDefinition(queryId);
                var context             = new Dictionary <string, string>()
                {
                    { "project", TeamProject.Name }
                };

                // Obtain query results using the query definition's QueryText
                Query obj = new Query(this.WIStore, queryDefinitionById.QueryText, context);
                WorkItemCollection queryResults = obj.RunQuery();
                Console.WriteLine($"Query with name: '{queryDefinitionById.Name}' and id: '{queryDefinitionById.Id}' returned {queryResults.Count} results:");
                if (queryResults.Count > 0)
                {
                    foreach (WorkItem result in queryResults)
                    {
                        Console.WriteLine($"WorkItem Id: '{result.Id}' Title: '{result.Title}'");
                    }
                }
                else
                {
                    Console.WriteLine($"Query with name: '{queryDefinitionById.Name}' and id: '{queryDefinitionById.Id}' did not return any results.");
                    Console.WriteLine($"Try assigning work items to yourself or following work items and run the sample again.");
                }
            }

            else
            {
                Console.WriteLine("My Queries haven't been populated yet. Open up the Queries page in the browser to populate these, and then run the sample again.");
            }

            Console.WriteLine();
        }
        public List <string> GetAvailableQueries(string projectName, string queryFolderName)
        {
            List <string> result = new List <string>();

            try
            {
                QueryHierarchy queryRoot = store.Projects[projectName].QueryHierarchy;
                var            entity    = queryRoot[queryFolderName];
                QueryFolder    root      = (QueryFolder)queryRoot[queryFolderName];
                var            queries   = GetQueries(root);
                return(queries.Select(o => o.Name).ToList());
            }
            catch (Exception ex)
            {
                Exception exception = new Exception("Make sure you set TfsURL before calling this method, and that the query is valid. Check inner exception for more details.", ex);
                throw exception;
            }
        }
        public List <string> GetAvailableQueryFolders(string projectName)
        {
            List <string> result = new List <string>();

            try
            {
                QueryHierarchy queryRoot = store.Projects[projectName].QueryHierarchy;

                foreach (QueryFolder folder in queryRoot)
                {
                    result.Add(folder.Name);
                }

                return(result);
            }
            catch (Exception ex)
            {
                Exception exception = new Exception("Make sure you set TfsURL before calling this method, and that the query is valid. Check inner exception for more details.", ex);
                throw exception;
            }
        }
        private void BuildQueryHierarchy(QueryHierarchy QueryHierarchy, string project)
        {
            var rootContent = new StackPanel {
                Orientation = Orientation.Horizontal, Margin = new Thickness(4)
            };
            var lbl = new TextBlock {
                Text = project, FontSize = 15
            };

            rootContent.Children.Add(lbl);

            var root = new TreeViewItem {
                IsExpanded = true, Header = rootContent
            };

            foreach (QueryFolder query in QueryHierarchy)
            {
                DefineFolder(query, root);
            }
            Queries.Items.Add(root);
        }
        private void btnSelectProject_Click(object sender, EventArgs e)
        {
            var          tfsPp  = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false, new UICredentialsProvider());
            DialogResult result = tfsPp.ShowDialog();

            if (result == DialogResult.OK && tfsPp.SelectedProjects != null && tfsPp.SelectedProjects.FirstOrDefault() != null)
            {
                ClearExisting();
                rtxtLog.AppendTextWithNewLine("Connected to " + tfsPp.SelectedTeamProjectCollection, Color.Green);
                rtxtLog.AppendTextWithNewLine("Connected to " + tfsPp.SelectedProjects.FirstOrDefault().Name, Color.Green);
                try
                {
                    _workItemStore = (WorkItemStore)tfsPp.SelectedTeamProjectCollection.GetService(typeof(WorkItemStore));
                    ProjectInfo firstOrDefault = tfsPp.SelectedProjects.FirstOrDefault();
                    if (firstOrDefault != null && _workItemStore != null)
                    {
                        _tfsProject = _workItemStore.Projects[firstOrDefault.Name];
                    }
                    QueryHierarchy queryHierarchy = _tfsProject.QueryHierarchy; // if it's null, check your permission
                    var            queryFolder    = queryHierarchy as QueryFolder;
                    QueryItem      myQueryItem    = queryFolder.FirstOrDefault();
                    _myQueryFolder = myQueryItem as QueryFolder;
                    if (_myQueryFolder != null && _myQueryFolder.Count > 0)
                    {
                        lbxQueries.Items.Clear();
                        foreach (var item in _myQueryFolder)
                        {
                            lbxQueries.Items.Add(item.Name);
                        }
                        rtxtLog.AppendTextWithNewLine("Retrieved " + _myQueryFolder.Count + " Queries From My Queries Folder", Color.Green);
                        return;
                    }
                    rtxtLog.AppendTextWithNewLine("No Queries in My Queries Folder", Color.DarkOrange);
                }
                catch (Exception exception)
                {
                    rtxtLog.AppendTextWithNewLine(Utilities.ReadException(exception), Color.Red);
                }
            }
        }
        public IEnumerable <IWorkItemSummary> GetWorkItemsBySavedQuery(string projectName, string queryFolderName, string queryName)
        {
            try
            {
                QueryHierarchy          queryRoot = store.Projects[projectName].QueryHierarchy;
                QueryFolder             folder    = (QueryFolder)queryRoot[queryFolderName];
                QueryDefinition         query1    = (QueryDefinition)folder[queryName];
                WorkItemCollection      queryResultsqueryResults = store.Query(query1.QueryText);
                List <IWorkItemSummary> result = new List <IWorkItemSummary>();

                foreach (WorkItem workItem in queryResultsqueryResults)
                {
                    result.Add(new DefaultWorkItemSummary(workItem));
                }

                return(result);
            }
            catch (Exception ex)
            {
                Exception exception = new Exception("Make sure you set TfsURL before calling this method, and that the query is valid. Check inner exception for more details.", ex);
                throw exception;
            }
        }
        public void SetTeamQueries(QueryHierarchy sourceQueryCol, string sourceProjectName)
        {
            foreach (QueryFolder queryFolder in sourceQueryCol)
            {
                if (queryFolder.Name == "Team Queries" || queryFolder.Name == "Shared Queries")
                {
                    QueryFolder teamQueriesFolder = null;

                    foreach (var localSharedQueryString in _sharedQueriesString)
                    {
                        if (store.Projects[projectName].QueryHierarchy.Contains(localSharedQueryString))
                        {
                            teamQueriesFolder = (QueryFolder)store.Projects[projectName].QueryHierarchy[localSharedQueryString];
                        }
                    }

                    if (teamQueriesFolder != null)
                    {
                        SetQueryItem(queryFolder, teamQueriesFolder, sourceProjectName);
                    }
                }
            }
        }
        private void BuildQueryHierarchy(QueryHierarchy QueryHierarchy, string project)
        {
            var rootContent = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(4) };
              var lbl = new TextBlock{ Text = project, FontSize = 15 };
              rootContent.Children.Add(lbl);

              var root = new TreeViewItem {IsExpanded = true, Header = rootContent};
              foreach (QueryFolder query in QueryHierarchy)
              {
            DefineFolder(query, root);
              }
              Queries.Items.Add(root);
        }
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values == null)
            {
                return(DependencyProperty.UnsetValue);
            }
            if (values.Length < 2)
            {
                return(DependencyProperty.UnsetValue);
            }

            QueryFolder     folder     = values[0] as QueryFolder;
            QueryHierarchy  hierarchy  = values[0] as QueryHierarchy;
            QueryDefinition definition = values[0] as QueryDefinition;

            string imagePath = TeamExplorerFolderCollapsed;


            bool isExpandend = values[1] is bool?(bool)values[1] : false;

            if (definition != null)
            {
                switch (definition.QueryType)
                {
                case QueryType.Invalid:
                    imagePath = TeamExplorerNoWorkItems;
                    break;

                case QueryType.List:
                    imagePath = TeamExplorerFlatList;
                    break;

                case QueryType.OneHop:
                    imagePath = TeamExplorerDirectLink;
                    break;

                case QueryType.Tree:
                    imagePath = TeamExplorerTree;
                    break;

                default:
                    imagePath = Error;
                    break;
                }
            }
            else if (folder != null)
            {
                hierarchy = folder.Parent as QueryHierarchy;
                if (hierarchy != null)
                {
                    // Our parent is the hierarchy so we are either My Queries or Team Queries
                    imagePath = folder.IsPersonal ? TeamExplorerMyQueries : TeamExplorerTeamQueries;
                }
                else
                {
                    imagePath = isExpandend ? TeamExplorerFolderExpanded : TeamExplorerFolderCollapsed;
                }
            }
            else if (hierarchy != null)
            {
                imagePath = TeamExplorerWorkItemsRoot;
            }

            try
            {
                return(new BitmapImage(new Uri(imagePath, UriKind.Relative)));
            }
            catch
            {
                return(DependencyProperty.UnsetValue);
            }
        }
        public void SetTeamQueries(QueryHierarchy sourceQueryCol, string sourceProjectName)
        {
            foreach (QueryFolder queryFolder in sourceQueryCol)
            {
                if (queryFolder.Name == "Team Queries" || queryFolder.Name == "Shared Queries")
                {
                    QueryFolder teamQueriesFolder = (QueryFolder)store.Projects[projectName].QueryHierarchy["Shared Queries"];
                    SetQueryItem(queryFolder, teamQueriesFolder, sourceProjectName);

                    QueryFolder test = (QueryFolder)store.Projects[projectName].QueryHierarchy["Shared Queries"];
                }

            }
        }
Beispiel #33
0
        static partial void RealInstanceFactory(ref QueryHierarchy real, string callerName)
        {
            var project = ProjectWrapper_UnitTests.GetRealInstance();

            real = project.QueryHierarchy;
        }
 public void BuildQueryTree(QueryHierarchy queryHierarchy, string project)
 {
     projectName = project;
     BuildQueryHierarchy(queryHierarchy, project);
 }
        private void BuildQueryHierarchy(ProjectInfo project, QueryHierarchy queryHierarchy)
        {
            tvwQueries.Nodes.Clear();

            var root = new TreeNode(project.Name);
            foreach (QueryFolder query in queryHierarchy)
            {
                DefineFolder(query, root);
            }

            tvwQueries.Nodes.Add(root);
        }
        /// <summary>
        /// Define Query Folders under the current parent
        /// </summary>
        /// <param name="targetHierarchy">The object that represents the whole of the target query tree</param>
        /// <param name="sourceFolder">The source folder in tree on source instance</param>
        /// <param name="parentFolder">The target folder in tree on target instance</param>
        private void MigrateFolder(QueryHierarchy targetHierarchy, QueryFolder sourceFolder, QueryFolder parentFolder)
        {
            // We only migrate non-private folders and their contents
            if (sourceFolder.IsPersonal)
            {
                Log.LogInformation("Found a personal folder {sourceFolderName}. Migration only available for shared Team Query folders", sourceFolder.Name);
            }
            else
            {
                this.totalFoldersAttempted++;

                // we need to replace the team project name in folder names as it included in query paths
                var requiredPath = sourceFolder.Path.Replace($"{Source.Project}/", $"{Target.Project}/");

                // Is the project name to be used in the migration as an extra folder level?
                if (_Options.PrefixProjectToNodes == true)
                {
                    // we need to inject the team name as a folder in the structure
                    requiredPath = requiredPath.Replace(_Options.SharedFolderName, $"{_Options.SharedFolderName}/{Source.Project}");

                    // If on the root level we need to check that the extra folder has already been added
                    if (sourceFolder.Path.Count(f => f == '/') == 1)
                    {
                        var         targetSharedFolderRoot = (QueryFolder)parentFolder[_Options.SharedFolderName];
                        QueryFolder extraFolder            = (QueryFolder)targetSharedFolderRoot.FirstOrDefault(q => q.Path == requiredPath);
                        if (extraFolder == null)
                        {
                            // we are at the root level on the first pass and need to create the extra folder for the team name
                            Log.LogInformation("Adding a folder '{Project}'", Source.Project);
                            extraFolder = new QueryFolder(Source.Project);
                            targetSharedFolderRoot.Add(extraFolder);
                            targetHierarchy.Save(); // moved the save here a more immediate and relavent error message
                        }

                        // adjust the working folder to the newly added one
                        parentFolder = targetSharedFolderRoot;
                    }
                }

                // check if there is a folder of the required name, using the path to make sure it is unique
                QueryFolder targetFolder = (QueryFolder)parentFolder.FirstOrDefault(q => q.Path == requiredPath);
                if (targetFolder != null)
                {
                    Log.LogInformation("Skipping folder '{sourceFolderName}' as already exists", sourceFolder.Name);
                }
                else
                {
                    Log.LogInformation("Migrating a folder '{sourceFolderName}'", sourceFolder.Name);
                    targetFolder = new QueryFolder(sourceFolder.Name);
                    parentFolder.Add(targetFolder);
                    targetHierarchy.Save(); // moved the save here a more immediate and relavent error message
                }

                // Process child items
                foreach (QueryItem sub_query in sourceFolder)
                {
                    if (sub_query.GetType() == typeof(QueryFolder))
                    {
                        MigrateFolder(targetHierarchy, (QueryFolder)sub_query, (QueryFolder)targetFolder);
                    }
                    else
                    {
                        MigrateQuery(targetHierarchy, (QueryDefinition)sub_query, (QueryFolder)targetFolder);
                    }
                }
            }
        }
Beispiel #37
0
 static partial void RealInstanceFactory(ref QueryHierarchy real, [CallerMemberName] string callerName        = "");
 public void BuildQueryTree(QueryHierarchy queryHierarchy, string project)
 {
     projectName = project;
       BuildQueryHierarchy(queryHierarchy, project);
 }
        public void SetTeamQueries(QueryHierarchy sourceQueryCol, string sourceProjectName)
        {
            foreach (QueryFolder queryFolder in sourceQueryCol)
            {
                if (queryFolder.Name == "Team Queries" || queryFolder.Name == "Shared Queries")
                {
                    QueryFolder teamQueriesFolder = null;

                    foreach (var localSharedQueryString in _sharedQueriesString)
                    {
                        if (store.Projects[projectName].QueryHierarchy.Contains(localSharedQueryString))
                            teamQueriesFolder = (QueryFolder)store.Projects[projectName].QueryHierarchy[localSharedQueryString];
                    }

                    if (teamQueriesFolder != null)
                        SetQueryItem(queryFolder, teamQueriesFolder, sourceProjectName);
                }
            }
        }