2010-06-30 27 views
6

我正在嘗試編寫一個連接到TFS並檢索工作項信息的c#應用程序。不幸的是,似乎所有使用TFS SDK的示例都使用當前用戶的默認憑證(即我的域登錄信息)。我發現的最接近的信息是使用TeamFoundationServer (String, ICredentials)構造函數,但是我找不到與接口ICredentials接口的合適類的任何信息(特別是因爲它似乎沒有使用System.Net ICredentials而是使用了TeamFoundationServer特定的ICredentials) 。如何使用特定憑證連接到C#中的TFS服務器?

有沒有人對使用特定用戶名/密碼/域組合登錄到TFS有任何洞察力?

回答

16

下面的代碼應該可以幫助您:

NetworkCredential cred = new NetworkCredential("Username", "Password", "Domain"); 
tfs = new TeamFoundationServer("http://tfs:8080/tfs", cred); 
tfs.EnsureAuthenticated(); 

domain是實際的域或工作組中的情況下,這將是承載TFS應用層的服務器的名稱。

+0

真棒工作!謝謝。 – KallDrexx 2010-06-30 15:51:29

+2

請注意'TeamFoundationServer'已被棄用,以支持'TfsConfigurationServer',但是這個代碼也適用於它。 – 2014-07-23 22:25:50

3

十年過去了,你這是怎麼用TFS 2013 API做到這一點:

// Connect to TFS Work Item Store 
ICredentials networkCredential = new NetworkCredential(tfsUsername, tfsPassword, domain); 
Uri tfsUri = new Uri(@"http://my-server:8080/tfs/DefaultCollection"); 
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(tfsUri, networkCredential); 
WorkItemStore witStore = new WorkItemStore(tfs); 

如果不工作,嘗試通過其他Credential類的憑據(爲我工作):

// Translate username and password to TFS Credentials 
ICredentials networkCredential = new NetworkCredential(tfsUsername, tfsPassword, domain); 
WindowsCredential windowsCredential = new WindowsCredential(networkCredential); 
TfsClientCredentials tfsCredential = new TfsClientCredentials(windowsCredential, false); 

// Connect to TFS Work Item Store 
Uri tfsUri = new Uri(@"http://my-server:8080/tfs/DefaultCollection"); 
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(tfsUri, tfsCredential); 
WorkItemStore witStore = new WorkItemStore(tfs); 
+0

爲什麼不直接將'NetworkCredential'傳遞給'TfsTeamProjectCollection',而不是創建兩個不必要的對象? – 2015-10-05 11:10:58

+0

嗯,我試過了,而且我得到臭名昭着的'基本身份驗證需要安全連接到服務器'的錯誤。即使在清除Windows Credential Manager條目之後,它仍然在發生。然後,我嘗試了一下,直到這使它工作。也許你是對的,你不需要它:-)只是想拯救別人的麻煩 – Heliac 2015-10-05 11:46:43

+0

感謝您的反饋 - 這是意想不到的,所以我會確保我們看看它。 – 2015-10-05 15:06:26

7

對於TFS 2015 & 2017,上述目的和方法已經(或正在)棄用。連接到TFS使用特定的憑據:

// For TFS 2015 & 2017 

    // Ultimately you want a VssCredentials instance so... 
    NetworkCredential netCred = new NetworkCredential(@"DOMAIN\user.name", @"Password1"); 
    WindowsCredential winCred = new WindowsCredential(netCred); 
    VssCredentials vssCred = new VssClientCredentials(winCred); 

    // Bonus - if you want to remain in control when 
    // credentials are wrong, set 'CredentialPromptType.DoNotPrompt'. 
    // This will thrown exception 'TFS30063' (without hanging!). 
    // Then you can handle accordingly. 
    vssCred.PromptType = CredentialPromptType.DoNotPrompt; 

    // Now you can connect to TFS passing Uri and VssCredentials instances as parameters 
    Uri tfsUri = new Uri(@"http://tfs:8080/tfs"); 
    var tfsTeamProjectCollection = new TfsTeamProjectCollection(tfsUri, vssCred); 

    // Finally, to make sure you are authenticated... 
    tfsTeamProjectCollection.EnsureAuthenticated(); 

希望這會有所幫助。

相關問題