public QueryResultsTotalizerModel(IVisualStudioAdapter visualStudioAdapter)
        {
            this.visualStudioAdapter = visualStudioAdapter;

            CurrentWorkItems = new WorkItem[0];
            NumericFieldDefinitions = new FieldDefinition[0];
        }
        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]));
        }
Example #3
0
        /// <summary>
        /// Creates a new work item of a defined type
        /// </summary>
        /// <param name="workItemType">The type name</param>
        /// <param name="title">Default title</param>
        /// <param name="description">Default description</param>
        /// <param name="fieldsAndValues">List of extra propierties and values</param>
        /// <returns></returns>
        public WorkItem CreateWorkItem(string workItemType, string title, string description, Dictionary<string, object> fieldsAndValues)
        {
            WorkItemType wiType = workItemTypeCollection[workItemType];
            WorkItem wi = new WorkItem(wiType) { Title = title, Description = description };

            foreach (KeyValuePair<string, object> fieldAndValue in fieldsAndValues)
            {
                string fieldName = fieldAndValue.Key;
                object value = fieldAndValue.Value;

                if (wi.Fields.Contains(fieldName))
                    wi.Fields[fieldName].Value = value;
                else
                    throw new ApplicationException(string.Format("Field not found {0} in workItemType {1}, failed to save the item", fieldName, workItemType));
            }

            if (wi.IsValid())
            {
                wi.Save();
            }
            else
            {
                ArrayList validationErrors = wi.Validate();
                string errMessage = "Work item cannot be saved...";
                foreach (Field field in validationErrors)
                    errMessage += "Field: " + field.Name + " has status: " + field.Status + "/n";

                throw new ApplicationException(errMessage);
            }

            return wi;
        }
Example #4
0
        public static TRSyncState getSyncState(Status status,
                                               Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem)
        {
            String trState  = getTRState(workItem);
            String bugState = workItem.State;

            TRSyncState syncState = TRSyncState.SyncStateOK;

            // If Bug marked as Duplicate, we should notify that No Sync will be done.
            String substate = workItem.Fields[TFSMapper.TFS_SUBSTATE].Value.ToString();

            if (substate.Equals(TFSMapper.TFS_SUBSTATE_DUPLICATE))
            {
                return(TRSyncState.SyncStateNone);
            }

            // Check if we are in sync error state. Get the TR states corresponding to the Bug state.
            // If Bug state is that list - OK, if not we have a sync "error state".
            if (bugStateToTrState.ContainsKey(bugState))
            {
                string[] trStatesForBug = bugStateToTrState[bugState];
                syncState = Array.IndexOf(trStatesForBug, trState) < 0 ? TRSyncState.SyncStateError : syncState;
            }

            // If not error - check if warn state
            if (syncState != TRSyncState.SyncStateError)
            {
                syncState = (status.GetMessage().Length > 0) ? TRSyncState.SyncStateWarning : syncState;
            }

            return(syncState);
        }
Example #5
0
 public void AddWorkItem()
 {
     WorkItem newItem = new WorkItem( teamProject.WorkItemTypes["タスク"] );
     newItem.Title = "作業項目の概要です";
     newItem.Description = "作業項目の詳細です";
     newItem.Save();
 }
