Skip to content

Instantly share code, notes, and snippets.

@pietergheysens
Created September 12, 2016 14:56
Show Gist options
  • Save pietergheysens/792ed505f09557e77ddfc1b83531e4fb to your computer and use it in GitHub Desktop.
Save pietergheysens/792ed505f09557e77ddfc1b83531e4fb to your computer and use it in GitHub Desktop.
Move inline images of work item description field to VSTS
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MoveInlineImages
{
class Program
{
static void Main(string[] args)
{
string oldTfsurl = @"todo";
string vstsUrl = @"https://todo.visualstudio.com";
string teamProject = "todo";
Uri tfsUri = new Uri(vstsUrl);
TfsTeamProjectCollection _tpc = new TfsTeamProjectCollection(tfsUri);
WorkItemStore ws = _tpc.GetService(typeof(WorkItemStore)) as WorkItemStore;
string wiql = "SELECT * FROM WorkItems WHERE [System.TeamProject] = '" + teamProject + "'";
WorkItemCollection wiCollection = ws.Query(wiql);
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential();
nc.UserName = "todo";
nc.Domain = "todo";
nc.Password = "todo";
client.Credentials = nc;
foreach (WorkItem wi in wiCollection)
{
string regExSearchForImageUrl = "(?<=<img.*src=\")[^\"]*";
MatchCollection matches = Regex.Matches(wi.Description, regExSearchForImageUrl);
string regExSearchFileName = "(?<=FileName=)[^=]*";
foreach (Match match in matches)
{
if (match.Value.Contains(oldTfsurl))
{
//save image locally and upload as attachment
Match newFileNameMatch = Regex.Match(match.Value, regExSearchFileName);
if (newFileNameMatch.Success)
{
string fullImageFilePath = @"E:\temp\ImageFileDownloads\" + newFileNameMatch.Value;
client.DownloadFile(match.Value, fullImageFilePath);
int attachmentIndex = wi.Attachments.Add(new Attachment(fullImageFilePath));
wi.Save();
string attachmentGuid = wi.Attachments[attachmentIndex].FileGuid;
string newImageLink = String.Format("{0}/WorkItemTracking/v1.0/AttachFileHandler.ashx?FileNameGuid={1}&amp;FileName={2}", _tpc.Uri.ToString(), attachmentGuid, newFileNameMatch.Value);
wi.Description = wi.Description.Replace(match.Value, newImageLink);
wi.Attachments.RemoveAt(attachmentIndex);
wi.Save();
}
else
{
//no match
Console.WriteLine("no match here");
}
}
}
}
client.Dispose();
}
}
}
@ravikaliappan
Copy link

ravikaliappan commented Nov 21, 2017

How to check whether the image is already exist with FileNameGuid?
or Where it is stored?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment