private void FixQueryForTeamProjectNameChange(ITestSuiteBase source, IDynamicTestSuite targetSuiteChild, TestManagementContext targetTestStore)
 {
     // Replacing old projectname in queries with new projectname
     // The target team project name is only available via target test store because the dyn. testsuite isnt saved at this point in time
     if (!source.Plan.Project.TeamProjectName.Equals(targetTestStore.Project.TeamProjectName))
     {
         Trace.WriteLine(string.Format(@"Team Project names dont match. We need to fix the query in dynamic test suite {0} - {1}.", source.Id, source.Title));
         Trace.WriteLine(string.Format(@"Replacing old project name {1} in query {0} with new team project name {2}", targetSuiteChild.Query.QueryText, source.Plan.Project.TeamProjectName, targetTestStore.Project.TeamProjectName));
         // First need to check is prefix project nodes has been applied for the migration
         if (config.PrefixProjectToNodes)
         {
             // if prefix project nodes has been applied we need to take the original area/iteration value and prefix
             targetSuiteChild.Query =
                 targetSuiteChild.Project.CreateTestQuery(targetSuiteChild.Query.QueryText.Replace(
                                                              string.Format(@"'{0}", source.Plan.Project.TeamProjectName),
                                                              string.Format(@"'{0}\{1}", targetTestStore.Project.TeamProjectName, source.Plan.Project.TeamProjectName)));
         }
         else
         {
             // If we are not profixing project nodes then we just need to take the old value for the project and replace it with the new project value
             targetSuiteChild.Query = targetSuiteChild.Project.CreateTestQuery(targetSuiteChild.Query.QueryText.Replace(
                                                                                   string.Format(@"'{0}", source.Plan.Project.TeamProjectName),
                                                                                   string.Format(@"'{0}", targetTestStore.Project.TeamProjectName)));
         }
         Trace.WriteLine(string.Format("New query is now {0}", targetSuiteChild.Query.QueryText));
     }
 }
Exemple #2
0
        void WriteRootSuite(IDynamicTestSuite testSuite, XmlDocument xmlDoc)
        {
            XmlNode rootNode = xmlDoc.CreateElement("suite");

            xmlDoc.AppendChild(rootNode);

            XmlNode idNode = xmlDoc.CreateElement("id");

            rootNode.AppendChild(idNode);

            XmlNode rootnameNode = xmlDoc.CreateElement("name");

            rootnameNode.InnerText = testSuite.Plan.Name;
            rootNode.AppendChild(rootnameNode);

            XmlNode rootdescNode = xmlDoc.CreateElement("description");

            rootdescNode.InnerText = testSuite.Plan.Description;
            rootNode.AppendChild(rootdescNode);

            XmlNode sectionsNode = xmlDoc.CreateElement("sections");

            rootNode.AppendChild(sectionsNode);
            GetTestCases(testSuite, xmlDoc, sectionsNode);
        }
Exemple #3
0
        private void UpdateQueryConditionsToSuite(IDynamicTestSuite suite, string replaced, string replacing)
        {
            bool hasReplacedString = true;

            try
            {
                if (!suite.Query.QueryText.Contains(replaced))
                {
                    hasReplacedString = false;
                    goto Out;
                }
                string newQuery = suite.Query.QueryText.Replace(replaced, replacing);

                suite.Query = _client.TeamProject.CreateTestQuery(newQuery);

                Console.WriteLine("Test Suite \"{0}\" the query string now is:\n{1}", suite.Title, newQuery);
            }
            catch (Exception e)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine(
                    $"Test Suite \"{suite.Title}\" with ID \"{suite.Id}\" meets errors:{e.InnerException.Message}");
                Console.ResetColor();
            }
Out:
            if (!hasReplacedString)
            {
                throw new TestObjectNotFoundException($"Replaced query condition \"{replaced}\" not found");
            }
        }
        private void ApplyTestSuiteQuery(ITestSuiteBase source, IDynamicTestSuite targetSuiteChild, TestManagementContext targetTestStore)
        {
            targetSuiteChild.Query = ((IDynamicTestSuite)source).Query;

            // Postprocessing common errors
            FixQueryForTeamProjectNameChange(source, targetSuiteChild, targetTestStore);
            FixWorkItemIdInQuery(targetSuiteChild);
        }
Exemple #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TfsTestSuite"/> class.
 /// </summary>
 /// <param name="testSuite">Original test suite - <see cref="IDynamicTestSuite"/>.</param>
 public TfsTestSuite(IDynamicTestSuite testSuite, ITfsTestPlan associatedTestPlan)
 {
     AssociatedTestPlan       = associatedTestPlan;
     OriginalDynamicTestSuite = testSuite;
     Id    = OriginalDynamicTestSuite.Id;
     Title = OriginalDynamicTestSuite.Title;
     InitializeChildSuites();
 }
        private ITestSuiteBase CreateNewDynamicTestSuite(ITestSuiteBase source)
        {
            IDynamicTestSuite targetSuiteChild = targetTestStore.Project.TestSuites.CreateDynamic();

            targetSuiteChild.TestSuiteEntry.Title = source.TestSuiteEntry.Title;
            ApplyTestSuiteQuery(source, targetSuiteChild, targetTestStore);

            return(targetSuiteChild);
        }
Exemple #7
0
        private void GetTestCases(IDynamicTestSuite dynamicTestSuite, XmlDocument xmlDoc, XmlNode node) //sectionsNode has to be "sections"
        {
            var casesNode = WriteSuite(dynamicTestSuite, xmlDoc, node);

            foreach (var testCase in dynamicTestSuite.AllTestCases)
            {
                var caseNode = WriteTestCase(testCase, xmlDoc);
                casesNode.AppendChild(caseNode);
            }
        }
Exemple #8
0
        private string AddQueryConditionsToSuite(IDynamicTestSuite suite, string query)
        {
            string newQuery = null;

            try
            {
                string queryWithoutOrder;
                string order;

                if (suite.Query.QueryText.Contains("order by"))
                {
                    queryWithoutOrder = suite.Query.QueryText
                                        .Substring(0, suite.Query.QueryText
                                                   .IndexOf("order", StringComparison.InvariantCultureIgnoreCase) - 1);
                    order = suite.Query.QueryText
                            .Substring(suite.Query.QueryText
                                       .IndexOf("order", StringComparison.InvariantCultureIgnoreCase));
                }
                else
                {
                    queryWithoutOrder = suite.Query.QueryText;
                    order             = string.Empty;
                }

                if (suite.Query.QueryText.Contains("where"))
                {
                    newQuery = queryWithoutOrder + " " + query + " " + order;
                }
                else
                {
                    if (query.StartsWith("and", StringComparison.CurrentCultureIgnoreCase))
                    {
                        query = query.Substring(4);
                    }
                    if (query.StartsWith("or", StringComparison.CurrentCultureIgnoreCase))
                    {
                        query = query.Substring(3);
                    }
                    newQuery = queryWithoutOrder + " where " + query + " " + order;
                }
                suite.Query = _client.TeamProject.CreateTestQuery(newQuery);

                suite.Plan.Save();
                Console.WriteLine("Test Suite \"{0}\" the query string now is:\n{1}", suite.Title, newQuery);
            }
            catch (Exception e)
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"Test Suite \"{suite.Title}\" with ID \"{suite.Id}\" meets errors:{e.InnerException.Message}");
                Console.ResetColor();
            }
            return(newQuery);
        }