Example #6
0
        public List <WorkItem> GetWorkItemTasks(int parentId)
        {
            string sql = string.Format(@"SELECT [System.Id], [System.State], [System.WorkItemType] 
FROM WorkItemLinks 
WHERE 
(
    Source.[System.Id] = {0}  
) 
AND [System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' 
AND Target.[System.WorkItemType] <> '' 
ORDER BY [System.Id] mode(Recursive)", parentId);

            List <WorkItemLinkInfo> query1 = new Query(GetWorkItemStore(), sql).RunLinkQuery().ToList();

            List <WorkItem> workItems = new List <WorkItem>();

            foreach (WorkItemLinkInfo wili in query1)
            {
                WorkItem wi = GetWorkItem(wili.TargetId);
                if (wi.Type.Name == "Task")
                {
                    workItems.Add(wi);
                }
            }

            return(workItems);
        }
Example #7
0
 private IEnumerable<RelatedLink> GetRelatedWorkItemLinks(WorkItem workItem)
 {
     return workItem.Links.Cast<Link>()
         .Where(link => link.BaseType == BaseLinkType.RelatedLink)
         .Select(link => link as RelatedLink)
         .ToList();
 }
Example #8
0
        // Return if Bug is successfully saved or not. Note that Save will cause event that will be
        // triggering our code - but correctly filtered out as done by the functional user.
        public Boolean saveBug(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem)
        {
            try
            {
                workItem.Save();
                HandlerSettings.LogMessage(
                    String.Format("Saved workitem: {0}", workItem.Title),
                    HandlerSettings.LoggingLevel.INFO);
            }
            catch (Exception e)
            {
                // According to doc there are two exceptions that can be thrown:
                //      Microsoft.TeamFoundation.WorkItemTracking.Client.ValidationException
                //      Microsoft.TeamFoundation.WorkItemTracking.Client.DeniedOrNotExistException
                // but at least ValidationException is not recognized as subclass to Exception so compile error
                // See http://msdn.microsoft.com/en-us/library/microsoft.teamfoundation.workitemtracking.client.workitem.partialopen.aspx

                HandlerSettings.LogMessage(
                    String.Format("Failed to save workitem, error: {0}", e.Message),
                    HandlerSettings.LoggingLevel.ERROR);
                return(false);
            }

            return(true);
        }
Example #9
0
        private DateTime?GetLastDate(WorkItem wi, string fieldName, string fieldValue)
        {
            DateTime?ret = DateTime.MinValue;

            foreach (Revision rev in wi.Revisions)
            {
                List <Field> fields = rev.Fields.Cast <Field>().ToList();

                if (fields.Any(x => x.Name == fieldName && x.Value != null && x.Value.ToString() == fieldValue))
                {
                    DateTime?revDt = DateTime.MinValue;
                    if (rev.Fields.Contains("State Change Date"))
                    {
                        revDt = rev.Fields["State Change Date"].Value as DateTime?;
                        if (revDt != null && revDt > ret.Value)
                        {
                            ret = revDt;
                        }
                    }
                }
            }

            if (ret.Value == DateTime.MinValue)
            {
                ret = null;
            }

            return(ret);
        }
Example #10
0
        private static int mapFromUpdated(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem,
            EnterpriseChangeRequest newEcr, String fieldName)
        {
            int noOfMappedChanged = 0;

            // TODO: For the "calculated" fields we have defined ourselves we know the
            // dependencies, but should be expressed more elegant than this. Also the
            // Ericsson.Defect.User.DisplayName is dependent on System.AssignedTo but
            // will not be updated - we "know" that ...
            if (fieldName.Equals(TFSMapper.TFS_OWNER))
            {
                fieldName = TFSMapper.ERICSSON_DEFECT_USER_SIGNUM;
            }

            // Can be multiple ECR properties updated by one TFS field
            List <Property> props = props = AttributesMapper.getInstance().getNotifyProperties(fieldName);

            if (props != null && props.Count > 0)
            {
                foreach (Property prop in props)
                {
                    if (prop.getNotifyChange() && TFSMapper.getInstance().setEcrValues(newEcr, prop.getKey(), workItem))
                    {
                        noOfMappedChanged++;
                    }
                }
            }

            return(noOfMappedChanged);
        }
        /// <summary>
        /// Method for processing work items down to the changesets that are related to them
        /// </summary>
        /// <param name="wi">Work Item to process</param>
        /// <param name="outputFile">File to write the dgml to</param>
        /// <param name="vcs">Version Control Server which contains the changesets</param>
        public void ProcessWorkItemRelationships(WorkItem[] wi, 
                                                 string outputFile, 
                                                 bool hideReverse,
                                                 bool groupbyIteration,
                                                 bool dependencyAnalysis,
                                                 List<TempLinkType> selectedLinks,
                                                 VersionControlServer vcs)
        {
            string projectName = wi[0].Project.Name;

            _workItemStubs = new List<WorkItemStub>();
            _wis = wi[0].Store;
            _vcs = vcs;
            _tms = vcs.TeamProjectCollection.GetService<ITestManagementService>();
            _tmp = _tms.GetTeamProject(projectName);
            _selectedLinks = selectedLinks;

            //Store options
            _hideReverse = hideReverse;
            _groupbyIteration = groupbyIteration;
            _dependencyAnalysis = dependencyAnalysis;

            for (int i = 0; i < wi.Length; i++)
            {
                ProcessWorkItemCS(wi[i]);
            }

            WriteChangesetInfo(outputFile, projectName);
        }
Example #12
0
        // If set, clear the TR fields conneting the Bug with a TR.
        static public Boolean disconnectBug(Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem)
        {
            Boolean updated = false;

            if (workItem.Fields[TFSMapper.ERICSSON_DEFECT_LINK_FIELD].Value != null &&
                workItem.Fields[TFSMapper.ERICSSON_DEFECT_LINK_FIELD].Value.ToString().Length > 0)
            {
                String trId = workItem.Fields[TFSMapper.ERICSSON_DEFECT_LINK_FIELD].Value.ToString();
                workItem.Fields[TFSMapper.TFS_HISTORY].Value = "Workitem disconnected from TR: " + trId;

                workItem.Fields[TFSMapper.ERICSSON_DEFECT_LINK_FIELD].Value  = null;
                workItem.Fields[TFSMapper.ERICSSON_DEFECT_STATE_FIELD].Value = null;
                workItem.Fields[TFSMapper.ERICSSON_DEFECT_SYNCSTATE].Value   = null;

                updated = true;

                HandlerSettings.LogMessage(
                    String.Format(
                        "Cleared TR connection fields for WorkItem with id {0}.",
                        "" + workItem.Id),
                    HandlerSettings.LoggingLevel.INFO);
            }

            return(updated);
        }
Example #13
0
        // Get the Uri for the TR before disconnected assuming disconnect was done in
        // previous save. Preconditions should be checked by caller.
        static public Uri getDisconnectedTRLink(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem,
            WorkItemChangedEvent notification)
        {
            // Apparently we need to check on second last revision to get the correct
            // value for the previous value. This does not show in UI, but is clear when
            // debugging. So check we have > 2 revisions, and then compare.

            if (workItem.Revision < 3)
            {
                return(null);
            }

            Revision lastRev   = workItem.Revisions[workItem.Revision - 2];
            String   oldTrLink = lastRev.Fields[TFSMapper.ERICSSON_DEFECT_LINK_FIELD].Value.ToString();

            if (oldTrLink == null || oldTrLink.Length == 0)
            {
                return(null);
            }

            HandlerSettings.LogMessage(
                String.Format(
                    "Disconnected TR '{0}' from WorkItem with id {1}.",
                    oldTrLink, "" + workItem.Id), HandlerSettings.LoggingLevel.INFO);

            return(new Uri(HandlerSettings.GetUriForTR(oldTrLink)));
        }
Example #14
0
 public WorkItemModel(WorkItem workItem)
 {
     Title = workItem.Title;
     ID = workItem.Id;
     Type = workItem.Type.Name;
     CompletedWork = Type == "Task" && workItem["Completed Work"] != null ? (double)workItem["Completed Work"] : 0;
 }
Example #15
0
 private static string GetReleaseNumber(WorkItem workItem, string customReleaseNumberFieldName)
 {
     if (string.IsNullOrEmpty(customReleaseNumberFieldName))
         return workItem.IterationPath.Substring(workItem.IterationPath.LastIndexOf('\\') + 1);
     else
         return workItem.Fields[customReleaseNumberFieldName].Value.ToString().Trim();
 }
Example #16
0
        private int GetAtivatedChildUsCount(WorkItemStore workItemStore, WorkItem wi)
        {
            var ids = new List<int>();

            foreach (WorkItemLink item in wi.WorkItemLinks)
            {
                if (item.LinkTypeEnd.Name == "Child")
                {
                    ids.Add(item.TargetId);
                }
            }

            var query = string.Format("SELECT [System.Id],[System.WorkItemType],[System.Title] FROM WorkItems WHERE [System.TeamProject] = 'PSG Dashboard' AND [System.WorkItemType] = 'User Story' AND [System.State] = 'Active' AND [System.Id] In ({0})", GetFormatedIds(ids));
            var workItems = workItemStore.Query(query);

            var count = 0;

            foreach (WorkItem tWi in workItems)
            {
                if (tWi.Type.Name == "User Story")
                {
                    count++;
                }
            }

            return count;
        }
Example #17
0
        /// <summary>
        /// Compiles the child tasks.
        /// </summary>
        /// <param name="taskUpdatesQueryResult">The task updates query result.</param>
        /// <param name="tfsUrlPath">The TFS URL path.</param>
        /// <param name="projectName">Name of the project.</param>
        /// <param name="workItem">The work item.</param>
        /// <returns>
        /// ChildItem Collection
        /// </returns>
        public ChildItemCollection CompileChildTasks(QueryResult taskUpdatesQueryResult, string tfsUrlPath, string projectName, Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem parentWorkItem)
        {
            ChildItemCollection childItemCollection = new ChildItemCollection();

            foreach (var workItemNode in taskUpdatesQueryResult.Result)
            {
                if (workItemNode.Children != null && workItemNode.Children.Count > 0)
                {
                    foreach (WorkItemNode childWorkItemNode in workItemNode.Children)
                    {
                        Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem = childWorkItemNode.Item;
                        if (Convert.ToString(workItemNode.Item.Fields[TFSLiterals.AssignedTo].Value) == Convert.ToString(workItem.Fields[TFSLiterals.AssignedTo].Value))
                        {
                            ChildItem childItem = GetChildItem(tfsUrlPath, projectName, workItem);
                            childItemCollection.ChildItems.Add(childItem);
                        }
                    }
                }
            }

            //// if we search only the Tasks it should return the same task as child item with detail info.
            if (parentWorkItem != null && parentWorkItem.Type != null && parentWorkItem.Type.Name == "Task")
            {
                ChildItem childItem = GetChildItem(tfsUrlPath, projectName, parentWorkItem);
                childItemCollection.ChildItems.Add(childItem);
            }

            return(childItemCollection);
        }
Example #18
0
        /// <summary>
        /// Copies the child work items from the templat work item, under parentWorkItem.
        /// Currently there is no support for multiple nesting in the template. This will only copy one level deep.
        /// </summary>
        /// <param name="parentWorkItem"></param>
        public void createChildWorkItems(WorkItem parentWorkItem, WorkItem templateWorkItem)
        {
            WorkItemLinkTypeEnd childLinkType =  workItemStore.WorkItemLinkTypes.LinkTypeEnds["Child"];
            WorkItemLinkTypeEnd parentLinkType =  workItemStore.WorkItemLinkTypes.LinkTypeEnds["Parent"];

            foreach(WorkItemLink itemLInk in templateWorkItem.WorkItemLinks) {

                if ((itemLInk.BaseType == BaseLinkType.WorkItemLink) && (itemLInk.LinkTypeEnd == childLinkType)) {
                   WorkItem copyWorkItem = getWorkItem(itemLInk.TargetId);

                    if (!copyWorkItem["State"].Equals("Removed")) {
                        WorkItem newWorkItem = copyWorkItem.Copy();

                        newWorkItem.Title =  newWorkItem.Title;
                        newWorkItem.IterationId = parentWorkItem.IterationId;
                        newWorkItem.Links.Clear();

                        clearHistoryFromWorkItem(newWorkItem);

                        //This history entry is added to the new items to prevent recursion on newly created items.
                        newWorkItem.History = Resources.strings.HISTORYTEXT_CLONED;

                        WorkItemLinkTypeEnd linkTypeEnd = parentLinkType;
                        newWorkItem.Links.Add(new RelatedLink(linkTypeEnd, parentWorkItem.Id));
                        newWorkItem.Save();
                    }
                }
            }
        }
		public static List<WorkItemField> Map(WorkItem workItem)
		{
			switch (workItem.Type.Name)
			{
				case Constants.TfsBug:
					{
						return GetMapping(workItem, BugFields);
					}
				case Constants.TfsTask:
					{
						return GetMapping(workItem, TaskFields);
					}
				case Constants.TfsUserStory:
					{
						return GetMapping(workItem, UserStoryFields);
					}
				case Constants.TfsIssue:
					{
						return GetMapping(workItem, IssueFields);
					}
				case Constants.TfsBacklogItem:
					{
						return GetMapping(workItem, BackLogFields);
					}
				case Constants.TfsImpediment:
					{
						return GetMapping(workItem, ImpedimentFields);
					}
				default:
					throw new ArgumentException(string.Format("Invalid Work Item Type: {0}", workItem.Type.Name));
			}
		}
        public bool IsIncluded(WorkItem item)
        {
            if (ExcludedItemTypes.Any(x => x.Equals(item.Type.Name, StringComparison.InvariantCultureIgnoreCase)))
            {
                return false;
            }

            if (Projects.Any(x => x.ProjectName.Equals(item.Project.Name, StringComparison.InvariantCultureIgnoreCase)))
            {
                if (Projects.First(x => x.ProjectName.Equals(item.Project.Name, StringComparison.InvariantCultureIgnoreCase))
                            .ExcludedItemTypes.Any(x => x.Equals(item.Type.Name, StringComparison.InvariantCultureIgnoreCase)))
                {
                    return false;
                }
            }

            if (Whitelist)
            {
                return WhitelistedProjects.Any(x => x.Equals(item.Project.Name, StringComparison.InvariantCultureIgnoreCase)) &&
                       !BlacklistedProjects.Any(x => x.Equals(item.Project.Name, StringComparison.InvariantCultureIgnoreCase));
            }
            else
            {
                return !BlacklistedProjects.Any(x => x.Equals(item.Project.Name, StringComparison.InvariantCultureIgnoreCase));
            }
        }
Example #21
0
 public bool CopyAttributes(Story pivotalstorySource, WorkItem destinationWorkItem)
 {
     destinationWorkItem.Fields[ConchangoTeamsystemScrumEstimatedeffort].Value = pivotalstorySource.Estimate;
     destinationWorkItem.Fields[ConchangoTeamsystemScrumBusinesspriority].Value = pivotalstorySource.Priority;
     destinationWorkItem.Fields[ConchangoTeamsystemScrumDeliveryorder].Value = pivotalstorySource.Priority;
     return true;
 }
Example #22
0
        /// <summary>
        /// Fills this instance's fields using the values from the provided <see cref="WorkItem"/>.
        /// This includes the Priority, Reason, Original Estimate, Remaining Work and Completed work fields.
        /// </summary>
        public override void FromWorkItem(WorkItem item)
        {
            base.FromWorkItem(item);

            ResolvedBy = GetFieldValue(item, "Resolved By");

            if (item.Fields.Contains("Priority") && item.Fields["Priority"].Value != null)
                Priority = item.Fields["Priority"].Value.ToString().ToIntOrDefault();

            if (item.Fields.Contains("Reason") && item.Fields["Reason"].Value != null)
                Reason = item.Fields["Reason"].Value.ToString();

            // Estimates
            // Check this field exists. 4.2 Agile doesn't have this field
            if (item.Fields.Contains("Original Estimate") && item.Fields["Original Estimate"].Value != null)
                EstimatedHours = item.Fields["Original Estimate"].Value.ToString().ToDoubleOrDefault();

            if (item.Fields.Contains("Remaining Work") && item.Fields["Remaining Work"].Value != null)
                RemainingHours = item.Fields["Remaining Work"].Value.ToString().ToDoubleOrDefault();

            if (item.Fields.Contains("Completed Work") && item.Fields["Completed Work"].Value != null)
                CompletedHours = item.Fields["Completed Work"].Value.ToString().ToDoubleOrDefault();

            // For updates only
            if (item.Fields.Contains("Original Estimate") && item.Fields["Original Estimate"].Value != null)
                EstimatedHours = item.Fields["Original Estimate"].Value.ToString().ToDoubleOrDefault();
        }
Example #23
0
        public List <WorkItemRevisionHistory> GetRevisionHistory(int workItemId)
        {
            List <WorkItemRevisionHistory> ret = new List <WorkItemRevisionHistory>();

            WorkItem wi = GetWorkItem(workItemId);

            foreach (Revision rev in wi.Revisions)
            {
                foreach (Field f in rev.Fields)
                {
                    if (f.IsChangedInRevision)
                    {
                        var wirh = new WorkItemRevisionHistory();
                        wirh.ChangedDt = DateTime.Parse(rev.Fields["Changed Date"].Value.ToString());
                        wirh.RevisedDt = DateTime.Parse(rev.Fields["Revised Date"].Value.ToString());
                        wirh.FieldName = f.Name;
                        wirh.Id        = workItemId;
                        wirh.NewValue  = f.Value;
                        wirh.Revision  = rev.Index + 1;
                        if (rev.Index > 0)
                        {
                            wirh.OldValue = wi.Revisions[rev.Index - 1].Fields[f.Name].Value;
                        }
                        ret.Add(wirh);
                    }
                }
            }

            return(ret);
        }
Example #24
0
        /// <inheritdoc/>
        public async Task ConfigureAsync(TfsServiceProviderConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if(string.IsNullOrEmpty(configuration.WorkItemType))
            {
                throw new ArgumentNullException(nameof(configuration.WorkItemType));
            }

            this.logger.Debug("Configure of TfsSoapServiceProvider started...");
            var networkCredential = new NetworkCredential(configuration.Username, configuration.Password);
            var tfsClientCredentials = new TfsClientCredentials(new BasicAuthCredential(networkCredential)) { AllowInteractive = false };
            var tfsProjectCollection = new TfsTeamProjectCollection(this.serviceUri, tfsClientCredentials);
            this.workItemType = configuration.WorkItemType;
            tfsProjectCollection.Authenticate();
            tfsProjectCollection.EnsureAuthenticated();
            this.logger.Debug("Authentication successful for {serviceUri}.", this.serviceUri.AbsoluteUri);

            await Task.Run(
                () =>
                    {
                        this.logger.Debug("Fetching workitem for id {parentWorkItemId}.", configuration.ParentWorkItemId);
                        this.workItemStore = new WorkItemStore(tfsProjectCollection);
                        this.parentWorkItem = this.workItemStore.GetWorkItem(configuration.ParentWorkItemId);
                        this.logger.Debug("Found parent work item '{title}'.", this.parentWorkItem.Title);
                    });
            this.logger.Verbose("Tfs service provider configuration complete.");
        }
Example #25
0
        private int GetStateCount(WorkItem wi, string fieldName, string fieldValue)
        {
            int ret = 0;

            List <DateTime> stateChangedDates = new List <DateTime>();

            foreach (Revision rev in wi.Revisions)
            {
                List <Field> fields = rev.Fields.Cast <Field>().ToList();

                if (fields.Any(x => x.Name == fieldName && x.Value != null && x.Value.ToString() == fieldValue))
                {
                    if (fields.Any(x => x.Name == "State Change Date"))
                    {
                        Field field = fields.First(x => x.Name == "State Change Date");
                        if (field.Value != null && !stateChangedDates.Contains(Convert.ToDateTime(field.Value.ToString())))
                        {
                            stateChangedDates.Add(Convert.ToDateTime(field.Value.ToString()));
                            ret += 1;
                        }
                    }
                }
            }

            return(ret);
        }
Example #26
0
        internal EffortDetails GetEffortDetailsForDuration(Duration duration)
        {
            double currentOriginalEstimate = Item.Fields[TFSLiterals.OriginalEstimate].Value.GetDoubleValue();
            double currentRemainingTime    = Item.Fields[TFSLiterals.RemainingWork].Value.GetDoubleValue();
            double currentTimeSpent        = Item.Fields[TFSLiterals.CompletedWork].Value.GetDoubleValue();
            double deviation               = 0;
            double initialRemainingTime    = 0;
            double initialTimeSpent        = 0;
            double initialOriginalEstimate = 0;

            if (Item.CreatedDate < duration.From)
            {
                Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem itemAsOf = Item.Store.GetWorkItem(Item.Id, duration.From);
                initialOriginalEstimate = itemAsOf.Fields[TFSLiterals.OriginalEstimate].Value.GetDoubleValue();
                initialRemainingTime    = itemAsOf.Fields[TFSLiterals.RemainingWork].Value.GetDoubleValue();
                initialTimeSpent        = itemAsOf.Fields[TFSLiterals.CompletedWork].Value.GetDoubleValue();
            }
            else
            {
                initialOriginalEstimate = Item.Fields[TFSLiterals.OriginalEstimate].Value.GetDoubleValue();
                initialRemainingTime    = initialOriginalEstimate;
                deviation        = initialOriginalEstimate;
                initialTimeSpent = 0;
            }

            return(new EffortDetails
            {
                Burn = (initialRemainingTime - currentRemainingTime) + (currentOriginalEstimate - initialOriginalEstimate),
                TimeSpent = currentTimeSpent - initialTimeSpent,
                Deviation = deviation
            });
        }
Example #27
0
        public bool AddToTFVC(string[] _files, WorkItem _wi, Workspace _ws)
        {
            try
             {
                 _ws.Get();
                 // Now add everything.
                 _ws.PendAdd(_files, false);
                 WorkItemCheckinInfo[] _wici = new WorkItemCheckinInfo[1];

                 _wici[0] = new WorkItemCheckinInfo(_wi, WorkItemCheckinAction.Associate);

                 if (_ws.CheckIn(_ws.GetPendingChanges(), null, null, _wici, null) > 0)
                 {
                     _ws.Delete();
                     return true;

                 }
                 else
                 {
                     return false;
                 }

             }
             catch
             {
                 return false;
             }
        }
Example #28
0
        internal static int AddLeadTaskRow(
			DataGridView dgv,
			ViewFiltersBuilder viewFiltersBuilder,
			WorkItemInfoFiller workItemInfoFiller,
			ViewColumnsIndexes viewColumnsIndexes,
			FreeDaysCalculator freeDaysCalculator,
			FocusFactorCalculator focusFactorCalculator,
			WorkItem leadTask,
			DataContainer data,
			Dictionary<int, string> planningAssignments)
        {
            dgv.Rows.Add(new DataGridViewRow());
            var leadTaskRow = dgv.Rows[dgv.Rows.Count - 1];

            List<int> blockersIds = data.BlockersDict.ContainsKey(leadTask.Id)
                ? data.BlockersDict[leadTask.Id]
                : null;
            bool shouldCheckEstimate = workItemInfoFiller.FillLeadTaskInfo(
                viewFiltersBuilder,
                leadTask,
                leadTaskRow,
                data,
                blockersIds);

            viewFiltersBuilder.MarkLeadTaskRow(leadTaskRow);

            if (blockersIds != null)
                foreach (int blockerId in blockersIds)
                {
                    AddBlockerRow(
                        dgv,
                        viewFiltersBuilder,
                        workItemInfoFiller,
                        data,
                        planningAssignments,
                        blockerId);
                }

            if (leadTask.IsProposed())
                return ScheduleFiller.AddDatesProposed(
                    viewColumnsIndexes,
                    freeDaysCalculator,
                    focusFactorCalculator,
                    leadTask,
                    leadTaskRow,
                    viewColumnsIndexes.FirstDateColumnIndex,
                    m_proposedLtMark,
                    m_proposedLtMark,
                    shouldCheckEstimate);
            return ScheduleFiller.AddDatesActive(
                viewColumnsIndexes,
                freeDaysCalculator,
                focusFactorCalculator,
                leadTask,
                leadTaskRow,
                viewColumnsIndexes.FirstDateColumnIndex,
                m_activeLtMark,
                m_activeLtMark);
        }
 public WorkItemLinkInfoDetails(WorkItemLinkInfo linkInfo, WorkItem sourceWorkItem,
     WorkItem targetWorkItem,WorkItemLinkType linkType)
 {
     this.LinkInfo = linkInfo;
     this.SourceWorkItem = sourceWorkItem;
     this.TargetWorkItem = targetWorkItem;
     this.LinkType = linkType;
 }
Example #30
0
 internal WorkItem(Tfs.WorkItem item)
     : base(
         ExceptionHandlingDynamicProxyFactory.Create <IWorkItemType>(new WorkItemType(item.Type)),
         () => ExceptionHandlingDynamicProxyFactory.Create <IFieldCollection>(new FieldCollection(item.Fields)))
 {
     _item = item;
     Url   = item.Uri.ToString();
 }
Example #31
0
        public WorkItemParser(WorkItem workItem)
        {
            this.WorkItem = workItem;

            DetailedList = new ObservableCollection<Item>();

            loadCommonData(workItem);
        }
        private void ProcessChildTestCases(ITestSuiteBase source, ITestSuiteBase target, ITestPlan targetPlan)
        {
            if (CanSkipElementBecauseOfTags(source.Id))
            {
                return;
            }


            Trace.WriteLine(string.Format("            Suite has {0} test cases", source.TestCases.Count), "TestPlansAndSuites");
            List <ITestCase> tcs = new List <ITestCase>();

            foreach (ITestSuiteEntry sourceTestCaseEntry in source.TestCases)
            {
                if (CanSkipElementBecauseOfTags(sourceTestCaseEntry.Id))
                {
                    return;
                }

                Trace.WriteLine(string.Format("    Processing {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                WorkItem wi = targetWitStore.FindReflectedWorkItem(sourceTestCaseEntry.TestCase.WorkItem, me.ReflectedWorkItemIdFieldName, false);
                if (wi == null)
                {
                    Trace.WriteLine(string.Format("    ERROR NOT FOUND {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                    break;
                }
                var exists = (from tc in target.TestCases
                              where tc.TestCase.WorkItem.Id == wi.Id
                              select tc).SingleOrDefault();

                if (exists != null)
                {
                    Trace.WriteLine(string.Format("    EXISTS {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                    ApplyConfigurations(sourceTestCaseEntry, exists);
                }
                else
                {
                    ITestCase targetTestCase = targetTestStore.Project.TestCases.Find(wi.Id);
                    if (targetTestCase == null)
                    {
                        Trace.WriteLine(string.Format("    ERROR TEST CASE NOT FOUND {0} : {1} - {2} ", sourceTestCaseEntry.EntryType, sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                    }
                    else
                    {
                        ApplyConfigurations(sourceTestCaseEntry, targetTestCase.TestSuiteEntry);
                        tcs.Add(targetTestCase);
                        Trace.WriteLine(string.Format("    ADDING {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                    }
                }
            }

            if (source.TestSuiteType == TestSuiteType.StaticTestSuite && HasChildTestCases(source))
            {
                target.TestCases.AddCases(tcs);
            }

            targetPlan.Save();
            Trace.WriteLine(string.Format("    SAVED {0} : {1} - {2} ", target.TestSuiteType.ToString(), target.Id, target.Title), "TestPlansAndSuites");
        }
        private void AddChildTestCases(ITestSuiteBase source, ITestSuiteBase target, ITestPlan targetPlan)
        {
            target.Refresh();
            targetPlan.Refresh();
            targetPlan.RefreshRootSuite();

            if (CanSkipElementBecauseOfTags(source.Id))
            {
                return;
            }

            Trace.WriteLine(string.Format("            Suite has {0} test cases", source.TestCases.Count), "TestPlansAndSuites");
            List <ITestCase> tcs = new List <ITestCase>();

            foreach (ITestSuiteEntry sourceTestCaseEntry in source.TestCases)
            {
                Trace.WriteLine($"Work item: {sourceTestCaseEntry.Id}");

                if (CanSkipElementBecauseOfTags(sourceTestCaseEntry.Id))
                {
                    return;
                }

                Trace.WriteLine(string.Format("    Processing {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                WorkItem wi = targetWitStore.FindReflectedWorkItem(sourceTestCaseEntry.TestCase.WorkItem, me.ReflectedWorkItemIdFieldName, false);
                if (wi == null)
                {
                    Trace.WriteLine(string.Format("    Can't find work item for Test Case. Has it been migrated? {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                    break;
                }
                var exists = (from tc in target.TestCases
                              where tc.TestCase.WorkItem.Id == wi.Id
                              select tc).SingleOrDefault();

                if (exists != null)
                {
                    Trace.WriteLine(string.Format("    Test case already in suite {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                }
                else
                {
                    ITestCase targetTestCase = targetTestStore.Project.TestCases.Find(wi.Id);
                    if (targetTestCase == null)
                    {
                        Trace.WriteLine(string.Format("    ERROR: Test case not found {0} : {1} - {2} ", sourceTestCaseEntry.EntryType, sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                    }
                    else
                    {
                        tcs.Add(targetTestCase);
                        Trace.WriteLine(string.Format("    Adding {0} : {1} - {2} ", sourceTestCaseEntry.EntryType.ToString(), sourceTestCaseEntry.Id, sourceTestCaseEntry.Title), "TestPlansAndSuites");
                    }
                }
            }

            target.TestCases.AddCases(tcs);

            targetPlan.Save();
            Trace.WriteLine(string.Format("    SAVED {0} : {1} - {2} ", target.TestSuiteType.ToString(), target.Id, target.Title), "TestPlansAndSuites");
        }
Example #34
0
        /// <summary>
        /// Generates the manual test.
        /// </summary>
        /// <param name="targetDirectory">The target directory.</param>
        /// <param name="workItem">The work item.</param>
        public void GenerateManualTest(string targetDirectory, WorkItem workItem)
        {
            // Create Bob the stringBuilder :-)
            StringBuilder _bob = new StringBuilder();

            // Create the XML header
            _bob.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

            // Create the root element of the manual test
            _bob.Append("<ManualTest xmlns=\"http://microsoft.com/schemas/VisualStudio/TeamTest/2006\" id=\"");
            _bob.Append(Guid.NewGuid().ToString());
            _bob.Append("\" name=\"");
            _bob.Append(workItem.Title);
            _bob.AppendLine("\">");
            _bob.AppendLine("");

            // Add the work item ID
            _bob.AppendLine("<Workitems>");
            _bob.Append("<Workitem>");
            _bob.Append(workItem.Id.ToString());
            _bob.AppendLine("</Workitem>");
            _bob.AppendLine("</Workitems>");
            _bob.AppendLine("");

            // Create the test body
            _bob.AppendLine("<BodyText>");
            _bob.Append("<![CDATA[");

            // Replace all the TFS line feeds with ones that work in the text document
            string alternateFieldName = ConfigurationManager.AppSettings["AlternateDescriptionFieldName"].ToString();
            if (string.IsNullOrEmpty(alternateFieldName))
            {
                _bob.Append(workItem.Title + "\n\r\n\r\n\r\n\r");
                _bob.Append(workItem.Description.Replace("\n","\n\r\n\r"));

            }
            else
            {
                string testDescription = workItem.Fields[alternateFieldName].Value.ToString();

                // Strip out the html
                testDescription = StripTags(testDescription);
                testDescription = workItem.Title + "\n\n" + testDescription;
                testDescription = testDescription.Replace("\n", "\n\r\n\r");
                _bob.Append(testDescription);
            }

            _bob.AppendLine("]]>");

            // Close out the document
            _bob.AppendLine("</BodyText>");
            _bob.AppendLine("</ManualTest>");

            // Write out the document to disk
            StreamWriter _streamWriter = new StreamWriter(targetDirectory + @"\" + workItem.Title + ".mtx", false);
            _streamWriter.Write(_bob.ToString());
            _streamWriter.Close();
        }
Example #35
0
        private void VisitChangesets(WorkItem workItem)
        {
            var externalLinks = workItem.Links.OfType<ExternalLink>();

            foreach (ExternalLink externalLink in externalLinks)
            {
                VisitChangeset(externalLink);
            }
        }
Example #36
0
        public MergeTask CreateMergeTask(IWorkItem parent, string taskTitle)
        {
            var tfs               = TfsTeamDataAccess.GetTfsTeamProjectCollection();
            var store             = tfs.GetService <WorkItemStore>();
            var project           = store.Projects[parent.Type.Project.Name];
            var taskType          = project.WorkItemTypes["Task"];
            var hierarchyLinkType = store.WorkItemLinkTypes[CoreLinkTypeReferenceNames.Hierarchy];

            var tfsParent = GetTfsWorkItem(parent.Id);

            if (tfsParent == null)
            {
                return(null);
            }

            var existing = (from WorkItemLink l in tfsParent.WorkItemLinks select l).ToList()
                           .Find(p => p.LinkTypeEnd.Name == "Child" && GetTfsWorkItem(p.TargetId).Title == taskTitle);

            if (existing != null)
            {
                var tfsExistingWorkItem = GetTfsWorkItem(existing.TargetId);
                return(new MergeTask(MapWorkItem(tfsExistingWorkItem))
                {
                    Parent = MapWorkItem(tfsParent)
                });
            }
            var task = new TfsWorkItem(taskType)
            {
                Title = taskTitle
            };

            task.Fields["Assigned To"].Value = "Jill LaMay";             // todo: get identity
            task.Links.Add(new WorkItemLink(hierarchyLinkType.ReverseEnd, parent.Id));

            // Check for data script and tag.
            var changesets = TfsSourceDataAccess.GetTfsChangesetsByPathName(tfs, tfsParent, "Data Scripts").ToList();             // todo: not hard code. obvs.

            if (changesets.Any())
            {
                changesets.SelectMany(s => s.Changes).GroupBy(g => g.Item.ServerItem).ToList().ForEach(f =>
                {
                    var descr  = string.Format("{0} Data Script: {1};", task.Fields["Description"].Value, f.First().Item.ServerItem);
                    task.Title = descr;                             // temp
                });
                //task.Fields["Tags"].Value = "data-script"; // todo: Not in 2012 :(
            }
            // todo: turn off save while testing
            //task.Save();

            //task.State = "Active";
            //task.Save();

            return(new MergeTask(MapWorkItem(task))
            {
                Parent = parent
            });
        }
        public void Collect(WorkItem workItem)
        {
            var changesetVisitor = new ChangesetVisitor(store, versionControlServer, visualStudioAdapter);
            changesetVisitor.ChangesetVisit += OnChangesetVisit;

            changesets = new List<ChangesetModel>();

            changesetVisitor.Visit(workItem);
        }
        // Check if we should disconnect a TR. Condition is that an external save
        // (by TFSProviderUser) has caused the TR Link field to transition from a
        // value to an empty value, This indicates disconnect.
        private EventType CheckDisconnect(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem wi,
            WorkItemChangedEvent notification,
            String user)
        {
            if (!user.Equals(HandlerSettings.TFSProviderUser, StringComparison.OrdinalIgnoreCase))
            {
                // Only disconnect based on incoming external event.
                // Disconnect by user is handled by separate code
                return(EventType.Ignore);
            }

            if (notification.ChangeType == ChangeTypes.New)
            {
                // Disconnect can only happen for a changed WI, not a new.
                return(EventType.Ignore);
            }

            // Get the current field - Disconnect case assume this is ""
            if (!wi.Fields.Contains(TFSMapper.ERICSSON_DEFECT_LINK_FIELD))
            {
                // Odd case where the mandatory field is missing
                return(EventType.Ignore);
            }

            Object trLinkValue = wi.Fields[TFSMapper.ERICSSON_DEFECT_LINK_FIELD].Value;

            if (trLinkValue == null)
            {
                return(EventType.Ignore);
            }
            String trLink = trLinkValue.ToString();

            if (trLink != null && trLink.Length > 0)
            {
                return(EventType.Ignore);
            }

            TextField[] changedTextFields = notification.TextFields;
            if (changedTextFields == null || changedTextFields.Length == 0)
            {
                // The TR Link field is a Text field - if no changes, ignore.
                return(EventType.Ignore);
            }

            // Check so also the TR Link field is changed
            for (int i = 0; i < changedTextFields.Length; i++)
            {
                String name = changedTextFields[i].ReferenceName;
                if (name.Equals(TFSMapper.ERICSSON_DEFECT_LINK_FIELD))
                {
                    return(EventType.Disconnect);
                }
            }

            return(EventType.Ignore);
        }
		private static List<WorkItemField> GetMapping(WorkItem workItem, IEnumerable<string> fields)
		{
			return (from field in fields
			        where workItem.Fields.Contains(field)
			        let workItemField = workItem.Fields[field]
			        select new WorkItemField
				        {
					        Name = field, Type = workItemField.FieldDefinition.FieldType.ToString(), Value = workItemField.Value == null ? string.Empty : workItemField.Value.ToString()
				        }).ToList();
		}
        public void ProcessWorkItemRelationships(WorkItem[] wi, bool groupbyIteration, bool dependencyAnalysis, List<TempLinkType> selectedLinks, bool hideLinks)
        {
            _full = false;
            _groupByIteration = groupbyIteration;
            _dependendyAnalysis = dependencyAnalysis;
            _selectedLinks = selectedLinks;
            _hideLinks = hideLinks;

            Process(wi);
        }
 internal static WorkItemVerificationResult VerifyAssignation(WorkItem task)
 {
     if (task.IsUnassigned())
         return new WorkItemVerificationResult
         {
             Result = VerificationResult.Warning,
             Messages = new List<string>(1) { Messages.TaskIsNotAssigned() },
         };
     return new WorkItemVerificationResult { Result = VerificationResult.Ok };
 }
 internal static WorkItemVerificationResult VerifyActiveTaskBlocking(WorkItem workItem, List<int> blockersIds)
 {
     if (workItem.IsActive() && blockersIds != null && blockersIds.Count > 0)
         return new WorkItemVerificationResult
         {
             Result = VerificationResult.Error,
             Messages = new List<string>(1) { Messages.ActiveIsBlocked(string.Join(",", blockersIds)) },
         };
     return new WorkItemVerificationResult { Result = VerificationResult.Ok };
 }
Example #43
0
        private static List<WorkItem> GetChildWorkItems(WorkItemStore store, WorkItem workitem, string queryText)
        {
            //Ref. http://blogs.msdn.com/b/jsocha/archive/2012/02/22/retrieving-tfs-results-from-a-tree-query.aspx and
              //http://blogs.msdn.com/b/team_foundation/archive/2010/07/02/wiql-syntax-for-link-query.aspx
              //https://msdn.microsoft.com/en-us/library/bb130306%28v=vs.120%29.aspx

              List<WorkItem> details = null;
              try
              {
            int id = workitem.Id;
            var treeQuery = new Query(store, queryText);
            WorkItemLinkInfo[] links = treeQuery.RunLinkQuery();

            List<int> except = new List<int>();
            except.Add(id);

            //
            // Build the list of work items for which we want to retrieve more information
            //
            int[] ids = (from WorkItemLinkInfo info in links
                     select info.TargetId).Except(except.AsEnumerable()).ToArray();

            if (ids.Length > 0)
            {
              //
              // 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 treeQuery.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(store, detailsWiql.ToString(), ids);
              details = flatQuery.RunQuery().OfType<WorkItem>().ToList();
            }
              }
              catch (Exception ex)
              {
            Console.WriteLine(ex);
              }
              return details;
        }
Example #44
0
        public Bug GetBug(WorkItem item)
        {
            var bug = new Bug();
            bug.Id = int.Parse(item.Fields["System.Id"].Value.ToString());
            bug.Title = item.Fields["System.Title"].Value.ToString();
            if (FieldExist(item, "Microsoft.VSTS.Common.Priority"))
                bug.Priority = item.Fields["Microsoft.VSTS.Common.Priority"].Value.ToString();
            if (FieldExist(item, "Microsoft.VSTS.Common.Severity"))
                bug.Severity = item.Fields["Microsoft.VSTS.Common.Severity"].Value.ToString();
            bug.Issue = item.Fields["Microsoft.VSTS.Common.Issue"].Value.ToString();
            bug.AssignedTo = item.Fields["System.AssignedTo"].Value.ToString();
            DateTime creationDate = DateTime.Parse(item.Fields["System.CreatedDate"].Value.ToString(),
                                                   CultureInfo.CurrentCulture);
            bug.CreationDate = creationDate.ToString("d MMM", CultureInfo.GetCultureInfo("en-us"));

            Dictionary<string, object> revision_prev = new Dictionary<string, object>();
            foreach (Revision rev in item.Revisions)
            {
                Dictionary<string, object> revision = new Dictionary<string, object>();
                foreach (Field field in item.Fields)
                {
                    bool addField = true;
                    if (revision_prev.ContainsKey(field.ReferenceName))
                    {
                        var objPrev = revision_prev[field.ReferenceName];
                        var objNew = rev.Fields[field.Name].Value;

                        if (objPrev != null && objNew != null)
                        {
                            if (objNew.Equals(objPrev))
                                addField = false;
                        }
                        else
                        {
                            if (objPrev != objNew)
                                addField = false;
                        }

                    }

                    if(addField)
                    {
                        revision.Add(field.ReferenceName, rev.Fields[field.Name].Value);
                    }
                }

                if (revision.Count > 0)
                {
                    bug.History.Add(revision);
                    revision_prev = revision;
                }
            }

            return bug;
        }
Example #45
0
        // UC 6: Create a TR based on a Bug.
        // Return if the bug is updated or not.
        private void createTR(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem,
            WorkItemChangedEvent notification,
            String user,
            ref Status status)
        {
            // Create the ECR
            callCreateTR(ECRMapper.mapFromWorkitem(workItem, null, ECRMapper.ACTION_CREATE), user, ref status);
            if (!status.OK)
            {
                return;
            }

            // UC 3 (one case): Update all changed attributes before handling any state change

            // Note: If adding an entry in History on create this should propagate to Progress Info, but
            // this caused Bug to appear dirty after Save, see issue 79. Given almost all fields are used on
            // create, it does not make sense to make extra update as below. TBD if we should re-add in a
            // changed form.

            //EnterpriseChangeRequest updatedEcr = ECRMapper.mapFromUpdatedWorkitem(workItem, status.TRAbout, notification);
            //if (updatedEcr != null)
            //{
            //    // Note: Failure to update will be Warning not Error, so status still OK.
            //    callUpdateTR(updatedEcr, user, null, ref status);
            //}

            // Set the ECR in state Registered
            EnterpriseChangeRequest ecr = ECRMapper.mapFromWorkitem(workItem, status.TRAbout, ECRMapper.ACTION_REGISTER_ROUTE);

            callUpdateTR(ecr, user, ECRMapper.TR_STATE_REGISTERED_S, ref status);
            if (!status.OK)
            {
                return;
            }

            // Set the ECR in state Assigned if we have a defined owner
            ecr = ECRMapper.mapFromWorkitem(workItem, status.TRAbout, ECRMapper.ACTION_ASSIGN);
            if (ecr.GetOwner() != null && ecr.GetOwner().Length > 0)
            {
                callUpdateTR(ecr, user, ECRMapper.TR_STATE_ASSIGNED_S, ref status);
                if (!status.OK)
                {
                    return;
                }
            }

            if (status.OK)
            {
                HandlerSettings.LogMessage(
                    String.Format("Created TR based on workitem named: {0}", workItem.Title),
                    HandlerSettings.LoggingLevel.INFO);
            }
        }
        private WorkItemData ConvertToWorkItemData(WorkItem wi)
        {
            WorkItemData wid = new WorkItemData
            {
                Id   = wi.Id.ToString(),
                Type = wi.Type.ToString()
            };

            PopulateRevisions(wi, wid);
            return(wid);
        }
        public void Collect(WorkItem workItem)
        {
            var changesetVisitor = new ChangesetVisitor(store, versionControlServer, visualStudioAdapter);
            changesetVisitor.ChangesetVisit += OnChangesetVisit;

            serverItems = new List<string>();

            changesetVisitor.Visit(workItem);

            ServerItems = serverItems;
        }
Example #48
0
 public TfsIssue(WorkItem workItem, HashSet<string> closedStates, TswaClientHyperlinkService hyperlinkService)
 {
     this.Id = workItem.Id;
     this.Title = workItem.Title;
     this.Description = workItem.Description;
     this.Status = workItem.State;
     this.SubmittedDate = EnsureUtc(workItem.CreatedDate);
     this.Submitter = workItem.CreatedBy;
     this.IsClosed = closedStates.Contains(workItem.State);
     this.Url = hyperlinkService.GetWorkItemEditorUrl(workItem.Id).AbsoluteUri;
 }
Example #49
0
        public WorkItemState GetWorkItemStateSummary(WorkItem workItem, string stateValue)
        {
            WorkItemState ret = new WorkItemState();

            ret.State      = stateValue;
            ret.WorkItemId = workItem.Id;
            ret.FirstDate  = GetFirstDate(workItem, "State", stateValue);
            ret.LastDate   = GetLastDate(workItem, "State", stateValue);
            ret.Count      = GetStateCount(workItem, "State", stateValue);

            return(ret);
        }
 private void PopulateRevisions(WorkItem wi, WorkItemData wid)
 {
     wid.Revisions = new List <RevisionItem>();
     foreach (Revision revision in wi.Revisions)
     {
         RevisionItem revi = new RevisionItem
         {
             Number = revision.Index,
             Index  = revision.Index
         };
         RunSourceEnrichers(revision, revi);
         wid.Revisions.Add(revi);
     }
 }
Example #51
0
        public void DisectTheShitOutOfAWorkItem()
        {
            List <string> includeFields = new List <string>();

            includeFields.Add("State Change Date");
            includeFields.Add("Board Lane");
            includeFields.Add("Board Column");
            includeFields.Add("Board Column Done");
            includeFields.Add("State");
            includeFields.Add("Changed Date");
            includeFields.Add("Revised Date");


            WorkItem wi = connect.GetWorkItem(125197);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(string.Format("{0} - {1}", wi.Id, wi.Title));

            sb.AppendLine("Current Revision");

            foreach (Field field in wi.Fields)
            {
                if (!includeFields.Contains(field.Name))
                {
                    continue;
                }

                sb.AppendLine(string.Format("Field: {0}, Value: {1}", field.Name, field.Value));
            }
            sb.AppendLine("---");
            foreach (Revision rev in wi.Revisions)
            {
                sb.AppendLine(string.Format("Revision {0}", rev.Index));
                foreach (Field field in rev.Fields)
                {
                    if (!includeFields.Contains(field.Name))
                    {
                        continue;
                    }
                    sb.AppendLine(string.Format("Field: {0}, Value: {1}", field.Name, field.Value));
                }
                sb.AppendLine("---");
            }

            string result = sb.ToString();

            string x = "";
        }
        // TODO: This is cheating as we have hardcoded knowledge where release field is.
        // Need to make this fast, but to be correct we should use regular TFSMapper way.
        public bool IsProductInMaintenance(Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem wi)
        {
            String releaseName = wi.Fields[TFSMapper.TFS_FAULTY_PRODUCT].Value.ToString();

            if (releaseName == null || releaseName.Length == 0)
            {
                // Should not happen - Mapping needs to be initialized
                HandlerSettings.LogMessage(
                    "Can not tell if product is in maintenance as the Release name not defined.",
                    HandlerSettings.LoggingLevel.WARN);
                return(false);
            }

            return(releaseToProductMap.ContainsKey(releaseName));
        }
Example #53
0
 public Tfs.Link Map(ILink link, Tfs.WorkItem item)
 {
     if (link.BaseType == BaseLinkType.RelatedLink)
     {
         var relatedLink = (IRelatedLink)link;
         var linkTypeEnd = LinkTypeEndMapper.Map(item.Store, relatedLink.LinkTypeEnd);
         return(new Tfs.RelatedLink(linkTypeEnd, relatedLink.RelatedWorkItemId));
     }
     if (link.BaseType == BaseLinkType.Hyperlink)
     {
         var hyperlink = (IHyperlink)link;
         return(new Tfs.Hyperlink(hyperlink.Location));
     }
     throw new ArgumentException("Unknown link type", nameof(link));
 }
Example #54
0
        // Update the changed fields that are mapped. Return if the bug is updated or not.
        private void updateTRFields(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem,
            WorkItemChangedEvent notification,
            String user,
            Uri about,
            ref Status status)
        {
            // UC 3 (one case): Update all changed attributes before handling any state change.
            EnterpriseChangeRequest updatedEcr = ECRMapper.mapFromUpdatedWorkitem(workItem, about, notification);

            if (updatedEcr != null)
            {
                // Note: Failure to update will be Warning not Error, so status still OK.
                callUpdateTR(updatedEcr, user, null, ref status);
            }
        }
        private ITestSuiteBase CreateNewRequirementTestSuite(ITestSuiteBase source, WorkItem requirement)
        {
            IRequirementTestSuite targetSuiteChild;

            try
            {
                targetSuiteChild = targetTestStore.Project.TestSuites.CreateRequirement(requirement);
            }
            catch (TestManagementValidationException ex)
            {
                Trace.WriteLine(string.Format("            Unable to Create Requirement based Test Suite: {0}", ex.Message), "TestPlansAndSuites");
                return(null);
            }
            targetSuiteChild.Title = source.Title;
            return(targetSuiteChild);
        }
Example #56
0
        /// <summary>
        /// Compiles the list of work items.
        /// </summary>
        /// <param name="tfsUrlPath">The TFS URL path.</param>
        /// <param name="projectName">Name of the project.</param>
        /// <param name="queryResult">The query result.</param>
        /// <returns>Child Item Collection</returns>
        public ChildItemCollection CompileListOfWorkItems(string tfsUrlPath, string projectName, QueryResult queryResult)
        {
            ChildItemCollection childItemCollection = new ChildItemCollection();

            foreach (var workItemNode in queryResult.Result)
            {
                foreach (WorkItemNode childWorkItemNode in workItemNode.Children)
                {
                    Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem = childWorkItemNode.Item;
                    ChildItem childItem = GetChildItem(tfsUrlPath, projectName, workItem);
                    childItemCollection.ChildItems.Add(childItem);
                }
            }

            return(childItemCollection);
        }
        // For call to create TR we need Ericsson user id (also domain?) - seems like we have what we want here.
        // TDOD: Try and make sure we are getting the correct attribute.
        // See http://stackoverflow.com/questions/19911368/using-the-tfs-2012-api-how-do-i-get-the-email-address-of-a-user
        static public String GetSignumForChangeNotification(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem,
            WorkItemChangedEvent notification)
        {
            TfsTeamProjectCollection tpc = workItem.Store.TeamProjectCollection;
            String userId = notification.ChangerTeamFoundationId;

            IIdentityManagementService mgmntService = tpc.GetService <IIdentityManagementService>();

            Guid[] ids = new Guid[1];
            ids[0] = new Guid(notification.ChangerTeamFoundationId);

            TeamFoundationIdentity[] members = mgmntService.ReadIdentities(ids, MembershipQuery.Direct);

            return(GetUserFromSignum(members[0].UniqueName));
        }
Example #58
0
        // Return if the workitem is updated (saved) by the handling code.
        public void handleEvent(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem,
            String user,
            WorkItemChangedEvent notification)
        {
            Status status = new Status();

            // If the user is the OSLC Provider functional user we will only update status
            // message if so needed. This as changes from the OSLC Provider originates from
            // external source = currently: MHWeb. Need revisit to allow multiple clients.
            String aboutStr = AttributesMapper.GetTfsValueForEcrKey(TFSMapper.ECM_ABOUT, workItem);

            if (!user.Equals(HandlerSettings.TFSProviderUser, StringComparison.OrdinalIgnoreCase))
            {
                if (aboutStr.Length == 0)
                {
                    // We do not have a linked TR, we need to create
                    createTR(workItem, notification, user, ref status);
                }
                else
                {
                    Uri    about        = new Uri(aboutStr);
                    Status statusAssign = null;

                    EnterpriseChangeRequest ecr        = ECRMapper.mapFromWorkitem(workItem, about, ECRMapper.ACTION_ASSIGN);
                    TeamFoundationIdentity  assignedTo = HandlerSettings.GetSignumForAssignedTo(workItem);
                    if (user != null && assignedTo != null && !user.Equals(HandlerSettings.GetUserFromSignum(assignedTo.UniqueName), StringComparison.OrdinalIgnoreCase))
                    {
                        statusAssign = new Status();
                        ecr.SetOwner(user);
                        callUpdateTR(ecr, user, ECRMapper.TR_STATE_ASSIGNED_S, ref statusAssign);
                    }

                    // We have a TR linked which might need to be updated
                    updateTR(workItem, notification, user, about, ref status);

                    if (statusAssign != null && statusAssign.OK)
                    {
                        ecr.SetOwner(HandlerSettings.GetUserFromSignum(assignedTo.UniqueName));
                        callUpdateTR(ecr, user, ECRMapper.TR_STATE_ASSIGNED_S, ref statusAssign);
                    }
                }
            }

            // Handle update of Bug
            ECRMapper.updateBug(status, user, workItem);
        }
Example #59
0
        internal bool HasStatusChangedBetweenDuration(Duration duration)
        {
            string currentStatus   = Item.State;
            string stateAtDuration = string.Empty;

            if (Item.CreatedDate < duration.From)
            {
                Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem itemAsOf = Item.Store.GetWorkItem(Item.Id, duration.From);
                stateAtDuration = itemAsOf.State;
            }
            else
            {
                stateAtDuration = StoryStatusType.New.ToString();
            }

            return(currentStatus.ToLower().CompareTo(stateAtDuration.ToLower()) != 0);
        }
        static void Main(string[] args)
        {
            Uri    uri     = new Uri("https://account.visualstudio.com");
            string PAT     = "xxxxxxxxxxxx";
            string project = "ProjectName";

            VssBasicCredential credentials = new VssBasicCredential("", PAT);

            //create a wiql object and build our query
            Wiql wiql = new Wiql()
            {
                Query = "Select * " +
                        "From WorkItems " +
                        "Where [Work Item Type] = 'User Story' " +
                        "And [System.TeamProject] = '" + project + "' " +
                        "And [System.State] <> 'Closed' " +
                        "And [System.AttachedFileCount] > 0 " +
                        "Order By [State] Asc, [Changed Date] Desc"
            };

            //create instance of work item tracking http client
            using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(uri, credentials))
            {
                //execute the query to get the list of work items in the results
                WorkItemQueryResult workItemQueryResult = workItemTrackingHttpClient.QueryByWiqlAsync(wiql).Result;

                if (workItemQueryResult.WorkItems.Count() != 0)
                {
                    //Download the first attachment for each work item.
                    foreach (var item in workItemQueryResult.WorkItems)
                    {
                        TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(uri);
                        ttpc.EnsureAuthenticated();
                        WorkItemStore wistore = ttpc.GetService <WorkItemStore>();
                        Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem wi = wistore.GetWorkItem(item.Id);
                        WorkItemServer wiserver = ttpc.GetService <WorkItemServer>();
                        string         tmppath  = wiserver.DownloadFile(wi.Attachments[0].Id);
                        string         filename = string.Format("D:\\temp\\vsts\\{0}-{1}", wi.Fields["ID"].Value, wi.Attachments[0].Name);
                        File.Copy(tmppath, filename);
                    }
                }
            }
        }