public bool Authenticate(string url, string userId, string password, string domain) { try { NetworkCredential credential = new NetworkCredential(userId, password, domain); WindowsCredential winCred = new WindowsCredential(credential); VssCredentials vssCred = new VssClientCredentials(winCred) { PromptType = CredentialPromptType.DoNotPrompt }; using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(url), vssCred)) { tpc.EnsureAuthenticated(); return(true); } } catch (TeamFoundationServiceUnavailableException ex) { logger.Error(ex, "Service not available"); throw new ServiceUnavailableException(url, "Service not Available", ex); } catch (TeamFoundationServerUnauthorizedException ex) { logger.Error(ex, "Authentication Failure."); throw new TFSAuthenticationException("Authentication Failure.", ex); } catch (Exception ex) { logger.Error(ex, "Authentication Failure."); throw; } }
public static void connectToTFS() { // catch the authentication error try { // create the connection to the TFS server NetworkCredential netCred = new NetworkCredential(DomainName, Password); Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(netCred); VssCredentials vssCred = new VssCredentials(winCred); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://tfs.mtsit.com/STS/"), vssCred); tpc.Authenticate(); workItemStore = tpc.GetService <WorkItemStore>(); workItem = workItemStore.GetWorkItem(Program.itemId); // create web link for tfs id tfsLink = tpc.Uri + workItem.AreaPath.Remove(workItem.AreaPath.IndexOf((char)92)) + "/_workitems/edit/"; // create path and name to html file PathToHtml = PathToTasks + workItem.Type.Name + " " + workItem.Id + ".html"; // create path and folder name for attachments PathToAttach = PathToTasks + workItem.Id; } catch (Exception ex) { Program.exExit(ex); } }
public static void LookupBranchesOnline() //Dictionary<string, string> { Uri tfsUri = new Uri(AppUtils.GetAppSetting <string>("TFPath")); //var vssCredentials = new VssCredentials("", ); NetworkCredential netCred = new NetworkCredential(@"DOMAIN\user.name", @"Password1"); var winCred = new Microsoft.VisualStudio.Services.Common.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 var tfsTeamProjectCollection = new TfsTeamProjectCollection(tfsUri, vssCred); // Finally, to make sure you are authenticated... tfsTeamProjectCollection.EnsureAuthenticated(); var tfs = new TfsTeamProjectCollection(tfsUri); var identity = tfs.AuthorizedIdentity; tfs.Authenticate(); var versionControlServer = tfs.GetService <VersionControlServer>(); var workspaces = versionControlServer.QueryWorkspaces(null, null, null, WorkspacePermissions.NoneOrNotSupported); foreach (var ws in workspaces) { string comment = ws.Comment; } }
private static void Authenticate(TFSCredentials credentials) { NetworkCredential netCred = new NetworkCredential(credentials.username, credentials.password); Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(netCred); VssCredentials vssCred = new VssClientCredentials(winCred); _tfs = new TfsTeamProjectCollection(new Uri("https://tfs.aurigo.com/tfs/DefaultCollection"), vssCred); _tfs.Authenticate(); }
static void Main(string[] args) { NetworkCredential networkCredentials = new NetworkCredential(@"Domain\Account", @"Password"); Microsoft.VisualStudio.Services.Common.WindowsCredential windowsCredentials = new Microsoft.VisualStudio.Services.Common.WindowsCredential(networkCredentials); VssCredentials basicCredentials = new VssCredentials(windowsCredentials); TfsTeamProjectCollection tfsColl = new TfsTeamProjectCollection( new Uri("http://XXX:8080/tfs/DefaultCollection"), basicCredentials); tfsColl.Authenticate(); // make sure it is authenticate }
public List <WorkItem> GetWorkItemByIds(List <int> taskIdList, string serverUrl, string credentialHash) { WorkItemCollection col = null; try { NetworkCredential credential = JsonConvert.DeserializeObject <NetworkCredential>(credentialHash.Decrypt()); WindowsCredential winCred = new WindowsCredential(credential); VssCredentials vssCred = new VssClientCredentials(winCred); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(serverUrl), vssCred); if (taskIdList == null || taskIdList.Count == 0) { throw new Exception("Task List cannot be empty"); } string iterationQuery = "'" + taskIdList[0].ToString() + "' "; foreach (int taskId in taskIdList) { iterationQuery = "OR '" + taskId + "' "; } string query = "Select * From WorkItems Where [Id] = " + iterationQuery + "Order By [State] Asc, [Changed Date] Desc"; WorkItemStore wis = new WorkItemStore(tpc); col = wis.Query(query); List <WorkItem> wil = new List <WorkItem>(); for (int i = 0; i < col.Count; i++) { wil.Add(wil[i]); } return(wil); } catch (TeamFoundationServiceUnavailableException ex) { logger.Error(ex, "Service not available"); throw new ServiceUnavailableException(serverUrl, "Service not Available", ex); } catch (TeamFoundationServerUnauthorizedException ex) { logger.Error(ex, "Authentication Failure."); throw new TFSAuthenticationException("Authentication Failure.", ex); } catch (Exception ex) { logger.Error(ex, "Authentication Failure."); throw; } }
//////////////////////////////////////////////////////////////////////////////////////////////////////// #region Private Methods private async Task <TfsTeamProjectCollection> OpenCollectionAsync(TfsConnectionInformation connectionInformation) { do { try { if (_retries > 1) { await Task.Delay(RetryDelayInMilliseconds); } TfsTeamProjectCollection tpc; if (connectionInformation.IntegratedSecurity) { tpc = new TfsTeamProjectCollection(new Uri(connectionInformation.TfsAddress)); tpc.EnsureAuthenticated(); } else { var netCred = new NetworkCredential(connectionInformation.Username, connectionInformation.Password); var windowsCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(netCred); var vssCred = new VssCredentials(windowsCred); tpc = new TfsTeamProjectCollection(new Uri(connectionInformation.TfsAddress), vssCred); tpc.Authenticate(); } return(tpc); } catch (WebException) { if (_retries + 1 > MaxRetries) { throw; } _retries++; } catch (TeamFoundationServiceUnavailableException) { if (_retries + 1 > MaxRetries) { throw; } _retries++; } } while (true); }
public bool Authenticate(int tfsId, string credentialHash) { TeamServer teamServer = null; string url = string.Empty; try { using (TeamServerRepository teamServerRepository = new TeamServerRepository()) { teamServer = teamServerRepository.GetById(tfsId); if (teamServer == null) { throw new Exception(string.Format("Invalid Team Server Id : {0}", tfsId)); } } url = teamServer.Url; NetworkCredential credential = JsonConvert.DeserializeObject <NetworkCredential>(credentialHash.Decrypt()); WindowsCredential winCred = new WindowsCredential(credential); VssCredentials vssCred = new VssClientCredentials(winCred) { PromptType = CredentialPromptType.DoNotPrompt }; using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(url), vssCred)) { tpc.EnsureAuthenticated(); return(true); } } catch (TeamFoundationServiceUnavailableException ex) { logger.Error(ex, "Service not available"); throw new ServiceUnavailableException(url, "Service not Available", ex); } catch (TeamFoundationServerUnauthorizedException ex) { logger.Error(ex, "Authentication Failure."); throw new TFSAuthenticationException("Authentication Failure.", ex); } catch (Exception ex) { logger.Error(ex, "Authentication Failure."); throw; } }
private static TfsTeamProjectCollection GetTfsTeamProjectCollection(string server, string creds, string personalAccessToken) { var uri = TfsTeamProjectCollection.GetFullyQualifiedUriForName(server); if (creds == null) { Logger.Info("using personalAccessToken"); return(personalAccessToken == null ? new TfsTeamProjectCollection(uri, new VssClientCredentials()) : new TfsTeamProjectCollection(uri, new VssBasicCredential(string.Empty, personalAccessToken))); } Logger.Info("using creds"); var credsLocal = Regex.Match(creds, SyncUtil.CredsPatternDomain).Groups; var networkCred = new NetworkCredential(credsLocal[1].Value, credsLocal[2].Value, credsLocal[3].Value); var windowsCred = new WindowsCredential(networkCred); return(new TfsTeamProjectCollection(uri, new VssClientCredentials(windowsCred, CredentialPromptType.DoNotPrompt))); }
public List <WorkItem> GetWorkItemByQuery(string query, string serverUrl, string credentialHash) { WorkItemCollection col = null; try { NetworkCredential credential = JsonConvert.DeserializeObject <NetworkCredential>(credentialHash.Decrypt()); WindowsCredential winCred = new WindowsCredential(credential); VssCredentials vssCred = new VssClientCredentials(winCred); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(serverUrl), vssCred); if (query == null) { throw new Exception("Query cannot be empty"); } WorkItemStore wis = new WorkItemStore(tpc); col = wis.Query(query); List <WorkItem> wil = new List <WorkItem>(); for (int i = 0; i < col.Count; i++) { wil.Add(col[i]); } return(wil); } catch (TeamFoundationServiceUnavailableException ex) { logger.Error(ex, "Service not available"); throw new ServiceUnavailableException(serverUrl, "Service not Available", ex); } catch (TeamFoundationServerUnauthorizedException ex) { logger.Error(ex, "Authentication Failure."); throw new TFSAuthenticationException("Authentication Failure.", ex); } catch (Exception ex) { logger.Error(ex, "Authentication Failure."); throw; } }
/// <summary> /// Retrieves a Work Item by ID from the configured server. /// </summary> /// <param name="taskId">Task Id.</param> /// <param name="serverUrl">Server URL.</param> /// <param name="credentialHash">The hash for authentication.</param> /// <returns></returns> public WorkItem GetWorkItemById(int taskId, string serverUrl, string credentialHash) { WorkItemCollection col = null; try { NetworkCredential credential = JsonConvert.DeserializeObject <NetworkCredential>(credentialHash.Decrypt()); WindowsCredential winCred = new WindowsCredential(credential); VssCredentials vssCred = new VssClientCredentials(winCred); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(serverUrl), vssCred); string query = "Select * From WorkItems Where [Id] = '" + taskId + "' " + "Order By [State] Asc, [Changed Date] Desc"; WorkItemStore wis = new WorkItemStore(tpc); col = wis.Query(query); if (col.Count > 0) { return(col[0]); } else { return(null); } } catch (TeamFoundationServiceUnavailableException ex) { logger.Error(ex, "Service not available"); throw new ServiceUnavailableException(serverUrl, "Service not Available", ex); } catch (TeamFoundationServerUnauthorizedException ex) { logger.Error(ex, "Authentication Failure."); throw new TFSAuthenticationException("Authentication Failure.", ex); } catch (Exception ex) { logger.Error(ex, "Authentication Failure."); throw; } }
static void Main(string[] args) { Console.Title = "CopyWorkItemFromTFStoHTMLandDownloadAttachment"; string configFile = @"CopyWorkItemFromTFStoHTMLandAttach2.conf"; int itemId; string[] config = null; // string array for read the config while (true) { // read the config file until success if (Config.callReadConfig(configFile, ref config)) { break; } } while (true) { Console.WriteLine("Enter TFS number or 'config' for modify [login/password/path to attach] in config file.\n"); Console.Write("Input TFS id (or 'config'): "); //int itemId = 1936268; itemId = Input.processingInput(); if (itemId == -1) { Config.callEditConfig(configFile); while (true) { // read the config file until success if (Config.callReadConfig(configFile, ref config)) { break; } } continue; } break; } // save the configuration for operate with // domain and login save from config as is string DomainName = config[0]; // decrypting password from config string Password = Cipher.Decrypt(config[1], Key); // add the last '\' to path if it's not entered by user in config string pathToTasks = (config[2].EndsWith("\\") ? config[2] : config[2] + "\\"); // ask if user want to download the attachments or not Console.Clear(); Console.Write("Download the Attachments? (y/n): "); bool confirm = Input.downloadConfirm(); // current state of program progress Console.Clear(); Console.Write("Creating the HTML file..."); // create the connection to the TFS server NetworkCredential netCred = new NetworkCredential(DomainName, Password); Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(netCred); VssCredentials vssCred = new VssCredentials(winCred); TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://tfs.mtsit.com/STS/"), vssCred); // catch the authentication error try { tpc.Authenticate(); } catch (Exception ex) { exExit(ex); } WorkItemStore workItemStore = tpc.GetService <WorkItemStore>(); WorkItem workItem = null; // catch not existed TFS id try { workItem = workItemStore.GetWorkItem(itemId); } catch (Exception ex) { exExit(ex); } // create web link for tfs id string tfsLink = tpc.Uri + workItem.AreaPath.Remove(workItem.AreaPath.IndexOf((char)92)) + "/_workitems/edit/"; // create path and name to html file string pathToHtml = pathToTasks + workItem.Type.Name + " " + workItem.Id + ".html"; // create path and folder name for attachments string pathToAttach = pathToTasks + workItem.Id; FileStream fileStream = null; StreamWriter streamWriter = null; // create/open the html file for write in to it if (File.Exists(pathToHtml)) { fileStream = new FileStream(pathToHtml, FileMode.Truncate); } else { fileStream = new FileStream(pathToHtml, FileMode.CreateNew); } streamWriter = new StreamWriter(fileStream); // fill in the html file // head, title, encoding streamWriter.WriteLine("{0}", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"); streamWriter.WriteLine("{0}", "<html>"); streamWriter.WriteLine("<head>{0}</head>", "<meta charset=\"UTF-8\">"); streamWriter.WriteLine("<title>{0} {1}</title>", workItem.Type.Name, workItem.Id); streamWriter.WriteLine("{0}", "<body>"); streamWriter.WriteLine("{0}", ""); // short info block: 'name', 'id', 'title', 'state' and 'assigned to' info of work item streamWriter.WriteLine(@"<p><font style=""background-color:rgb(255, 255, 255); color:rgb(0, 0, 0); font-family:Segoe UI; font-size:12px;"">" + workItem.Type.Name + " " + workItem.Id + ": " + workItem.Title + @"</font></p>"); streamWriter.WriteLine(@"<p style=""border: 1px solid; color: red; width: 50%;"">" + @"<font style=""background-color:rgb(255, 255, 255); color:rgb(0, 0, 0); font-family:Segoe UI; font-size:12px;"">" + workItem.Type.Name + " is <b>" + workItem.State + (workItem.State == "Closed" ? "</b>" : "</b> and Assigned To <b>" + workItem.Fields["Assigned To"].Value + "</b>") + @"</font></p>"); // blok 'title' streamWriter.WriteLine(@"<div style=""border: 1px solid black; background-color:lightgray;"">TITLE:</div>"); streamWriter.WriteLine("<p>{0}</p>", workItem.Title); // block 'description' streamWriter.WriteLine(@"<div style=""border: 1px solid black; background-color:lightgray;"">DESCRIPTION:</div>"); if (workItem.Type.Name == "Bug" || workItem.Type.Name == "Issue") { streamWriter.WriteLine(workItem.Fields["REPRO STEPS"].Value); } else if (workItem.Type.Name == "Task") { streamWriter.WriteLine(workItem.Fields["DESCRIPTION"].Value); } // block 'history' streamWriter.WriteLine(@"<div style=""border: 1px solid black; background-color:lightgray;"">HISTORY:</div><br>"); for (int i = workItem.Revisions.Count - 1; i >= 0; i--) { streamWriter.WriteLine(@"<font style=""background-color:rgb(255, 255, 255); color:rgb(0, 0, 0); font-family:Segoe UI; font-size:12px; font-weight:bold;"">" + workItem.Revisions[i].Fields["Changed By"].Value + @"</font><br>"); if (workItem.Revisions[i].Fields["History"].Value.Equals("")) { streamWriter.WriteLine(workItem.Revisions[i].Fields["History"].Value); } else { streamWriter.WriteLine(workItem.Revisions[i].Fields["History"].Value + "<br>"); } streamWriter.WriteLine(@"<font style=""background-color:rgb(255, 255, 255); color:rgb(128, 128, 128); font-family:Segoe UI; font-size:12px;"">" + " " + workItem.Revisions[i].Fields["State Change Date"].Value + @"</font><br><br>"); } // block with linked work items. in table streamWriter.WriteLine(@"<div style=""border: 1px solid black; background-color:lightgray;"">ALL LINKS:</div>"); streamWriter.WriteLine(@"<p><table style=""width:100%; font-family:Segoe UI; font-size:12px;"">"); streamWriter.WriteLine(@"<tr><th align=""left"">Link Type</th> <th align=""left"">Work Item Type</th> <th align=""left"">ID</th> <th align=""left"">State</th> <th align=""left"">Title</th> <th align=""center"">Assigned To</th></tr>"); foreach (WorkItemLink link in workItem.WorkItemLinks) { WorkItem wiDeliverable = workItemStore.GetWorkItem(link.TargetId); streamWriter.WriteLine(@"<tr><td>{0}</td>", link.LinkTypeEnd.Name); streamWriter.WriteLine(@"<td>{0}</td>", wiDeliverable.Type.Name); streamWriter.WriteLine(@"<td><a href=""{0}{1}"">{1}</a></td>", tfsLink, wiDeliverable.Id); streamWriter.WriteLine(@"<td>{0}</td>", wiDeliverable.State); streamWriter.WriteLine(@"<td>{0}</td>", wiDeliverable.Title); streamWriter.WriteLine(@"<td>{0}</td></tr>", wiDeliverable.Fields["Assigned To"].Value); } streamWriter.WriteLine(@"</table></p>"); // block with the web link to the thin client on to work item streamWriter.WriteLine(@"<div style=""border: 1px solid black; background-color:lightgray;"">LINK:</div>"); streamWriter.WriteLine(@"<p><a href=""{0}{1}"">{0}{1}</a></p>", tfsLink, workItem.Id); // current state of program progress Console.Clear(); Console.Write("Search folder for attach..."); Thread.Sleep(700); // create the path to directory for saving attachments and search if the dir alredy exist DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(pathToTasks); FileSystemInfo[] filesAndDirs = hdDirectoryInWhichToSearch.GetFileSystemInfos("*" + workItem.Id + "*"); // if folder for attach alredy exists change the the default name to it foreach (FileSystemInfo foundDir in filesAndDirs) { if (foundDir.GetType() == typeof(DirectoryInfo)) { pathToAttach = foundDir.FullName; } } // if folder exists, add the link to it if (Directory.Exists(pathToAttach) || confirm) { // block with link to folder with attacments streamWriter.WriteLine(@"<div style=""border: 1px solid black; background-color:lightgray;"">ATTACHMENTS:</div>"); streamWriter.WriteLine(@"<p><a href=""{0}"">{0}</a></p>", pathToAttach); } streamWriter.WriteLine("{0}", "</body>"); streamWriter.WriteLine("{0}", "</html>"); streamWriter.Close(); fileStream.Close(); // current state of program progress Console.Clear(); Console.Write("Saving the HTML file..."); Thread.Sleep(700); // download the attachments from tfs item if (confirm) { // current state of program progress Console.Clear(); Console.Write("Download Attachments..."); // if folder is not exists, create it if (!Directory.Exists(pathToAttach)) { Directory.CreateDirectory(pathToAttach); } // Get a WebClient object to do the attachment download WebClient webClient = new WebClient() { UseDefaultCredentials = true }; // catch the error with download the attacments try { // Loop through each attachment in the work item. foreach (Attachment attachment in workItem.Attachments) { // Construct a filename for the attachment string filename = string.Format("{0}\\{1}", pathToAttach, attachment.Name); // Download the attachment. webClient.DownloadFile(attachment.Uri, filename); } } catch (Exception ex) { exExit(ex); } } // current state of program progress Console.Clear(); Console.Write("Opening the HTML file..."); Thread.Sleep(700); // open the created html file, will be open by default app for html files System.Diagnostics.Process.Start(pathToHtml); // current state of program progress Console.Clear(); Console.Write("Finish..."); Thread.Sleep(700); }