public static WorkItemCollection GetItemsByBoardColumn(string boardColumn, string sourceProject) { string info = String.Empty; var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("yourserver/tfs/defaultcollection")); WorkItemStore workItemStore = new WorkItemStore(tpc); string queryText = String.Format("" + " SELECT * FROM WorkItems WHERE [System.TeamProject] = @project " + " and [System.State] <> 'Closed'" + " and [System.State] <> 'Completed'" + " and [System.State] <> 'Removed'" + " and [System.BoardColumn] = '{0}'" + " and [System.WorkItemType] <> 'Task'" + " and [System.WorkItemType] <> 'Test Case'" + " and [System.WorkItemType] <> 'Test Suite'" + " and [System.WorkItemType] <> 'Test Plan'", boardColumn); Query query = new Query(workItemStore, queryText, new Dictionary <string, string>() { { "project", sourceProject } }); WorkItemCollection wic = query.RunQuery(); return(wic); }
internal void DoWork(DateTime startDate, DateTime endDate) { WorkItemCollection workItemCollection = GetWorkItemCollection(startDate.Date.ToString()); Parent.EnableStartButton(); ParseTFSHistory(workItemCollection, startDate, endDate); }
public HttpResponseMessage SearchItem([FromUri] string requestedCollectionUri, [FromUri] string requestedProject, [FromUri] int count, [FromBody] BasicQuery query) { string type = Utils.GetTFSType(query.type); string filter = query.query; Uri collectionUri = new Uri(requestedCollectionUri); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri, new NetworkCredential(username, password, domain)); WorkItemStore workItemStore = tpc.GetService <WorkItemStore>(); WorkItemCollection queryResults = workItemStore.Query( "Select [Title], [State], [Id], [Stack Rank] " + "From Workitems " + "Where [Work Item Type] = '" + type + "' and [State] != 'Removed' and [State] != 'Closed' and " + "[State] != 'Resolved' and [Area Path] under 'RD\\Azure App Plat\\Logic Apps' and [Title] contains '" + filter + "' " + "Order By [Stack Rank] Asc" ); var response = (from WorkItem r in queryResults select new SimpleWorkItem { Title = r.Title, State = r.State, id = r.Id, AreaPath = r.AreaPath, IterationPath = r.IterationPath, Type = r.Type.Name }).Take(count); return(Request.CreateResponse(HttpStatusCode.OK, response)); }
public void GetWorkItems() { WorkItem wi = new WorkItem(DefaultWorkItemType) { Title = "Work Item Created Using WIT OM" }; wi.Save(); WorkItemsAdded.Add(wi.Id); wi.Close(); var workItemsList = string.Join(",", WorkItemsAdded); // Can get multiple work items by using a wiql query string wiql = $"Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.Id] In ({workItemsList})"; WorkItemCollection wiqlQueryResults = WIStore.Query(wiql); Console.WriteLine($"Wiql query searching for work items in ({workItemsList}) returned {wiqlQueryResults.Count} values"); Console.WriteLine(); // Alternatively, you can specify the ids as a collection, and a wiql for columns to return string columnWiql = $"Select [System.Id], [System.Title], [System.State] From WorkItems "; WorkItemCollection idAndColumnWiqlResults = WIStore.Query(WorkItemsAdded.ToArray(), columnWiql); Console.WriteLine($"Query searching for work items in ({workItemsList}) returned {idAndColumnWiqlResults.Count} values"); Console.WriteLine(); }
static partial void RealInstanceFactory(ref WorkItemCollection real, string callerName) { var store = WorkItemStoreWrapper_UnitTests.GetRealInstance(); const string wiql = "SELECT * FROM WorkItems WHERE [System.TeamProject] = 'RestPlaypen' ORDER BY [System.Id] "; real = store.Query(wiql); }
public void SeveralSelectsTest() { string expected = MINIMAL_WIQL; string expected2 = MINIMAL_WIQL.Replace("[System.Id]", "[System.Id], [System.Title]"); var query = from item in _store.WorkItems() select item; var query2 = query.Select(item => item.Columns()); string actual2 = TrimQueryText(query2); Assert.Equal(expected, actual2); var query3 = query.Select(item => item.Columns("System.Id", CoreFieldReferenceNames.Title)); string actual3 = TrimQueryText(query3); Assert.Equal(expected, actual2); Assert.Equal(expected2, actual3); var query4 = query3.Where(item => item.Field <int>(CoreFieldReferenceNames.Id) == 12345); WorkItemCollection result = query4.Provider.Execute <WorkItemCollection>(query4.Expression); int displayFields3 = result.DisplayFields.Count; Assert.Equal(2, displayFields3); }
public void RefreshWorkItems(IResultsDocument queryResultsDocument) { string query = queryResultsDocument.QueryDocument.QueryText; Hashtable context = GetTfsQueryParameters(queryResultsDocument); var tpc = visualStudioAdapter.GetCurrent(); var workItemStore = tpc.GetService <WorkItemStore>(); var workItemQuery = new Query(workItemStore, query, context); NumericFieldDefinitions = GetNumericFieldDefinitions(workItemQuery); if (!NumericFieldDefinitions.Any()) { CurrentWorkItems = new WorkItem[0]; return; } WorkItemCollection workItemCollection = workItemStore.GetWorkItems(workItemQuery, NumericFieldDefinitions); WorkItem[] workItemsA = new WorkItem[workItemCollection.Count]; ((ICollection)workItemCollection).CopyTo(workItemsA, 0); CurrentWorkItems = workItemsA; RefreshTotals((queryResultsDocument.SelectedItemIds ?? new int[0])); }
public static TFSBugProvider.QueryArgument MergeAndQuery(WorkItemCollection workItems, string key, TFSBugProvider.QueryArgument arg) { TFSBugProvider.QueryArgument temp = TFSBugProvider.QueryArgument.Parse(key); if (arg.State != null) { temp.State = arg.State; } if (!string.IsNullOrEmpty(arg.Keyword)) { temp.Keyword = arg.Keyword; } if (arg.Category != null) { temp.Category = arg.Category; } if (!string.IsNullOrEmpty(arg.Creater)) { temp.Creater = arg.Creater; } CounterRecord.ComplexValue cv = new CounterRecord.ComplexValue( SimplifyKey(temp.ToString()), Type, TFSBugProvider.QueryBugCount(workItems, temp)); cache[temp.ToString()] = cv; return(temp); }
public IEnumerable <WorkItem> PullWorkItemsThatChanged(Uri tfsConnectionstring, string projectName, DateTime startDate, DateTime endDate) { WorkItemStore workItemStore = GetWorkItemStore(tfsConnectionstring); const string queryTemplate = @" SELECT ID, Title, [Team Project], [Microsoft.VSTS.Common.Priority], System.ChangedDate, [System.AssignedTo], [System.IterationPath], [System.AreaPath], [System.State], [CodeBox.UserVotes] FROM Issue WHERE [System.TeamProject] = @projectName and System.ChangedDate > @startDate and System.ChangedDate < @endDate "; IDictionary paramsDictionary = new Dictionary <string, object>(); paramsDictionary["projectName"] = projectName; //TFS will throw an error if you use the time in query and it defaults to midnight on the day sent in so we //have to use the previous day's date. paramsDictionary["startDate"] = startDate.Date.AddDays(-1); paramsDictionary["endDate"] = endDate.Date.AddDays(1); WorkItemCollection tfsWorkItemCollection = workItemStore.Query(queryTemplate, paramsDictionary); return(tfsWorkItemCollection.Cast <WorkItem>().ToList()); }
/// <summary> /// Executes a query that gets a <see cref="WorkItemCollection"/> that contains <see cref="WorkItem"/> objects that satisfy the query. /// </summary> /// <param name="cancellationToken">Used to cancel the operation.</param> /// <returns>A list that contains <see cref="ITfsWorkItem"/> objects that satisfy the query.</returns> public IList <ITfsWorkItem> RunQuery(CancellationToken cancellationToken) { WorkItemCollection workItems = null; ICancelableAsyncResult result = this.query.BeginQuery(); try { cancellationToken.Register(s => ((ICancelableAsyncResult)s).Cancel(), result); result.AsyncWaitHandle.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); } finally { workItems = this.query.EndQuery(result); } IList <ITfsWorkItem> ans = new List <ITfsWorkItem>(); foreach (WorkItem wi in workItems) { ans.Add(new TfsWorkItem(wi)); } return(ans); }
internal override void InternalExecute() { Stopwatch stopwatch = Stopwatch.StartNew(); ////////////////////////////////////////////////// WorkItemStoreContext sourceStore = new WorkItemStoreContext(me.Source, WorkItemStoreFlags.None); TfsQueryContext tfsqc = new TfsQueryContext(sourceStore); tfsqc.AddParameter("TeamProject", me.Source.Config.Name); tfsqc.Query = string.Format(@"SELECT [System.Id], [System.Tags] FROM WorkItems WHERE [System.TeamProject] = @TeamProject {0} ORDER BY [System.ChangedDate] desc", _config.QueryBit); WorkItemCollection sourceWIS = tfsqc.Execute(); int current = sourceWIS.Count; var workItemServer = me.Source.Collection.GetService <WorkItemServer>(); var invalidFileNameChars = Path.GetInvalidFileNameChars(); foreach (WorkItem wi in sourceWIS) { WorkItemAttachmentExport(workItemServer, wi); current++; } ////////////////////////////////////////////////// stopwatch.Stop(); Console.WriteLine(@"EXPORT DONE in {0:%h} hours {0:%m} minutes {0:s\:fff} seconds", stopwatch.Elapsed); }
/// <summary> /// Classics the object model. /// </summary> /// <param name="tfs">The TFS.</param> private static void ClassicObjectModel(TfsTeamProjectCollection tfs) { tfs.EnsureAuthenticated(); var workitemstore = tfs.GetService <WorkItemStore>(); const string wiql = "SELECT * FROM WorkItems WHERE [System.TeamProject] = 'RestPlaypen' ORDER BY [System.Id] "; WorkItemCollection wic = workitemstore.Query(wiql); foreach (WorkItem wi in wic) { if (wi.Rev > 1) { Console.WriteLine("{0}:{1}\t{2}", wi.Id, wi.Rev, wi.Title); RevisionCollection revisions = wi.Revisions; foreach (Revision revision in revisions) { Console.WriteLine("\t{0}\t{1}\t{2}", revision.Index, revision.Fields.Count, revision.Fields["System.ChangedDate"].Value); } } if (wi.Links.Count > 0) { Console.WriteLine("{0}:{1}\t{2}", wi.Id, wi.Rev, wi.Title); Console.WriteLine("\t{0} Links", wi.Links.Count); foreach (Link link in wi.Links) { Console.WriteLine("\t\t{0}\tComment: {1}", WriteSpecific(link), SafeWriteComment(link)); } } } }
public void GetAllWorkItems() { //_WorkItemViewModel.WorkItemInfos = new ObservableCollection<WorkItemInfo>(); TfsTeamProjectCollection prjCollection = new TfsTeamProjectCollection(new Uri("http://*****:*****@project", new Dictionary <string, string>() { { "project", "TFSBaseline" } }); WorkItemCollection wic = query.RunQuery(); //foreach (WorkItem item in wic) //{ // _WorkItemViewModel.WorkItemInfos.Add(new WorkItemInfo() // { // Id = item.Id, // Revision = item.Revision, // WorkItemType = item.Type.ToString(), // Desc = item.Description, // AssignedTo = item.CreatedBy, // State = item.State // }); //} //return _WorkItemViewModel.WorkItemInfos; }
/// <summary> /// Executes a WIQL query using the provided query, parameters. If useDefaultProject is set, then the query is /// constrained to the user's currently selected project. /// </summary> public IEnumerable <WorkItemSummary> ExecuteWiqlQuery(string query, Dictionary <string, object> parameters, bool useDefaultProject) { if (parameters == null) { parameters = new Dictionary <string, object>(); } // Add the default project name if one is missing if (query.IndexOf("TeamProject") == -1 && useDefaultProject) { if (!parameters.ContainsKey("Project")) { parameters.Add("Project", UserContext.Current.CurrentProject.Name); } else { parameters["Project"] = UserContext.Current.CurrentProject.Name; } query += " AND System.TeamProject = @Project"; } WorkItemCollection collection = UserContext.Current.WorkItemStore.Query(query, parameters); return(collection.ToSummaries()); }
/// <summary> /// Enumerate the diff items found based on the query passed in as well as the filterString and version passed /// to InitializeForDiff. The return type is IEnumerable<> so that adapter implementations do not need download and keep /// all of the IWITDiffItems in memory at once. /// </summary> /// <param name="queryCondition">A string that specifies a query used to select a subset of the work items defined by /// the set that the filter string identified.</param> /// <returns>An enumeration of IWITDiffItems each representing a work item to be compared by the WIT Diff operation</returns> public IEnumerable <IWITDiffItem> GetWITDiffItems(string queryCondition) { string columnList = "[System.Id], [System.Rev]"; StringBuilder conditionBuilder = new StringBuilder(m_filterString); if (!string.IsNullOrEmpty(queryCondition)) { if (conditionBuilder.Length > 0) { conditionBuilder.Append(" AND "); } conditionBuilder.Append(queryCondition); } string orderBy = "[System.Id]"; string wiql = TfsWITQueryBuilder.BuildWiqlQuery(columnList, conditionBuilder.ToString(), orderBy); // Run query with date precision off Dictionary <string, object> context = new Dictionary <string, object>(); context.Add("project", m_projectName); Query wiq = new Query(m_workItemStore, wiql, context, false); // Retrieve all results ICancelableAsyncResult car = wiq.BeginQuery(); WorkItemCollection workItems = wiq.EndQuery(car); foreach (WorkItem workItem in workItems) { yield return((IWITDiffItem) new TfsWITDiffItem(this, workItem)); } }
public ObservableCollection <WorkItemInfo> GetAllWorkItems() { _WorkItemViewModel.WorkItemInfos = new ObservableCollection <WorkItemInfo>(); TfsTeamProjectCollection prjCollection = new TfsTeamProjectCollection(new Uri("http://*****:*****@project", new Dictionary <string, string>() { { "project", "TFSBaseline" } }); WorkItemCollection wic = query.RunQuery(); foreach (WorkItem item in wic) { _WorkItemViewModel.WorkItemInfos.Add(new WorkItemInfo() { Id = item.Id, Revisions = item.Revisions, Revision = item.Revision, WorkItemType = item.Type.Name, WorkItemTitle = item.Title, Desc = item.Description, CreatedBy = item.CreatedBy, State = item.State, AssignedTo = item["Assigned To"].ToString() }); } return(_WorkItemViewModel.WorkItemInfos); }
public IEnumerable <TfsStory> GetTfsStories() { if (_stories == null) { _stories = new List <TfsStory>(); string wiql = @"Select [Id], [Title], [Assigned To], [Created Date], [Iteration Path], [State] From [WorkItems] Where ([Work Item Type] = 'User Story' or [Work Item Type] = 'Product Backlog Item') and [Team Project] = '{0}'"; WorkItemCollection queryResults = TeamProject.Store.Query( string.Format(wiql, TeamProject.ProjectName)); foreach (WorkItem item in queryResults) { TfsStory story = null; story = item.ToTfsStory(); story.Link = string.Format("{0}/{1}/_workitems/edit/{2}", TeamProject.Store.TeamProjectCollection.Uri.AbsoluteUri, TeamProject.ProjectName, item.Id); _stories.Add(story); } } return(_stories); }
/// <summary> /// Gets the TFS tasks. /// </summary> /// <param name="iterationPath">The iteration path.</param> /// <returns></returns> public IEnumerable <TfsTask> GetTfsTasks(string iterationPath) { if (_tasks == null) { _tasks = new List <TfsTask>(); string wiql = @"Select [State], [Title] From [WorkItems] Where [Work Item Type] = 'Task' And [Team Project] = '{0}' And [Iteration Path] = '{1}'"; WorkItemCollection queryResults = TeamProject.Store.Query( string.Format(wiql, TeamProject.ProjectName, iterationPath)); foreach (WorkItem item in queryResults) { TfsTask task = null; task = item.ToTfsTask(); task.Link = string.Format("{0}/{1}/_workitems/edit/{2}", TeamProject.Store.TeamProjectCollection.Uri.AbsoluteUri, TeamProject.ProjectName, item.Id); _tasks.Add(task); } } return(_tasks); }
static void Main(string[] args) { string info = String.Empty; TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://xxxx.visualstudio.com")); new System.Net.NetworkCredential("*****@*****.**", "password"); tpc.EnsureAuthenticated(); WorkItemStore workItemStore = new WorkItemStore(tpc); Query query = new Query(workItemStore, "SELECT * FROM WorkItems WHERE [System.TeamProject] = @project", new Dictionary <string, string>() { { "project", "ProjectNameHere" } }); WorkItemCollection wic = query.RunQuery(); foreach (WorkItem item in wic) { info += String.Format("WIT:{0} ID: {1} Title: {2}\n", item.Type.Name, item.Id, item.Title); } Console.WriteLine(info); Console.ReadLine(); }
// TODO - should be parameterized by date public void QueryClosedTodayWorkItems(Project project) { string query = " SELECT [System.Id], [System.WorkItemType]," + " [System.State], [System.AssignedTo], [System.Title] " + " FROM WorkItems " + " WHERE [System.TeamProject] = '" + project.Name + "'" + " AND [System.State] = '" + "done" + "'" + " AND [Microsoft.VSTS.Common.ClosedDate] = " + "@today" + " ORDER BY [System.WorkItemType], [System.Id]"; var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(_tfsAddress)); var wiStore = tfs.GetService <WorkItemStore>(); WorkItemCollection workItems = wiStore.Query(query); if (workItems.Count == 0) { Console.WriteLine("No closed work items"); return; } foreach (WorkItem wi in workItems) { Console.WriteLine(wi.Title + "[" + wi.Type.Name + "]" + wi.State); } }
/// <summary> /// Flats the link query. /// </summary> /// <param name="query">The query.</param> /// <returns></returns> private IEnumerable <WorkItem> FlatLinkQuery(Query query) { var workItemLinks = query.RunLinkQuery(); // Build the list of work items for which we want to retrieve more information int[] ids = (from WorkItemLinkInfo info in workItemLinks select info.TargetId).ToArray(); // Next we want to create a new query that will retrieve all the column values from the original query, for // each of the work item IDs returned by the original query. var detailsWiql = new StringBuilder(); detailsWiql.AppendLine("SELECT"); bool first = true; foreach (FieldDefinition field in query.DisplayFieldList) { detailsWiql.Append(" "); if (!first) { detailsWiql.Append(","); } detailsWiql.AppendLine("[" + field.ReferenceName + "]"); first = false; } detailsWiql.AppendLine("FROM WorkItems"); // Get the work item details var flatQuery = new Query(TeamProject.Store, detailsWiql.ToString(), ids); WorkItemCollection details = flatQuery.RunQuery(); return(details.Cast <WorkItem>()); }
public Dictionary <string, int> IDWithTitle(WorkItemCollection items) { Dictionary <string, int> idWithTitle = new Dictionary <string, int>(); foreach (WorkItem item in items) { string key = UC(item.Title); if (key != null && key != "") { if (!idWithTitle.ContainsKey(key)) { try { idWithTitle.Add(key, item.Id); } catch (ArgumentNullException) { Console.WriteLine("Key为Null"); } catch (ArgumentException) { Console.WriteLine("存在两个UC编号一样的uc"); } } } } return(idWithTitle); }
public void CreatLink(Dictionary <string, int> child) { foreach (WorkItem item in SearchResult) { String pattern = @"UC-\d+"; Match match = Regex.Match(item.Description, pattern, RegexOptions.IgnoreCase); if (match.Value != "") { if (child.ContainsKey(match.Value)) { base.Link(item.Id, child[match.Value], "Shared Steps"); } else { String tempQuery = String.Format("SELECT [System.ID] FROM WorkItems WHERE [System.TeamProject] = '{0}' AND [System.Title] CONTAINS '{1}'", RecentProject.Name, match.Value); WorkItemCollection eItems = ItemStore.Query(tempQuery); foreach (WorkItem eItem in eItems) { if (UC(eItem.Title) == match.Value) { base.Link(item.Id, eItem.Id, "Shared Steps"); } } } } } }
public void Mark1SprintTasksDone() { TfsTeamProjectCollection tpc = TfsConnect(); // Get Task work items int count = 0; WorkItemStore store = new WorkItemStore(tpc); Project project = store.Projects[TeamProject]; string wiql = "SELECT [System.Id], [System.State], [Microsoft.VSTS.Scheduling.RemainingWork] FROM WorkItems " + "WHERE [System.TeamProject] = '" + TeamProject + "' AND [System.WorkItemType] = 'Task'"; WorkItemCollection tasks = store.Query(wiql); for (int i = 0; i < tasks.Count; i++) { WorkItem task = tasks[i]; if (task.Title.ToLower().Contains("test plan") || task.Title.ToLower().Contains("test suite") || task.Title.ToLower().Contains("test case")) { task.Open(); task.State = "Done"; task.Save(); Console.Write("."); count++; } } Console.WriteLine(string.Format(" ({0} tasks marked done)", count)); }
public void testQuery() { TFSAccessor t = TFSAccessor.TFSAccessorFactory("", "", "", ""); WorkItemCollection wic = t.GetReleaseNotesFromQuery(); Assert.IsNotNull(wic); }
private WorkItemCollection GetWorkItems(int startIndex, int length) { Debug.Assert(startIndex >= 0, "startIndex < 0"); Debug.Assert(length >= 0, "length < 0"); Debug.Assert(m_idsInQueryResult != null, "m_idsInQueryResult is NULL"); BatchReadParameterCollection readParams = new BatchReadParameterCollection(); int index = startIndex; for (; length > 0 && index < m_idsInQueryResult.Length; ++index) { readParams.Add(new BatchReadParameter(m_idsInQueryResult[index])); --length; } if (readParams.Count == 0) { return(null); } WorkItemCollection items = m_store.Query(readParams, BatchReadQuery); m_firstItemIdInNextPage = index; return(items); }
public void Sprint1Forecast() { TfsTeamProjectCollection tpc = TfsConnect(); // Get work items WorkItemStore store = new WorkItemStore(tpc); Project project = store.Projects[TeamProject]; string wiql = "SELECT [System.Id] FROM WorkItems " + "WHERE [System.TeamProject] = '" + TeamProject + "' AND [System.WorkItemType] ='Product Backlog Item'"; WorkItemCollection collection = store.Query(wiql); // Get list of work items to put into Sprint 1 int count = 0; for (int i = 0; i < collection.Count; i++) { WorkItem wi = collection[i]; // Set Iteration Path and State wi.Open(); wi.IterationPath = @"Fabrikam\Release 1\Sprint 1"; wi.State = "Committed"; wi.Save(); Console.Write("."); count++; } // Done Console.WriteLine(string.Format(" ({0} PBIs added)", count)); }
static void Main(String[] args) { // Connect to Team Foundation Server // Server is the name of the server that is running the application tier for Team Foundation. // Port is the port that Team Foundation uses. The default port is 8080. // VDir is the virtual path to the Team Foundation application. The default path is tfs. TfsTeamProjectCollection prjCollection = new TfsTeamProjectCollection(new Uri("http://*****:*****@project", new Dictionary <string, string>() { { "project", "TFSBaseline" } }); WorkItemCollection wic = query.RunQuery(); string info = String.Empty; foreach (WorkItem item in wic) { info += String.Format($"{item.Title}-{item.CreatedBy}-{item.CreatedDate}-{item.Id}"); } Console.WriteLine(info); Console.ReadLine(); //GetProjectDetails(tfsUri); }
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { WorkItemCollection workItemCollection = GetWorkItemCollection(); EnableStartButton(); ParseTFSHistory(workItemCollection); }
internal override void InternalExecute() { Stopwatch stopwatch = Stopwatch.StartNew(); ////////////////////////////////////////////////// WorkItemStoreContext targetStore = new WorkItemStoreContext(me.Target, WorkItemStoreFlags.BypassRules); TfsQueryContext tfsqc = new TfsQueryContext(targetStore); tfsqc.AddParameter("TeamProject", me.Target.Config.Project); tfsqc.Query = string.Format(@"SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @TeamProject AND [System.AreaPath] UNDER '{0}\_DeleteMe'", me.Target.Config.Project); WorkItemCollection workitems = tfsqc.Execute(); Trace.WriteLine(string.Format("Update {0} work items?", workitems.Count)); ////////////////////////////////////////////////// int current = workitems.Count; //int count = 0; //long elapsedms = 0; var tobegone = (from WorkItem wi in workitems where wi.AreaPath.Contains("_DeleteMe") select wi.Id).ToList(); foreach (int begone in tobegone) { targetStore.Store.DestroyWorkItems(new List <int>() { begone }); Trace.WriteLine(string.Format("Deleted {0}", begone)); } ////////////////////////////////////////////////// stopwatch.Stop(); Console.WriteLine(@"DONE in {0:%h} hours {0:%m} minutes {0:s\:fff} seconds", stopwatch.Elapsed); }
public static void Print(WorkItemCollection queryResults, string tfsUri, string tfsCollection) { Console.WriteLine("Number of matching query result(s): " + queryResults.Count); foreach (WorkItem item in queryResults) { var id = item.Id.ToString(); var Uri = constructUri(tfsUri, tfsCollection, id); Console.WriteLine(Uri); } }
private void CreateCards(WorkItemCollection workItems) { EnsureTempDirectoryExists(); CreateCardsXmlFile(workItems); TransformWorkItemsToCards(); OpenCreatedCardsInBrowser(); }
private IEnumerable<OtfsTask> IterarWorkItemsCollection(WorkItemCollection collection, OtfsIteration iteration = null) { foreach (WorkItem item in collection) { var task = WorkItenFactory<OtfsTask>.Build(item); task.Comitar(iteration); yield return task; } }
private void CreateCardsXmlFile(WorkItemCollection workItems) { var tpc = visualStudioAdapter.GetCurrent(); var workItemStore = tpc.GetService<WorkItemStore>(); int[] relatedWorkITemIdentifiers = workItems.OfType<WorkItem>() .SelectMany(wi => wi.WorkItemLinks.Cast<WorkItemLink>()) .Select(s => s.TargetId).Distinct().ToArray(); WorkItemCollection relatedWorkItems = workItemStore.GetWorkItems(relatedWorkITemIdentifiers); new WorkItemXmlFileCreator().Create(workItems, relatedWorkItems, WorkItemsFileName); }
public void GenerateDailyReportContent() { foreach (CatalogNode collectionNode in collectionNodes) { // Use the InstanceId property to get the team project collection Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]); TfsTeamProjectCollection teamProjectCollection = impersonatedConnection.GetTeamProjectCollection(collectionId); // Get a catalog of team projects for the collection ReadOnlyCollection<CatalogNode> projectNodes = collectionNode.QueryChildren( new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None); WorkItemStore workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore)); string query = "SELECT [System.Id] FROM WorkItems where [Assigned to]=@Me"; queryResults = workItemStore.Query(query); } }
public void Create(WorkItemCollection workItems, WorkItemCollection relatedWorkItems, string fileName) { var xmlWriter = XmlWriter.Create(fileName, new XmlWriterSettings { Indent = true }); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("WorkItems"); foreach (WorkItem workItem in workItems) { WriteWorkItemXml(workItem, xmlWriter, "WorkItem"); } foreach (WorkItem workItem in relatedWorkItems) { WriteWorkItemXml(workItem, xmlWriter, "RelatedWorkItem"); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); }
private IEnumerable<OtfsBacklogItem> IterarWorkItemsCollection(WorkItemCollection collection, OtfsIteration iteration) { foreach (WorkItem item in collection) { var backlogItem = WorkItenFactory<OtfsBacklogItem>.Build(item); backlogItem.AdicionarTags(item.Tags.Replace(" ", "")); backlogItem.Comitar(iteration); yield return backlogItem; } }
private void DumpAllWorkItems(WorkItemCollection workitems) { foreach (WorkItem item in workitems) { foreach (Field field in item.Fields) { Console.Write(field.Id); Console.Write(":"); Console.Write(field.Name); Console.Write(":"); Console.Write(field.Value); Console.WriteLine("---"); } } }
// NOTE: Horrible run time. We should probably look into other ways to talk with TFS. private List<WorkItem> GetWorkItemRevisions(WorkItemCollection allWorkItems) { var allWorkItemRevisions = new List<WorkItem>(); for (int i = 0; i < allWorkItems.Count; i++) { var workItem = allWorkItems[i]; for (int j = 0; j < workItem.Revisions.Count; j++) { var revision = workItem.Revisions[j]; var revisionItem = workItemStore.GetWorkItem(workItem.Id, ParseFieldToInt(revision.Fields[CoreField.Rev])); allWorkItemRevisions.Add(revisionItem); } } return allWorkItemRevisions; }
/* Save existing attachments of workitems to local folders of workitem ID */ private void SaveAttachments(WorkItemCollection workItemCollection) { if (!Directory.Exists(@"Attachments")) { Directory.CreateDirectory(@"Attachments"); } else { EmptyFolder(new DirectoryInfo(@"Attachments")); } System.Net.WebClient webClient = new System.Net.WebClient(); webClient.UseDefaultCredentials = true; foreach (WorkItem wi in workItemCollection) { if (wi.AttachedFileCount > 0) { foreach (Attachment att in wi.Attachments) { try { String path = @"Attachments\" + wi.Id; bool folderExists = Directory.Exists(path); if (!folderExists) { Directory.CreateDirectory(path); } if (!File.Exists(path + "\\" + att.Name)) { webClient.DownloadFile(att.Uri, path + "\\" + att.Name); } else { webClient.DownloadFile(att.Uri, path + "\\" + att.Id + "_" + att.Name); } } catch (Exception) { logger.Info("Error downloading attachment for work item : " + wi.Id + " Type: " + wi.Type.Name); } } } } }
/* Copy work items to project from work item collection */ public void writeWorkItems(WorkItemStore sourceStore, WorkItemCollection workItemCollection, string sourceProjectName, ProgressBar ProgressBar, Hashtable fieldMapAll) { ReadItemMap(sourceProjectName); int i = 1; List<WorkItem> newItems = new List<WorkItem>(); foreach (WorkItem workItem in workItemCollection) { if (itemMap.ContainsKey(workItem.Id)) { continue; } WorkItem newWorkItem = null; Hashtable fieldMap = ListToTable((List<object>)fieldMapAll[workItem.Type.Name]); if (workItemTypes.Contains(workItem.Type.Name)) { newWorkItem = new WorkItem(workItemTypes[workItem.Type.Name]); } else if (workItem.Type.Name == "User Story") { newWorkItem = new WorkItem(workItemTypes["Product Backlog Item"]); } else if (workItem.Type.Name == "Issue") { newWorkItem = new WorkItem(workItemTypes["Impediment"]); } else { logger.InfoFormat("Work Item Type {0} does not exist in target TFS", workItem.Type.Name); continue; } /* assign relevent fields*/ foreach (Field field in workItem.Fields) { if (field.Name.Contains("ID") || field.Name.Contains("State") || field.Name.Contains("Reason")) { continue; } if (newWorkItem.Fields.Contains(field.Name) && newWorkItem.Fields[field.Name].IsEditable) { newWorkItem.Fields[field.Name].Value = field.Value; if (field.Name == "Iteration Path" || field.Name == "Area Path" || field.Name == "Node Name" || field.Name == "Team Project") { try { string itPath = (string)field.Value; int length = sourceProjectName.Length; string itPathNew = destinationProject.Name + itPath.Substring(length); newWorkItem.Fields[field.Name].Value = itPathNew; } catch (Exception) { } } } //Add values to mapped fields else if (fieldMap.ContainsKey(field.Name)) { newWorkItem.Fields[(string)fieldMap[field.Name]].Value = field.Value; } } /* Validate Item Before Save*/ ArrayList array = newWorkItem.Validate(); foreach (Field item in array) { logger.Info(String.Format("Work item {0} Validation Error in field: {1} : {2}", workItem.Id, item.Name, newWorkItem.Fields[item.Name].Value)); } //if work item is valid if (array.Count == 0) { UploadAttachments(newWorkItem, workItem); newWorkItem.Save(); itemMap.Add(workItem.Id, newWorkItem.Id); newItems.Add(workItem); //update workitem status updateToLatestStatus(workItem, newWorkItem); } else { logger.ErrorFormat("Work item {0} could not be saved", workItem.Id); } ProgressBar.Dispatcher.BeginInvoke(new Action(delegate () { float progress = (float)i / (float)workItemCollection.Count; ProgressBar.Value = ((float)i / (float)workItemCollection.Count) * 100; })); i++; } WriteMaptoFile(sourceProjectName); CreateLinks(newItems, sourceStore, ProgressBar); CreateExternalLinks(newItems, sourceStore, ProgressBar); }
public bool TryGetQueryDefinitionWorkItemCollection(out WorkItemCollection workItemCollection, TfsTeamProjectCollection tfsTeamProjectCollection, QueryDefinition queryDefinition, string projectName) { try { workItemCollection = _teamPilgrimTfsService.GetQueryDefinitionWorkItemCollection(tfsTeamProjectCollection, queryDefinition, projectName); return true; } catch (Exception ex) { this.Logger().DebugException(ex); LastException = ex; } workItemCollection = null; return false; }
/* Save existing attachments of workitems to local folders of workitem ID */ private void SaveAttachments(WorkItemCollection workItemCollection, System.Windows.Controls.ProgressBar ProgressBar) { if (!Directory.Exists(@"Attachments")) { Directory.CreateDirectory(@"Attachments"); } else { EmptyFolder(new DirectoryInfo(@"Attachments")); } System.Net.WebClient webClient = new System.Net.WebClient(); webClient.UseDefaultCredentials = true; int index = 0; foreach (WorkItem wi in workItemCollection) { if (wi.AttachedFileCount > 0) { foreach (Attachment att in wi.Attachments) { try { String path = @"Attachments\" + wi.Id; bool folderExists = Directory.Exists(path); if (!folderExists) { Directory.CreateDirectory(path); } var fileInfo = new FileInfo(path + "\\" + att.Name); if (!fileInfo.Exists) { webClient.DownloadFile(att.Uri, path + "\\" + att.Name); } else if (fileInfo.Length != att.Length) { webClient.DownloadFile(att.Uri, path + "\\" + att.Id + "_" + att.Name); } } catch (Exception) { logger.Info("Error downloading attachment for work item : " + wi.Id + " Type: " + wi.Type.Name); } } } index++; ProgressBar.Dispatcher.BeginInvoke(new Action(delegate () { float progress = (float)index / (float)workItemCollection.Count; ProgressBar.Value = ((float)index / (float)workItemCollection.Count) * 100; })); } }