Uncategorized

Opening Work items in Visual Studio “15” Preview

If you have used Visual Studio “15” Preview to connect to a Team Services instance, or you follow the Microsoft ALM blog you will have noticed that with the Visual Studio “15” Preview: Work items now open in the web from Visual Studio ’15’!

While the official post shows why that change was made and what advantages the web form brings, I wanted to quickly point out some small things that were done to make this behavior more usable.

You can follow along by downloading the Visual Studio “15” Preview and connecting to your Team Services or Team Foundation Server “15” RC1 instance.

Running Queries from Visual Studio

There is still the full work item query tree available in Visual Studio, including favorites:

team-explorer

You can also still create and run new or existing queries and look at the results:

query-1

If you look at the screenshot above, you can see that I have run the “My Bugs” query and that I have selected the second work item from the result, with id 62. When I open this work item now, it will launch in my browser and display the now familiar modern work item form:

Opened Work Item

And if you look closely, you can see that in the upper right hand corner of the work item form it displays “2 of 4” and some buttons:

query-3

When you open a work item from a query result in Visual Studio, we don’t want you lose the query context you were in. So, when opening the work item we pass some context information along, in this case this included the name of the query that you ran and the position of the work item inside of that query result. Then, in the web we can restore this context, show you the work item, and also give you the option to easily switch to the next/previous work item in the “My Bugs” query:

query-4

You can also just return to the full query result in the web:

query-5

Preserving the context this way works with all queries in Visual Studio, even new and unsaved ones.

New, unsaved query in Visual Studio

New, unsaved query in Visual Studio

Work item opened from query result in web

Work item opened from query result in web

Web query editor

Web query editor

Linking Work Items to Code Changes

With the Development section on the new work item form we have made it really easy to view code changes that contributed to work item, be it he implementation of a feature or a bugfix:

commit-dnd-result.png

To associate your code changes with your work items you can create a link after the fact from the work item form, or in Visual Studio when you commit or check in your code. For both Git and TFVC you can still run work item queries from the Changes or Pending Changes view and even drag and drop work items from the query result to the Related Work Items section. Adding a work item to a git commit:

Adding a related work item to a git commit

Adding a related work item to a git commit

Sommerurlaub auf Kauai in Hawaii — 10hourflight

Miriam’s blog (in German) about what we do when we are not working at MSFT:

Da wir so nah wohnen, dachten wir, fliegen wir mal nach Hawai’i. Im Mai war es endlich soweit – 10 Tage auf Kaua’i, eine der kleineren Insel des Staates Hawai’i im Norden. Da sonst nicht so viel passiert ist im Mai, hier ein ausführlicher Bericht!

via Sommerurlaub auf Kauai in Hawaii — 10hourflight

VSTS Tags MRU extension – Part 2

In the last post we ended up with a list of tags a user added last to a work item. The next step is now to keep an MRU list with tags from earlier sessions and update it when new tags are added.

Every time the user adds tags to a work item we want to merge these new tags with the (persisted) list of tags. We will keep a maximum of N tags and need to either only add tags to the list (if |tags| < N), or and and remove (if |tags| > N), or just reorder the tags in the list, so that the most recently used tags appear first in the final dropdown menu.

Keeping MRU list of tags

We want to store at maximum 5 tags for now, so we add a constant to our app.ts:

/** Maximum size of MRU */
const MAX_TAGS = 5;

And as before, we implement our business logic as a simple singleton:

class Tags {
  /** Key used for document service */
  private static KEY: string = "tags";
  private static instance: Tags = null;

  /** Get or create singleton instance */
  public static getInstance(): Tags {
    if (!Tags.instance) {
      Tags.instance = new Tags(MAX_TAGS);
    }

    return Tags.instance;
  }

  constructor(private maxCount: number) {
  }
}

This class needs to keep track of

  • what tags are currently in the MRU list
  • the order of tags

While we could maintain a dictionary depicting whether a tag is in the list and a queue with the MRU order, for only 5 tags a simple array is probably be enough.

private queue: string[] = [];

Now, when we add tag, and it is not in the queue yet, we just add it in front of the queue, or we delete it from its current position in the queue and then add it in front of the queue.

In order to maintain our maximum of 5 tags, we add another method prune, that removes tags from the end of the queue if the overall count is more than the configured max and call it

public addTag(tag: string) {
  // Remove tag from current position
  var idx = this.dict[tag];
  if (idx !== -1) {
    this.queue.splice(idx, 1);
  }

  // Add tag in first position and record position
  this.queue.unshift(tag);

  this.prune();
}

/** Ensure only maximum number of tags configured is stored */
private prune() {
  if (this.queue.length < this.maxCount) {
    for (var i = 0; i < this.queue.length - MAX_TAGS; ++i) {
      this.queue.pop();
    }
  }
}

For later displaying tags in the context menu, we can just return the current queue which contains our tags in the correct order