Exemple #9
0
        private ITestSuiteBase CreateNewDynamicTestSuite(ITestSuiteBase source)
        {
            IDynamicTestSuite targetSuitChild = targetTestStore.Project.TestSuites.CreateDynamic();

            if (source.TestSuiteEntry.Configurations != null)
            {
                ApplyConfigurations(source, targetSuitChild);
            }
            targetSuitChild.TestSuiteEntry.Title = source.TestSuiteEntry.Title;
            targetSuitChild.Query = ((IDynamicTestSuite)source).Query;
            return(targetSuitChild);
        }
        private List <TestObjectViewModel> RecursiveSuiteCollector(TestObjectViewModel item, ITestSuiteBase suite,
                                                                   List <TestObjectViewModel> selectedItems)
        {
            IStaticTestSuite      staticSuite     = null;
            IDynamicTestSuite     dynamicSuite    = null;
            IRequirementTestSuite requirmentSuite = null;
            ITestSuiteBase        suiteBase       = TfsShared.Instance.SourceTestProject.TestSuites.Find(item.ID);

            if (suiteBase.TestSuiteType == TestSuiteType.StaticTestSuite)
            {
                staticSuite = (IStaticTestSuite)suiteBase;
                if (item.IsChecked)
                {
                    selectedItems.AddRange(staticSuite.TestCases.Select(test => new TestObjectViewModel(test)
                    {
                        TestSuiteId = suite.Id
                    }));
                    if (staticSuite.SubSuites.Count > 0)
                    {
                        foreach (ITestSuiteBase subSuite in staticSuite.SubSuites)
                        {
                            var children = item.Children.Where(t => t.ID > 0 && t.ID == subSuite.Id);
                            if (children.Count() > 0)
                            {
                                RecursiveSuiteCollector(children.First(), subSuite, selectedItems);
                            }
                        }
                    }
                }
            }
            else if ((suite.TestSuiteType == TestSuiteType.DynamicTestSuite) && (item.IsChecked))
            {
                dynamicSuite = (IDynamicTestSuite)suite;
                selectedItems.AddRange(dynamicSuite.TestCases.Select(test => new TestObjectViewModel(test)
                {
                    TestSuiteId = suite.Id
                }));
            }
            else if ((suite.TestSuiteType == TestSuiteType.RequirementTestSuite) && (item.IsChecked))
            {
                requirmentSuite = (IRequirementTestSuite)suite;
                selectedItems.AddRange(requirmentSuite.TestCases.Select(test => new TestObjectViewModel(test)
                {
                    TestSuiteId = suite.Id
                }));
            }

            return(selectedItems);
        }
 private void ValidateAndFixTestSuiteQuery(ITestSuiteBase source, IDynamicTestSuite targetSuiteChild,
                                           TestManagementContext targetTestStore)
 {
     try
     {
         // Verifying that the query is valid
         targetSuiteChild.Query.Execute();
     }
     catch (Exception e)
     {
         FixIterationNotFound(e, source, targetSuiteChild, targetTestStore);
     }
     finally
     {
         targetSuiteChild.Repopulate();
     }
 }
Exemple #12
0
        public string GetSuiteQuery(string suiteId)
        {
            var id    = Int32.Parse(suiteId);
            var suite = GetSuiteById(id);

            if (suite == null)
            {
                throw new TestObjectNotFoundException(
                          $"Test suite with ID:{suiteId} is not found.");
            }
            if (suite is IDynamicTestSuite)
            {
                IDynamicTestSuite dynamicTestSuite = suite as IDynamicTestSuite;
                return(dynamicTestSuite.Query.QueryText);
            }
            throw new TestObjectNotFoundException(
                      $"Test suite with ID:{suiteId} is not query based test suite.");
        }
Exemple #13
0
        XmlNode WriteSuite(IDynamicTestSuite testSuite, XmlDocument xmlDoc, XmlNode node) //sectionsNode has to be "sections"
        {
            XmlNode sectionNode = xmlDoc.CreateElement("section");

            node.AppendChild(sectionNode);
            XmlNode nameNode = xmlDoc.CreateElement("name");

            nameNode.InnerText = testSuite.Title;
            sectionNode.AppendChild(nameNode);
            XmlNode descNode = xmlDoc.CreateElement("description");

            sectionNode.AppendChild(descNode);
            XmlNode casesNode = xmlDoc.CreateElement("cases");

            sectionNode.AppendChild(casesNode);

            return(casesNode);
        }
Exemple #14
0
        private void ApplyTestSuiteQuery(ITestSuiteBase source, IDynamicTestSuite targetSuitChild, TestManagementContext targetTestStore)
        {
            targetSuitChild.Query = ((IDynamicTestSuite)source).Query;

            // Replacing old projectname in queries with new projectname
            // The target team project name is only available via target test store because the dyn. testsuite isnt saved at this point in time
            if (!source.Plan.Project.TeamProjectName.Equals(targetTestStore.Project.TeamProjectName))
            {
                Trace.WriteLine(string.Format(@"Team Project names dont match. We need to fix the query in dynamic test suite {0} - {1}.", source.Id, source.Title));
                Trace.WriteLine(string.Format(@"Replacing old project name {1} in query {0} with new team project name {2}",
                                              targetSuitChild.Query.QueryText,
                                              source.Plan.Project.TeamProjectName,
                                              targetTestStore.Project.TeamProjectName
                                              ));

                // it is possible that user has used project name in query values. we try only to change iteration + area path values
                // A child level is selected in area / iteration path
                targetSuitChild.Query = targetSuitChild.Project.CreateTestQuery(
                    targetSuitChild.Query.QueryText.Replace(
                        string.Format(@"'{0}\", source.Plan.Project.TeamProjectName),
                        string.Format(@"'{0}\", targetTestStore.Project.TeamProjectName)
                        ));

                // Only root level is selected in area / iteration path
                targetSuitChild.Query = targetSuitChild.Project.CreateTestQuery(
                    targetSuitChild.Query.QueryText.Replace(
                        string.Format(@"'{0}'", source.Plan.Project.TeamProjectName),
                        string.Format(@"'{0}'", targetTestStore.Project.TeamProjectName)
                        ));

                try
                {
                    // Verifying that the query is valid
                    targetSuitChild.Query.Execute();
                }
                catch (Exception e)
                {
                    FixIterationNotFound(e, source, targetSuitChild, targetTestStore);
                }


                Trace.WriteLine(string.Format("New query is now {0}", targetSuitChild.Query.QueryText));
            }
        }
Exemple #15
0
        public string GetSuiteQuery(string testPlanName, string testSuiteName)
        {
            ITestSuiteBase suite = GetSuites(testPlanName, testSuiteName)
                                   .FirstOrDefault(
                s =>
                s.TestSuiteType.Equals(TestSuiteType.DynamicTestSuite));

            if (suite == null)
            {
                throw new TestObjectNotFoundException(
                          String
                          .Format(
                              "Could not find query based test suite {0} .",
                              testSuiteName));
            }
            IDynamicTestSuite dynamicTestSuite = suite as IDynamicTestSuite;

            return(dynamicTestSuite.Query.QueryText);
        }
Exemple #16
0
        //Copy all Test suites from source plan to destination plan.
        private void CopyTestSuites(ITestPlan sourceplan, ITestPlan destinationplan)
        {
            ITestSuiteEntryCollection suites = sourceplan.RootSuite.Entries;

            CopyTestCases(sourceplan.RootSuite, destinationplan.RootSuite);

            foreach (ITestSuiteEntry suite_entry in suites)
            {
                if (suite_entry.TestSuite is IStaticTestSuite suite)
                {
                    IStaticTestSuite newSuite = targetTestMgmtProj.TestSuites.CreateStatic();
                    newSuite.Title = suite.Title;
                    destinationplan.RootSuite.Entries.Add(newSuite);
                    destinationplan.Save();

                    CopyTestCases(suite, newSuite);
                    if (suite.Entries.Count > 0)
                    {
                        CopySubTestSuites(suite, newSuite);
                    }
                }
                else
                {
                    if (suite_entry.TestSuite is IDynamicTestSuite dynamicSuite)
                    {
                        IDynamicTestSuite newDynamicSuit = targetTestMgmtProj.TestSuites.CreateDynamic();
                        newDynamicSuit.Title = dynamicSuite.Title;
                        //newDynamicSuit.Query = dynamicSuite.Query;

                        var text = ReplaceAreaPath(dynamicSuite.Query.QueryText);
                        text = ReplaceIterationPath(text);

                        var newQuery = targetTestMgmtProj.CreateTestQuery(text);

                        newDynamicSuit.Query = newQuery;

                        destinationplan.RootSuite.Entries.Add(newDynamicSuit);
                        destinationplan.Save();
                    }
                }
            }
        }
Exemple #17
0
 private void GetAllQueryBasedTestSuiteFromSuiteNode(ITestSuiteEntryCollection suiteCollection, List <IDynamicTestSuite> dynamicTestSuites)
 {
     foreach (var suiteEntry in suiteCollection)
     {
         if (suiteEntry.TestSuite != null)
         {
             if (suiteEntry.TestSuite.TestSuiteType == TestSuiteType.DynamicTestSuite)
             {
                 IDynamicTestSuite suite = suiteEntry.TestSuite as IDynamicTestSuite;
                 dynamicTestSuites.Add(suite);
             }
             else if (suiteEntry.TestSuite.TestSuiteType == TestSuiteType.StaticTestSuite)
             {
                 IStaticTestSuite parentStaticSuite = suiteEntry.TestSuite as IStaticTestSuite;
                 if (parentStaticSuite != null)
                 {
                     GetAllQueryBasedTestSuiteFromSuiteNode(parentStaticSuite.Entries, dynamicTestSuites);
                 }
             }
         }
     }
 }
Exemple #18
0
        //Drill down and Copy all subTest suites from source root test suite to destination plan's root test suites.
        private void CopySubTestSuites(IStaticTestSuite parentsourceSuite, IStaticTestSuite parentdestinationSuite)
        {
            ITestSuiteEntryCollection suitcollection = parentsourceSuite.Entries;

            foreach (ITestSuiteEntry suite_entry in suitcollection)
            {
                if (suite_entry.TestSuite is IStaticTestSuite suite)
                {
                    IStaticTestSuite subSuite = targetTestMgmtProj.TestSuites.CreateStatic();
                    subSuite.Title = suite.Title;
                    parentdestinationSuite.Entries.Add(subSuite);

                    CopyTestCases(suite, subSuite);

                    if (suite.Entries.Count > 0)
                    {
                        CopySubTestSuites(suite, subSuite);
                    }
                }
                else
                {
                    if (suite_entry.TestSuite is IDynamicTestSuite dynamicSuite)
                    {
                        IDynamicTestSuite newDynamicSuit = targetTestMgmtProj.TestSuites.CreateDynamic();
                        newDynamicSuit.Title = dynamicSuite.Title;

                        var text = ReplaceAreaPath(dynamicSuite.Query.QueryText);
                        text = ReplaceIterationPath(text);

                        var newQuery = targetTestMgmtProj.CreateTestQuery(text);

                        newDynamicSuit.Query = newQuery;
                    }
                }
            }
        }
        private async Task DuplicateTestCases(List <TestObjectViewModel> selectedItems, bool duplicate)
        {
            await Task.Factory.StartNew(() =>
            {
                TestObjectViewModel selectedSuite = null;
                selectedSuite = HasSelectedItem(_mappingViewModel.TestPlans, selectedSuite);

                ITestPlan plan =
                    TfsShared.Instance.TargetTestProject.TestPlans.Find(selectedSuite._testObject.TestPlanID);

                try
                {
                    foreach (TestObjectViewModel test in selectedItems)
                    {
                        var parentTestSuites       = new Stack();
                        ITestSuiteBase sourceSuite =
                            TfsShared.Instance.SourceTestProject.TestSuites.Find(test.TestSuiteId);

                        ITestCase testCase      = TfsShared.Instance.SourceTestProject.TestCases.Find(test.ID);
                        WorkItem targetWorkItem = null;
                        #region Create duplicate test cases
                        if (duplicate)
                        {
                            WorkItem duplicateWorkItem = null;
                            //if (!DuplicatedTestCase.Any(t => t.OldID.Equals(test.ID)))
                            //{
                            if ((sourceSuite.TestSuiteType != TestSuiteType.RequirementTestSuite) && (sourceSuite.TestSuiteType != TestSuiteType.DynamicTestSuite))
                            {
                                duplicateWorkItem = testCase.WorkItem.Copy(TfsShared.Instance.TargetProjectWorkItemType,
                                                                           WorkItemCopyFlags.CopyFiles);
                                //duplicateWorkItem.WorkItemLinks.Clear();

                                if (!duplicateWorkItem.IsValid())
                                {
                                    Logger = "Cannot Save Work Item - Stoping Migration\n" + Logger;
                                    ArrayList badFields = duplicateWorkItem.Validate();
                                    foreach (Field field in badFields)
                                    {
                                        Logger =
                                            string.Format("Name: {0}, Reference Name: {1},  Invalid Value: {2}\n",
                                                          field.Name, field.ReferenceName, field.Value) + Logger;
                                    }

                                    break;
                                }
                                else
                                {
                                    duplicateWorkItem.Save();

                                    //App.Current.Dispatcher.Invoke(() =>
                                    //{
                                    //    DuplicatedTestCase.Add(new TestCaseOldNewMapping()
                                    //    {
                                    //        OldID = testCase.Id,
                                    //        NewID = duplicateWorkItem.Id
                                    //    });
                                    //});

                                    Logger =
                                        string.Format("Duplicate Test Case: {0} completed, new Test Case ID: {1}\n",
                                                      test.ID,
                                                      duplicateWorkItem.Id) + Logger;
                                }
                            }
                            //}
                            //else
                            //{
                            //    TestCaseOldNewMapping mapping =
                            //        DuplicatedTestCase.FirstOrDefault(t => t.OldID.Equals(test.ID));
                            //    if (mapping == null) throw new NullReferenceException("Cannot locate new id");
                            //    duplicateWorkItem =
                            //        TfsShared.Instance.TargetTestProject.TestCases.Find(mapping.NewID).WorkItem;

                            //    Logger =
                            //        string.Format("Test Case: {0} already exists, Test Case ID: {1}\n", test.ID,
                            //            duplicateWorkItem.Id) + Logger;
                            //}

                            targetWorkItem = duplicateWorkItem;
                        }
                        else
                        {
                            targetWorkItem = testCase.WorkItem;
                        }
                        #endregion
                        ITestSuiteBase suite = sourceSuite;
                        while (suite != null)
                        {
                            parentTestSuites.Push(suite);
                            suite = suite.TestSuiteEntry.ParentTestSuite;
                        }

                        parentTestSuites.Pop();                                                      //Source tree parent suites

                        var parentSuite = (IStaticTestSuite)selectedSuite._testObject.TestSuiteBase; //Selected target suite
                        bool isTestCaseParentRequirementTestSuite = false;
                        bool isTestCaseParentDynamicTestSuite     = false;
                        foreach (ITestSuiteBase testSuite in parentTestSuites)
                        {
                            ITestSuiteBase existingSuite         = null;
                            isTestCaseParentRequirementTestSuite = false;
                            isTestCaseParentDynamicTestSuite     = false;
                            if (testSuite.TestSuiteType == TestSuiteType.RequirementTestSuite)
                            {
                                isTestCaseParentRequirementTestSuite = true;
                            }
                            if (testSuite.TestSuiteType == TestSuiteType.DynamicTestSuite)
                            {
                                isTestCaseParentDynamicTestSuite = true;
                            }

                            if (parentSuite.Title.Equals(testSuite.Title))
                            {
                                existingSuite = parentSuite;
                            }
                            else if (parentSuite.SubSuites.FirstOrDefault(t => t.Title.Equals(testSuite.Title)) != null)
                            {
                                var subSuite = parentSuite.SubSuites.FirstOrDefault(t => t.Title.Equals(testSuite.Title));

                                if (subSuite.TestSuiteType == TestSuiteType.StaticTestSuite)
                                {
                                    parentSuite = (IStaticTestSuite)parentSuite.SubSuites.FirstOrDefault(t => t.Title.Equals(testSuite.Title));
                                }
                                continue;
                            }
                            if (existingSuite == null)
                            {
                                Logger = "Creating new suite called - " + testSuite.Title + "\n" + Logger;


                                #region New Feature
                                switch (testSuite.TestSuiteType)
                                {
                                case TestSuiteType.RequirementTestSuite:
                                    var store          = ((IRequirementTestSuite)testSuite).Project.WitProject.Store;
                                    var tfsRequirement = store.GetWorkItem(((IRequirementTestSuite)testSuite).RequirementId);
                                    IRequirementTestSuite newRequirementSuite = TfsShared.Instance.TargetTestProject.TestSuites.CreateRequirement(tfsRequirement);


                                    newRequirementSuite.Title       = testSuite.Title;
                                    newRequirementSuite.Description = testSuite.Description;
                                    newRequirementSuite.State       = testSuite.State;
                                    tfsRequirement.Save();
                                    parentSuite.Entries.Add(newRequirementSuite);
                                    break;

                                case TestSuiteType.StaticTestSuite:
                                    IStaticTestSuite newStaticSuite = TfsShared.Instance.TargetTestProject.TestSuites.CreateStatic();
                                    newStaticSuite.Title            = testSuite.Title;
                                    newStaticSuite.State            = testSuite.State;
                                    newStaticSuite.Description      = testSuite.Description;

                                    parentSuite.Entries.Add(newStaticSuite);
                                    parentSuite = newStaticSuite;
                                    break;

                                case TestSuiteType.DynamicTestSuite:
                                    IDynamicTestSuite newDynamicSuite = TfsShared.Instance.TargetTestProject.TestSuites.CreateDynamic();
                                    newDynamicSuite.Query             = TfsShared.Instance.TargetTestProject.CreateTestQuery(((IDynamicTestSuite)testSuite).Query.QueryText);
                                    newDynamicSuite.Title             = testSuite.Title;
                                    newDynamicSuite.State             = testSuite.State;
                                    newDynamicSuite.Description       = testSuite.Description;
                                    parentSuite.Entries.Add(newDynamicSuite);
                                    break;
                                }
                                #endregion
                            }
                            else
                            {
                                Logger = string.Format("Suite '{0}' already exists.\n{1}", existingSuite.Title, Logger);
                            }

                            plan.Save();
                        }
                        if ((parentSuite.TestSuiteType == TestSuiteType.StaticTestSuite) && (isTestCaseParentRequirementTestSuite == false) && (isTestCaseParentDynamicTestSuite == false))
                        {
                            ITestCase targetTestCase =
                                TfsShared.Instance.TargetTestProject.TestCases.Find(targetWorkItem.Id);
                            if (!parentSuite.Entries.Contains(targetTestCase))
                            {
                                ITestSuiteEntry entry = parentSuite.Entries.Add(targetTestCase);
                                entry.Configurations.Add(test.Configuration);
                                Logger = "Adding duplicated test case completed.\n" + Logger;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger = string.Format("** ERROR ** : {0}\n", ex.Message) + Logger;
                }
            });
        }
        private void FixIterationNotFound(Exception exception, ITestSuiteBase source, IDynamicTestSuite targetSuiteChild, TestManagementContext targetTestStore)
        {
            if (exception.Message.Contains("The specified iteration path does not exist."))
            {
                Regex regEx = new Regex(@"'(.*?)'");

                var missingIterationPath = regEx.Match(exception.Message).Groups[0].Value;
                missingIterationPath = missingIterationPath.Substring(missingIterationPath.IndexOf(@"\") + 1, missingIterationPath.Length - missingIterationPath.IndexOf(@"\") - 2);

                Trace.WriteLine("Found a orphaned iteration path in test suite query.");
                Trace.WriteLine(string.Format("Invalid iteration path {0}:", missingIterationPath));
                Trace.WriteLine("Replacing the orphaned iteration path from query with root iteration path. Please fix the query after the migration.");

                targetSuiteChild.Query = targetSuiteChild.Project.CreateTestQuery(
                    targetSuiteChild.Query.QueryText.Replace(
                        string.Format(@"'{0}\{1}'", source.Plan.Project.TeamProjectName, missingIterationPath),
                        string.Format(@"'{0}'", targetTestStore.Project.TeamProjectName)
                        ));

                targetSuiteChild.Query = targetSuiteChild.Project.CreateTestQuery(
                    targetSuiteChild.Query.QueryText.Replace(
                        string.Format(@"'{0}\{1}'", targetTestStore.Project.TeamProjectName, missingIterationPath),
                        string.Format(@"'{0}'", targetTestStore.Project.TeamProjectName)
                        ));
            }
        }
        public void CreateSprint1TestPlan()
        {
            TfsTeamProjectCollection   tpc     = TfsConnect();
            ITestManagementTeamProject project = tpc.GetService <ITestManagementService>().GetTeamProject(TeamProject);

            // Create test plan if none exist
            //
            // See http://bit.ly/2dup2XY for why we can't delete Test Plans or Suites at this point in time
            //
            // If this routine isn't creating the test plan and/or test suites for you, you'll need to manually
            // delete the Test Plan and Test Suites using witadmin

            WorkItemStore      store     = new WorkItemStore(tpc);
            string             wiql      = "SELECT [System.Id] FROM WorkItems " + "WHERE [System.TeamProject] = '" + TeamProject + "' AND [System.WorkItemType] ='Test Plan' AND [System.Title] = 'Sprint 1'";
            WorkItemCollection workItems = store.Query(wiql);
            int testPlanCount            = workItems.Count;

            wiql = "SELECT [System.Id] FROM WorkItems " + "WHERE [System.TeamProject] = '" + TeamProject + "' AND [System.WorkItemType] ='Test Suite'";
            int       testSuiteCount = store.Query(wiql).Count;
            ITestPlan testPlan;

            if (testPlanCount == 0)
            {
                testPlan           = project.TestPlans.Create();
                testPlan.Name      = "Sprint 1";
                testPlan.Iteration = @"Fabrikam\Release 1\Sprint 1";
                testPlan.Save();
                Console.WriteLine(" . (1 plan created)");
            }
            else
            {
                testPlan = project.TestPlans.Find(workItems[0].Id);
                Console.WriteLine(" . (plan exists)");
            }

            // Create Test Suites if non exist

            if (testSuiteCount <= 10) // May create duplicate test suites
            {
                Console.Write(" Creating sprint 1 test suites ");

                // suites

                int count = 0;
                IStaticTestSuite staticSuite = project.TestSuites.CreateStatic();
                staticSuite.Title = "Automated";
                testPlan.RootSuite.Entries.Add(staticSuite);
                testPlan.Save();
                Console.Write(".");
                count++;

                staticSuite       = project.TestSuites.CreateStatic();
                staticSuite.Title = "Regression";
                testPlan.RootSuite.Entries.Add(staticSuite);
                testPlan.Save();
                Console.Write(".");
                count++;

                // Requirement-based suites

                // Get PBI work items

                wiql      = "SELECT [System.Id] FROM WorkItems " + "WHERE [System.TeamProject] = '" + TeamProject + "' AND [System.WorkItemType] ='Product Backlog Item'";
                workItems = store.Query(wiql);
                for (int i = 0; i < workItems.Count; i++)
                {
                    WorkItem pbi = workItems[i];

                    // Link Test Case to PBI

                    int testCaseID = (int)TestCases[pbi.Title.ToLower()];
                    WorkItemLinkTypeEnd testedByLink = store.WorkItemLinkTypes.LinkTypeEnds["Tested By"];
                    pbi.WorkItemLinks.Add(new WorkItemLink(testedByLink, testCaseID));
                    pbi.Save();

                    // Create Requirement-based test suite

                    IRequirementTestSuite reqSuite = project.TestSuites.CreateRequirement(pbi);
                    reqSuite.Title = pbi.Title;
                    testPlan.RootSuite.Entries.Add(reqSuite);
                    testPlan.Save();
                    Console.Write(".");
                    count++;
                }

                // Query-based suites

                IDynamicTestSuite querySuite = project.TestSuites.CreateDynamic();
                querySuite.Title = "UI Tests";
                querySuite.Query = project.CreateTestQuery(@"SELECT [System.Id],[System.WorkItemType],[System.Title],[Microsoft.VSTS.Common.Priority],[System.AssignedTo],[System.AreaPath] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.WorkItemType] IN GROUP 'Microsoft.TestCaseCategory' AND [System.AreaPath] UNDER 'Fabrikam' AND [System.IterationPath] UNDER 'Fabrikam\Release 1\Sprint 1' AND [System.Title] CONTAINS 'ui'");
                testPlan.RootSuite.Entries.Add(querySuite);
                testPlan.Save();
                Console.Write(".");
                count++;

                querySuite       = project.TestSuites.CreateDynamic();
                querySuite.Title = "Bug Existence Tests";
                querySuite.Query = project.CreateTestQuery(@"SELECT [System.Id],[System.WorkItemType],[System.Title],[Microsoft.VSTS.Common.Priority],[System.AssignedTo],[System.AreaPath] FROM WorkItems WHERE [System.TeamProject] = @project AND [System.WorkItemType] IN GROUP 'Microsoft.TestCaseCategory' AND [System.AreaPath] UNDER 'Fabrikam' AND [System.IterationPath] UNDER 'Fabrikam\Release 1\Sprint 1' AND [System.Title] CONTAINS 'bug'");
                testPlan.RootSuite.Entries.Add(querySuite);
                testPlan.Save();
                Console.Write(".");
                count++;

                Console.WriteLine(string.Format(" ({0} suites created)", count));
            }
        }