Search code examples
c#tfsazure-devopstfs-sdk

Unable to initialize a TFS store


I am trying to create a task / work item in Visual Studio Team Services (previously Visual Studio Online). My code fails because "tfsStore" returns null value causing the exception to be thrown.

NetworkCredential myNetCredentials = new NetworkCredential("*****", "******");
ICredentials myCredentials = (ICredentials)myNetCredentials;
Uri tfsUri = new Uri("https://*****.visualstudio.com/DefaultCollection/");
var tfsServer = new TfsTeamProjectCollection(tfsUri, myCredentials);
tfsServer.EnsureAuthenticated();
TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(tfsUri);
WorkItemStore tfsStore = tfsServer.GetService<WorkItemStore>(); 
if (tfsStore == null)
{
    throw new Exception("Cannot initialize TFS Store");
}
Project teamProject = tfsStore.Projects["******"];

I would appreciate any useful tips as to how to resolve the error. Thanks!


Solution

  • I've tested the code snippet below on my side, which can create a Task work item successfully, you may have a try:

    NetworkCredential myNetCredentials = new NetworkCredential("******", "******");
    TfsTeamProjectCollection tfsUri = new TfsTeamProjectCollection(new Uri("https://*****.visualstudio.com/DefaultCollection"), myNetCredentials);
    WorkItemStore tfsStore = tfsUri.GetService<WorkItemStore>();
             if (tfsStore == null)
                {
                    throw new Exception("Cannot initialize TFS Store");
                }
    
             Project teamProject = tfsStore.Projects["*****"];
             WorkItemType workItemType = teamProject.WorkItemTypes["Task"];
             WorkItem Task = new WorkItem(workItemType)
                {
                    Title = "APITask",
                };
                Task.Save();
    

    Including .net api, you can also use REST API, which is simply:

    PATCH https://{instance}/DefaultCollection/{project}/_apis/wit/workitems/${workItemTypeName}?api-version={version}