public getTags(): string[] {
  return this.queue;
}

Persisting Data from an extension

The VSTS framework provides the ExtensionDataService which allows us to store key/value pairs or collections of JSON documents on the VSTS servers. Usage is quite simple, to store a value we just need to get an instance of the service, and call setValue with a key and a value. The value can be as simple as a string, or an JS object that’s transparently serialized to JSON. We can also pass a scope, that limits values either to an “account” or a “user” scope:

VSS.getService(VSS.ServiceIds.ExtensionData).then((dataService) => {
  dataService.setValue("key", "value", { scopeType: "User" });
});

For the tags extension we want a user scope and our value to store will be an array of strings containing our tags.

Persisting Tags

First step is again to add another import to our app.ts file:

import VSS_Extension_Service = require("VSS/SDK/Services/ExtensionData");

To keep it simple, loading tags is something we’d like to do only once at the beginning of a session, and then save every time tags are added. This way, we might run into conflicts if the user is working with different browser tabs/windows at the same time, but for this sample that last-write-wins concurrency is enough.

Using the ExtensionDataService we can modify the getInstance call to retrieve the list of tags from the data service using getValue and add every one using the addTag method we implemented above. Since service calls use Promises, we change getInstance to return a promise instead of a value. If the instance has already been created, we use Q(<value>) to return an immediately resolved promise, otherwise we retrieve tags and then create the instance:

/** Get or create singleton instance */
public static getInstance(): IPromise<Tags> {
  if (Tags.instance) {
    return Q(Tags.instance);
  } else {
    return VSS.getService(VSS.ServiceIds.ExtensionData).then(
      (dataService: VSS_Extension_Service.ExtensionDataService) => {
      return dataService.getValue(Tags.KEY, {
        defaultValue: [],
        scopeType: "User"
      }).then((savedTags: string[]) => {
        Tags.instance = new Tags(MAX_TAGS);
        if (savedTags) {
          savedTags.forEach(t => Tags.instance.addTag(t));
        }

        return Tags.instance;
      });
    });
  }
}

Persisting tags will be done in another method, again getting a service instance (we could cache the instance), and calling then calling setValue. A promise is returned to allow callers to wait for the end of the call:

public persist(): IPromise<any> {
  return VSS.getService(VSS.ServiceIds.ExtensionData).then(
    (dataService: VSS_Extension_Service.ExtensionDataService) => {
      dataService.setValue(Tags.KEY, this.queue, {
        scopeType: "User"
      });
    });
}

Since we do want to show the tag context menu as fast as possible, we will proactively initialized that tag service as soon as the extension file is loaded:

// Proactively initialize instance and load tags
Tags.getInstance();

Showing Tags in work item context menu

We are nearly done,

// Register context menu action
VSS.register("tags-mru-work-item-menu", {
  getMenuItems: (context) => {
    return Tags.getInstance().then(tags => {
      var childItems: IContributedMenuItem[] = [];
      tags.getTags().forEach(tag => {
        childItems.push(<IContributedMenuItem>{
          text: tag,
          title: `Add tag: ${tag}`,
          action: () => {});
        });
      });

      if (childItems.length === 0) {
        childItems.push(<IContributedMenuItem>{
          title: "No tag added",
          disabled: true
        });
      }

      return [<IContributedMenuItem>{
        title: "Recent Tags",
          childItems: childItems
        }]
      });
   });
});

 

Updating work items

Final step is to add an action to the child menu items to actually add the tag to all selected work items. First we need to determine the selected work items. Unfortunately, the different VSTS views are not consistent in exposing the ids of selected work items right now. We need to look for different properties in the passed context depending on the view we are in. The logic is:

  • Backlog – array of numbers called workItemIds
  • Boards (Kanban/Iteration) – single number called id
  • Query results – array of numbers called ids

To unify in an array called ids we need to add the following code to the beginning of the getMenuItems method:

// Not all areas use the same format for passing work item ids.
// "ids" for Queries, "workItemIds" for backlogs, "id" for boards
var ids = context.ids || context.workItemIds;
if (!ids || context.id) {
  // Boards only support a single work item
  ids = [context.id];
}

Then, in the action handler of our child menu items, we need to:

  1. Get the work items
  2. For each work item
    1. Get the existing value for the System.Tags field
    2. Concatenate with the tag to add using “;” as separator
    3. Update work item

Since we are changing work items not opened in any form right now, we need to use the REST API for the update operations. Some additional imports are required:

import TFS_Wit_Contracts = require("TFS/WorkItemTracking/Contracts");
import TFS_Wit_Client = require("TFS/WorkItemTracking/RestClient");
import TFS_Wit_Services = require("TFS/WorkItemTracking/Services");

Then we just get an http client and start iterating over the work items:

// Get work items, add the new tag to the list of existing tags, then update
var client = TFS_Wit_Client.getClient();
client.getWorkItems(ids).then((workItems) => {
  for (var workItem of workItems) {
    client.updateWorkItem([{
      "op": "add",
      "path": "/fields/System.Tags",
      "value": (workItem.fields["System.Tags"] || "") + ";" + tag
    }], workItem.id);
  }
});

(Potential optimization would be to use the batch API for the work item updates instead of making a single call per work item)

All done

That’s it. The extension is done, can be published, and should mostly work as designed. I say mostly, because, if you remember, I mentioned earlier that there is one drawback, for which no workaround exists yet: When we add a tag, we need to use the REST API to update the work items. When we do this, the current VSTS view does not know that a work item has been updated, and does not refresh automatically.

Ideally, there would be a way to tell VSTS from an extension that a work item has been changed, but no such service is exposed at the moment. This means, users have to manually refresh the view or a specific work item after using the extension to add a new tag. For example like in this short gif (click to view full screen):

add-tag

I do think, however, that the extension still provides value, and will publish it in the marketplace soon. Let me me know in the comments if anything is unclear or doesn’t work.

Again, the code is available at https://github.com/cschleiden/vsts-extension-tags-mru. Small details might vary, but I mostly tried to keep these posts and the code in sync.

Extending VSTS – Setup

Last year Visual Studio Team Services (formerly known as Visual Studio Online) released support for extensions. There are some great samples on GitHub and a growing number of finished extensions in the marketplace. One of my published extensions is Estimate, a planning poker implementation for VSTS.

Extending VSTS is really easy, there is documentation and some great examples at the official GitHub repository.

Since I work on the Agile planning tools and work item tracking, I would like to show with a few simple examples how you can add functionality to your backlogs, boards, and queries. To make it really easy I’ve published  a small seed project that contributes a single menu item to the work item context menu and which will be the base for some extensions with a bit more functionality. If you’re already familiar with VSTS extensions feel free to skip immediately to part 2.

image

The seed project is available at GitHub; here is a step by step description how to build, publish, and install it:

  1. First you need a VSTS account, it’s free, just register with your Microsoft account.
  2. Create a publisher: With your Microsoft account, sign in at the marketplace and pick an ID and a display name:
    image
  3. Generate a personal access token: Login to VSTS, go to My Security:

    security

    then to the Personal access tokens section:

    image

    generate a token for All accessible accounts:

    image
    copy and save the generate token for later:

    image
  4. Clone (or download as zip and extract) the seed project from:
    https://github.com/cschleiden/vsts-extension-ts-seed-simple
  5. Install nodejs
  6. cd into the folder where you placed the project in step 4
  7. Install required dependencies with
    npm install
  8. Open the extension manifest, vss-extension.json
  9. Change <your-publisher> to the publisher ID you created in step 2:

    image
  10. As part of step 5, the TFS Cross Platform Command Line Interface was installed. This will be used to package and publish the extension. Login to your account by executing
    tfx login --service-url https://marketplace.visualstudio.com

    when prompted for the token, use the one generated in step 3. This will save the login information for subsequent operations:
    image(Update: the uri has changed, please use https://marketplace.visualstudio.com)

  11. Finally, execute
    grunt publish-dev
    to build, package, and publish the extension using the development configuration. If everything works the output should be similar to this:

    image
  12. Share with your account: The extension has now been published as a private extension, no one else can see it yet. To test it, we need to share it with our account. There are two ways, one is using the tfx command line, the other is using again the Marketplace. When you login again you should now see the extension and a Share button:

    image

    Just share it with your account

    image
  13. Install: After sharing the extension, it should show up in the Manage extensions page of your VSTS account:

    image
    to install, select it, confirm, and allow the requested OAuth scopes:

    imageimage

    image
  14. Test: If you now navigate to a query result (create a query and some work items if you haven’t) and open the context menu for any work item, you should see the menu action contributed by the extension:

    image
    click will execute the registered action and show the id of the selected work item:

    image

Windows Phone 7 and Silverlight Slider Binding Bug

It took me about 4-5 hours today to finally recognize why one my custom controls behaved in a strange way. It is a control derived from the Silverlight slider control and I encountered strange behavior when binding the Maximum and Minimum properties. After countless checks to make sure, that my ViewModel logic was flawless I finally discovered that … the order of attributes in the xaml code *does* matter when binding these exact properties.

It turns out, instead of this

<Slider Name="slider" Grid.Column="1" Minimum="{Binding MinValue}" Maximum="{Binding MaxValue}" />

it should be this:


<Slider Name="slider" Grid.Column="1" Maximum="{Binding MaxValue}" Minimum="{Binding MinValue}" />

(Source: http://social.msdn.microsoft.com/Forums/en-US/silverlightgeneral/thread/5a08a3c7-66d3-4ee0-aa29-43bb8d186ab7)

Other people have noticed the same: http://dotnetbyexample.blogspot.com/2009/08/bind-silverlight-3-slider-value-minimum.html