Search code examples
c#tfstfs-workitemtfs-events

How can I get a reference to the TFS WorkItem in a WorkItemChangedEvent?


Seems like this would be super simple, but I'm struggling to find what I need.

I'm implementing a TFS 2013 event handler and simply want to get a reference to the Work Item that raised the change event. It seems easy enough to get the title, but I can't find a property or method in the event signature objects that gives me either a reference to the WorkItem object or the information I'd need to go query it (e.g. the ID).

public EventNotificationStatus ProcessEvent(
         TeamFoundationRequestContext requestContext, 
         NotificationType notificationType, 
         object notificationEventArgs, 
         out int statusCode, 
         out string statusMessage, 
         out ExceptionPropertyCollection properties)
    {          
        var ev = notificationEventArgs as WorkItemChangedEvent;
        string WorkItemTitle = ev.WorkItemTitle; /* easy enough */

        /*********** need help with this bit *********/
        int ChangedWorkItemID = ???
              OR
        WorkItem ChangedWorkItem= ???
    }

Note: this code has been stripped down to bare bones to make it easier to read and focus on the problem at hand.


Solution

  • I found a way to do this. It isn't as elegant as I'd like, but it works. I'm definitely interested if anyone has a better answer.

    Here's what worked for the benefit of anyone else with the same question.

    You can get the Work Item's ID from the CoreFields.IntegerFields collection on the notificationEventArgs (of type WorkItemChangedEvent) passed into the event handler. Using that you can get the WorkItem from the WorkItemStore's GetWorkItem method.

    Note: The item you want has a field name of "ID", and it appears that it is always element 0 in the collection, but I didn't trust that always to be true so I searched on the name property using LINQ just in case. Here's a code snippet of the whole affair.

    IntegerField idField =  ev.CoreFields.IntegerFields
                              .Where<IntegerField>(field => field.Name.Equals("ID"))
                              .FirstOrDefault<IntegerField>();
    
    int WorkItemID=  idField.NewValue;
    
    //Assuming you have an initialized WorkItemStore Object here
     workItemStore.GetWorkItem(WorkItemID);