On the verge of 2014 I wanted to share a last post with you. At the moment I am working on a migration tool to migrate from another system to TFS 2013. The source system contains a lot of items with a description that contains images. Not as an attachment but as an inline image into the description field.
TFS 2013 has the possibility to display inline images as well. You can press the inline image icon and you can even copy and paste images.
In the background TFS uploads the image to the server and creates a HTML string that looks something like this.
<img src="<collectionurl>/WorkItemTracking/v1.0/AttachFileHandler.ashx?FileNameGuid=<guid>&FileName=<filename.jpg>" />
It contains a reference to the server and a guid to a file. But how can we do this when we want to insert an inline image into a work item. The file must be uploaded to the server so just adding a image to the description field won’t work.
I wrote some simple code to achieve this in another way. The way to achieve this is to follow these steps
- Attach a picture as an attachment to a work item
- Save the work item
- Construct the right URL by using the attachment Guid
- Remove the attachment
- Save the work item
The code to do this:
private void UploadInlinePicture() { TfsTeamProjectCollection _tpc = new TfsTeamProjectCollection(new Uri("<url>")); WorkItemStore ws = _tpc.GetService(typeof(WorkItemStore)) as WorkItemStore; string pic = "path to file"; //Upload to attachmentStore WorkItem wi = ws.GetWorkItem(<workitemID>); int attachmentIndex = wi.Attachments.Add(new Attachment(pic)); wi.Save(); string attachmentGuid = wi.Attachments[attachmentIndex].FileGuid.ToString(); string originalDescription = wi.Description; string newDescription = string.Format("{0}<br><br>Image<br><img src=\"{1}/WorkItemTracking/v1.0/AttachFileHandler.ashx?FileNameGuid={2}&FileName={3}\"/>", originalDescription, _tpc.Uri.ToString(), attachmentGuid, Path.GetFileName(pic)); wi.Description = newDescription; wi.Attachments.RemoveAt(attachmentIndex); wi.Save(); }
For your convencience I added a sample application as well that has some visual help.
You can download the file here: http://1drv.ms/13SgU9M
Happy new year !
How can get back the image from the handler?
I don’t understand the question .. All the code is in the post ? What would you like to do ?