예제 #1
0
        public virtual void SetUp()
        {
            var collectionUrl = Environment.GetEnvironmentVariable("WILINQ_TEST_TPCURL");

            if (string.IsNullOrWhiteSpace(collectionUrl))
            {
                collectionUrl = "http://localhost:8080/tfs/DefaultCollection";
            }

            TPC = new TfsTeamProjectCollection(new Uri(collectionUrl));

            TPC.Authenticate();

            var projectName = Environment.GetEnvironmentVariable("WILINQ_TEST_PROJECTNAME");

            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
            if (string.IsNullOrWhiteSpace(projectName))
            {
                Project = TPC.GetService<WorkItemStore>().Projects.Cast<Project>().First();
            }
            else
            {

                Project = TPC.GetService<WorkItemStore>().Projects.Cast<Project>().First(_ => _.Name == projectName);
            }
        }
예제 #2
0
        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 TfsTeamProjectCollection TfsConnect()
        {
            try
            {
                // Determine if local TFS or VSTS

                if ((!AccountURL.ToLower().Contains("https")) || AccountURL.ToLower().Contains("8080"))
                {
                    // Authenticate to on-premises TFS

                    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(AccountURL));
                    tpc.EnsureAuthenticated();
                    return(tpc);
                }
                else
                {
                    // Authenticate to VSTS

                    NetworkCredential    netCred   = new NetworkCredential(MicrosoftAccountAlias, MicrosoftAccountPassword);
                    BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
                    TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);
                    tfsCred.AllowInteractive = false;
                    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(AccountURL), tfsCred);
                    tpc.Authenticate();
                    return(tpc);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                throw;
            }
        }
        public void Run(TFSConfiguration tfsConfiguration = null)
        {
            Logger.Log.Info("Run TFS integration");

            if (tfsConfiguration == null)
            {
                Logger.Log.Info($"Application runs from this location: {System.Reflection.Assembly.GetExecutingAssembly().Location}");
                Logger.Log.Info("Read configuration");
                tfsConfiguration = ReadTFSConfiguration(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), CONFIG_FILE));
            }

            Logger.Log.Info($"Authenticate to server {tfsConfiguration.TfsUrl}");
            NetworkCredential credentials = CredentialUtil.GetCredential(
                tfsConfiguration.TfsUrl.AbsoluteUri.Substring(0, tfsConfiguration.TfsUrl.AbsoluteUri.Length - tfsConfiguration.TfsUrl.AbsolutePath.Length + 1));
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(tfsConfiguration.TfsUrl, credentials);

            tfs.Authenticate();


            Logger.Log.Info("Get build server!");
            IBuildServer buildServer = tfs.GetService <IBuildServer>();

            Logger.Log.Info($"Build server version: {buildServer.BuildServerVersion}!");

            Parallel.ForEach(tfsConfiguration.TFSSettings, (tfsIntegrationSettings) =>
            {
                Logger.Log.Info($"Get all build definitions from team project {tfsIntegrationSettings.TeamProject}.");
                IBuildDefinition[] buildDefinitions = buildServer.QueryBuildDefinitions(tfsIntegrationSettings.TeamProject, QueryOptions.Definitions);

                if (buildDefinitions == null || !buildDefinitions.Any())
                {
                    Logger.Log.Info("No build definitions found! Exiting!");
                    return;
                }

                Logger.Log.Info($"Found {buildDefinitions.Length} build definitions.");
                IBuildDefinition buildDefinition =
                    buildDefinitions.Where(build => build.Name == tfsIntegrationSettings.BuildDefinitionName)
                    .Select(b => b)
                    .FirstOrDefault();

                Logger.Log.Info($"Get build details from {buildDefinition.Name}.");
                IBuildDetail buildDetail = GetLatestBuildDetails(buildServer, buildDefinition,
                                                                 tfsIntegrationSettings.TeamProject);

                if (buildDetail != null)
                {
                    DownloadVantageInstaller(
                        Path.Combine(buildDetail.DropLocation, tfsIntegrationSettings.SourcePathFragment,
                                     tfsIntegrationSettings.SourceFile),
                        Path.Combine(tfsIntegrationSettings.CopyTo, tfsIntegrationSettings.BuildDefinitionName,
                                     buildDetail.BuildNumber, tfsIntegrationSettings.SourceFile));
                }

                Logger.Log.Info("Cleanup old builds");
                CleanUp(Path.Combine(tfsIntegrationSettings.CopyTo, tfsIntegrationSettings.BuildDefinitionName),
                        tfsIntegrationSettings.MaxBuildsToKeep);
                Logger.Log.Info("FINISHED");
            });
        }
예제 #5
0
        public bool TryConnectToTfs()
        {
            if (_isConnected)
            {
                return(true);
            }

            var accountUri = new Uri(_adoApiSettings.AdoUrl);

            _tfsCollection = new TfsTeamProjectCollection(
                accountUri,
                new VssBasicCredential("", _adoApiSettings.AdoToken.Value));

            Logger.Debug("Try connect to TFS {url}", accountUri);

            _tfsCollection.Authenticate();

            //we need to bypass rules if we want to load data in the past.
            _workItemStore = new WorkItemStore(_tfsCollection, WorkItemStoreFlags.BypassRules);
            TfsProject     = _workItemStore.Projects[_adoApiSettings.AdoProject];

            Logger.Debug("Loaded project {projectName} {url}", TfsProject.Name, TfsProject.Uri);

            return(_isConnected = true);
        }
예제 #6
0
        public void Initialize(BuildConfig config)
        {
            string username = string.IsNullOrWhiteSpace(config.Username) ? string.Empty : config.Username;

            if (username == string.Empty)
            {
                InitializeWebApi(config);
                return;
            }

            VssCredentials c    = null;
            var            swtc = new VssServiceIdentityCredential(username, config.Password);

            c = new VssCredentials(swtc);


            c.PromptType = CredentialPromptType.DoNotPrompt;

            tpc = new TfsTeamProjectCollection(new Uri(config.SourceUrl + "/" + config.Collection), c);

            tpc.Authenticate();



            this.Server = tpc.GetService <Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer>();
        }
예제 #7
0
        /// <summary>
        /// Get the parameters of the test case
        /// </summary>
        /// <param name="testCaseId">Test case id (work item id#) displayed into TFS</param>
        /// <returns>Returns the test case parameters in datatable format. If there are no parameters then it will return null</returns>
        public static DataTable GetTestCaseParameters(int testCaseId)
        {
            ITestManagementService TestMgrService;
            ITestCase TestCase = null;
            DataTable TestCaseParameters = null;

            NetworkCredential netCred = new NetworkCredential(
              Constants.TFS_USER_NAME,
              Constants.TFS_USER_PASSWORD);
            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(
                new Uri(Constants.TFS_URL),
                tfsCred);

            teamProjectCollection.Authenticate();

            TestMgrService = teamProjectCollection.GetService<ITestManagementService>();
            TestCase = TestMgrService.GetTeamProject(Constants.TFS_PROJECT_NAME).TestCases.Find(testCaseId);

            if (TestCase != null)
            {
                if (TestCase.Data.Tables.Count > 0)
                {
                    TestCaseParameters = TestCase.Data.Tables[0];
                }
            }

            return TestCaseParameters;
        }
예제 #8
0
        private void PopulateProjectNameComboBox()
        {
            string url = tfsAddressTextBox.Text;
            string username = tfsUsernameTextBox.Text;
            string password = tfsPasswordTextBox.Text;

            Uri tfsUri;
            if (!Uri.TryCreate(url, UriKind.Absolute, out tfsUri))
                return;

            var credentials = new System.Net.NetworkCredential();
            if (!string.IsNullOrEmpty(username))
            {
                credentials.UserName = username;
                credentials.Password = password;
            }

            var tfs = new TfsTeamProjectCollection(tfsUri, credentials);
            tfs.Authenticate();

            var workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));

            projectComboBox.Items.Clear();
            foreach (Project project in workItemStore.Projects)
                projectComboBox.Items.Add(project.Name);

            int existingProjectIndex = -1;
            if (!string.IsNullOrEmpty(options.ProjectName))
                existingProjectIndex = projectComboBox.Items.IndexOf(options.ProjectName);
            projectComboBox.SelectedIndex = existingProjectIndex > 0 ? existingProjectIndex : 0;
        }
예제 #9
0
        /// <inheritdoc/>
        public async Task ConfigureAsync(TfsServiceProviderConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if(string.IsNullOrEmpty(configuration.WorkItemType))
            {
                throw new ArgumentNullException(nameof(configuration.WorkItemType));
            }

            this.logger.Debug("Configure of TfsSoapServiceProvider started...");
            var networkCredential = new NetworkCredential(configuration.Username, configuration.Password);
            var tfsClientCredentials = new TfsClientCredentials(new BasicAuthCredential(networkCredential)) { AllowInteractive = false };
            var tfsProjectCollection = new TfsTeamProjectCollection(this.serviceUri, tfsClientCredentials);
            this.workItemType = configuration.WorkItemType;
            tfsProjectCollection.Authenticate();
            tfsProjectCollection.EnsureAuthenticated();
            this.logger.Debug("Authentication successful for {serviceUri}.", this.serviceUri.AbsoluteUri);

            await Task.Run(
                () =>
                    {
                        this.logger.Debug("Fetching workitem for id {parentWorkItemId}.", configuration.ParentWorkItemId);
                        this.workItemStore = new WorkItemStore(tfsProjectCollection);
                        this.parentWorkItem = this.workItemStore.GetWorkItem(configuration.ParentWorkItemId);
                        this.logger.Debug("Found parent work item '{title}'.", this.parentWorkItem.Title);
                    });
            this.logger.Verbose("Tfs service provider configuration complete.");
        }
예제 #10
0
        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);
            }
        }
예제 #11
0
        public Initializer(string sourceBranch, string destBranch)
        {
            Console.WriteLine($"Auto Merging tool start on {DateTime.Now:MM-dd-yyyy-HH-mm-ss}");
            Console.WriteLine($"Source branch: {sourceBranch}, Target Branch: {destBranch}");

            string password = GetPassword(settings.VsoSecretName).Result;

            ProjectCollection = new TfsTeamProjectCollection(
                new Uri(settings.VSTSUrl),
                new VssBasicCredential(settings.UserName, password));

            try
            {
                ProjectCollection.Authenticate();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Could not authenticate with {settings.VSTSUrl}");
                Console.WriteLine(ex);
            }

            var gitClient = ProjectCollection.GetClient <GitHttpClient>();

            MergeTool = new VstsMergeTool(gitClient, sourceBranch, destBranch);
        }
        private static void FindWorkspace(string path, string tfsServerUri)
        {
            if (String.IsNullOrEmpty(tfsServerUri))
            {
                return;
            }
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(tfsServerUri));

            tpc.Authenticate();

            if (tpc == null)
            {
                return;
            }

            var versionControlServer = tpc.GetService <VersionControlServer>();

            // Try to query all workspaces the user has on this machine
            Workspace[] workspaces = versionControlServer.QueryWorkspaces(null, null, Environment.MachineName);

            foreach (Workspace w in workspaces)
            {
                foreach (WorkingFolder f in w.Folders)
                {
                    if (path.StartsWith(f.LocalItem))
                    {
                        workspace = w;
                        return;
                    }
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Presents the TeamProjectPicker just as in Team Explorer to select the TFS Server and prompts for
        /// login information if needed.
        /// </summary>
        protected void ConnectToServer()
        {
            TeamProjectPicker tpp = new TeamProjectPicker();

            if (tpp.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;

                    TfsTeamProjectCollection tfs = tpp.SelectedTeamProjectCollection;
                    tfs.Authenticate();

                    eventService  = (IEventService)tfs.GetService(typeof(IEventService));
                    userName      = IdentityHelper.GetDomainUserName(tfs.AuthorizedIdentity);
                    tfsCollection = tfs;

                    LoadEventTypes();
                }
                catch (Exception ex)
                {
                    DisplayException(ex.Message);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }

            DisplayServerInfo();
        }
예제 #14
0
        public static ITestRun CreateTestRun(int testId)
        {
            NetworkCredential        cred = new NetworkCredential("UserName", "Password");
            TfsTeamProjectCollection tfs  = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("VSTSSiteBase"));

            tfs.Credentials = cred;
            tfs.Authenticate();
            tfs.EnsureAuthenticated();

            ITestManagementTeamProject project = tfs.GetService <ITestManagementService>().GetTeamProject("Schwans Company");

            // find the test case.
            ITestCase testCase = project.TestCases.Find(testId);
            string    title    = testCase.Title.ToString();

            // find test plan.
            int planId = Int32.Parse("testPlanId");
            //ConfigurationManager.AppSettings["TestPlanId"]);
            ITestPlan plan = project.TestPlans.Find(planId);

            // Create test configuration. You can reuse this instead of creating a new config everytime.
            ITestConfiguration config = CreateTestConfiguration(project, string.Format("My test config {0}", DateTime.Now));

            // Create test points.
            IList <ITestPoint> testPoints = CreateTestPoints(project, plan, new List <ITestCase>()
            {
                testCase
            }, new IdAndName[] { new IdAndName(config.Id, config.Name) });

            // Create test run using test points.
            ITestRun run = CreateRun(project, plan, testPoints, title);

            return(run);
        }
예제 #15
0
        private void MainForm_Activated(object sender, EventArgs e)
        {
            RefreshDurationText();

            _cboProjects.Items.Clear();
            //NetworkCredential credential = new NetworkCredential("guoshaoyue", "netboy", "hissoft.com");//初始化用户
            //TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(ConfigHelper.TeamFoundationServerURL), credential);
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(ConfigHelper.TeamFoundationServerURL), CredentialCache.DefaultCredentials);

            tpc.Authenticate();

            WorkItemStore workItemStore = tpc.GetService <WorkItemStore>();

            foreach (Project item in workItemStore.Projects)
            {
                _cboProjects.Items.Add(item.Name);
            }
            _cboProjects.SelectedIndex = 0;
            _dtpRestart.Value          = DateTime.Now;
            if (_currentVersion == null)
            {
                DefaultCustomer.Checked = true;
            }
            else
            {
                _currentVersion.Checked = true;
            }
        }
        public TfsTeamProjectCollection Authorize(IDictionary<string, string> authorizeInformation)
        {
            var tfsCredentials = new TfsClientCredentials();
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(this.tfsUri));

            tfs.Authenticate();
            return tfs;
        }
예제 #17
0
        public TfsTeamProjectCollection GenerateTfsConnection()
        {
            var tfs= new TfsTeamProjectCollection(GetTfsUri(), GetNetworkCredential());
            tfs.Authenticate();
            tfs.Connect(new ConnectOptions());

            return tfs;
        }
예제 #18
0
 public override Task OpenAsync(CancellationToken cancellationToken)
 {
     return(Task.Factory.StartNew(() =>
     {
         TfsTeamProjectCollection.Authenticate();
         ConnectionState = ConnectionState.Open;
     }));
 }
예제 #19
0
        private bool SaveWorkItem(string workItemIds, string projectName)
        {
            WorkItemStore            workItemStore;
            WorkItemCollection       queryResults;
            WorkItem                 workItem;
            NetworkCredential        credential = new NetworkCredential("guoshaoyue", "netboy", "hissoft.com");//初始化用户
            TfsTeamProjectCollection tpc        = new TfsTeamProjectCollection(new Uri("http://svrdevelop:8080/tfs/medicalhealthsy"), credential);

            tpc.Authenticate();

            // [System.Title], [System.WorkItemType], [System.State], [System.ChangedDate], [System.Id]
            string  base_sql = string.Format("Select * From WorkItems Where [System.TeamProject] = '{0}' ", projectName);
            string  sql;
            string  query = string.Format("select e.FullName, b.* from tBug b, tbEmployee e where b.CodeEmployeeID = e.EmployeeID and b.BugId in ( {0} )", workItemIds);
            DataSet ds    = SqlDbHelper.Query(query);
            string  rets  = string.Empty;

            foreach (DataRowView item in ds.Tables[0].DefaultView)
            {
                Debug.Print(item["BugID"].ToString());
                sql           = string.Format("{0} and [System.Title] = '{1}'", base_sql, item["BugID"].ToString());
                workItemStore = tpc.GetService <WorkItemStore>();
                queryResults  = workItemStore.Query(sql);
                int cnt = queryResults.Count;
                if (cnt > 0)
                {
                    workItem = queryResults[0];
                    if (!workItem.IsOpen)
                    {
                        workItem.Open();
                    }
                }
                else
                {
                    Project project = workItemStore.Projects[projectName];
                    workItem = new WorkItem(int.Parse(item["CustomerCaseID"].ToString()) == -1 ? project.WorkItemTypes["Bug"] : project.WorkItemTypes["任务"]);
                    workItem.Fields["团队项目"].Value = projectName;
                    workItem.Fields["标题"].Value   = item["BugID"].ToString();
                }
                if (int.Parse(item["CustomerCaseID"].ToString()) == -1)
                {
                    workItem.Fields["重现步骤"].Value = item["CaseDesc"].ToString();
                }
                else
                {
                    workItem.Fields["说明"].Value = item["CaseDesc"].ToString();
                }
                workItem.Fields["指派给"].Value = item["FullName"].ToString();
                ArrayList ar = workItem.Validate();
                workItem.Save();

                rets = string.IsNullOrEmpty(rets) ? workItem.Fields["ID"].Value.ToString() : string.Format("{0}, {1}", rets, workItem.Fields["ID"].Value);
            }
            _txtTFSWorkItemIDs.Text = rets;

            return(true);
        }
예제 #20
0
        private static WorkItemStore GetWorkItemStore(Uri tpcAddress)
        {
            _Tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tpcAddress);
            _Tpc.Authenticate(); // windows authentication

            var result = new WorkItemStore(_Tpc);

            return(result);
        }
예제 #21
0
        public TfsTeamProjectCollection GenerateTfsConnection()
        {
            var tfs = new TfsTeamProjectCollection(GetTfsUri(), GetNetworkCredential());

            tfs.Authenticate();
            tfs.Connect(new ConnectOptions());

            return(tfs);
        }
예제 #22
0
        /// <summary>
        /// Perform the adapter-specific initialization
        /// </summary>
        public virtual void InitializeClient(MigrationSource migrationSource)
        {
            TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(migrationSource.ServerUrl));

            tfs.Authenticate();

            m_workItemStore = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));

            m_projectName = migrationSource.SourceIdentifier;
        }
예제 #23
0
        private static TfsTeamProjectCollection EstablishSoapConnection(Settings settings)
        {
            NetworkCredential  netCred   = new NetworkCredential(string.Empty, settings.Pat);
            VssBasicCredential basicCred = new VssBasicCredential(netCred);
            VssCredentials     tfsCred   = new VssCredentials(basicCred);
            var collection = new TfsTeamProjectCollection(new Uri(settings.Account), tfsCred);

            collection.Authenticate();
            return(collection);
        }
예제 #24
0
 public TfsTeamProjectCollection Connection()
 {
     string tfsUrl = _settings.TfsUrl;
     ICredentials credentials = (_settings.TfsUseDomainCredentials)
         ? System.Net.CredentialCache.DefaultCredentials
         : new NetworkCredential(_settings.TfsUsername, _settings.TfsPassword, _settings.TfsDomain);
     var server = new TfsTeamProjectCollection(new System.Uri(tfsUrl), credentials);
     server.Authenticate();
     return server;
 }
예제 #25
0
        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();
        }
예제 #26
0
        public TfsTeamProjectCollection GetCollection()
        {
            //var credentials = new System.Net.NetworkCredential("tfsbuild2010", "7f3.bu1ld", "janison");
            const string tfsUrl      = "https://tfscls.janison.com.au:8081/tfs/clscollection";
            var          credentials = System.Net.CredentialCache.DefaultCredentials;

            Collection = new TfsTeamProjectCollection(new Uri(tfsUrl), credentials);
            Collection.Authenticate();
            return(Collection);
        }
예제 #27
0
        public TfsTeamProjectCollection Connection()
        {
            string       tfsUrl      = _settings.TfsUrl;
            ICredentials credentials = (_settings.TfsUseDomainCredentials)
                ? System.Net.CredentialCache.DefaultCredentials
                : new NetworkCredential(_settings.TfsUsername, _settings.TfsPassword, _settings.TfsDomain);
            var server = new TfsTeamProjectCollection(new System.Uri(tfsUrl), credentials);

            server.Authenticate();
            return(server);
        }
예제 #28
0
        public AuthTfsTeamProjectCollection(string url)
        {
            if (Tfs == null || TfsUrl != url)
            {
                TfsUrl = url;
                Tfs    = new TfsTeamProjectCollection(new Uri(TfsUrl), new UICredentialsProvider());
                // Tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(Tfs
            }

            Tfs.Authenticate();
        }
예제 #29
0
        public void Initialize(BuildConfig config)
        {
            NetworkCredential credentials = new NetworkCredential(config.Username, config.Password);
            BasicAuthCredential basicCredentials = new BasicAuthCredential(credentials);
            TfsClientCredentials cred = new TfsClientCredentials(basicCredentials);
            cred.AllowInteractive = false;
            tpc = new TfsTeamProjectCollection(new Uri(config.SourceUrl + "/" + config.Collection),cred);

            tpc.Authenticate();

            this.Server = tpc.GetService<Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer>();
        }
예제 #30
0
        public TfsTeamProjectCollection GetCollection()
        {
            Collection = new TfsTeamProjectCollection(new Uri(_serverUrl));
            Collection.EnsureAuthenticated();

            if (!Collection.HasAuthenticated)
            {
                Collection.Authenticate();
            }

            return(Collection);
        }
예제 #31
0
        public void TfsCheckIn()
        {
            var sourceLocation = "$/TestProject/ScriptsTest";
            try
            {
                //There is a method above to connect TFS.   
                InitializeTfsConfiguration();

                var user = versionControl.AuthorizedUser;

                workspace = versionControl.GetWorkspace(comboBoxWorkspaces.Text, GetWorkSpacesOwnerName());
                directory = workspace.GetLocalItemForServerItem(sourceLocation);

                System.Windows.MessageBox.Show(directory);

                filePathToCheckIn = directory + "\\" + txtPbiId.Text + ".sql";
                System.Windows.MessageBox.Show(filePathToCheckIn);

                teamProjectCollection.Authenticate();

                /* workspace.Map("$/TestProject/ScriptsTest", directory);

                 workspace.Get();*/

                FileIOHelper.fileWriter(filePathToCheckIn, txtScript);

                workItem = WIStore.GetWorkItem(Convert.ToInt32(txtPbiId.Text));
                var WIChecInInfo = new[]
                {
                    new WorkItemCheckinInfo(workItem, WorkItemCheckinAction.Associate)
                };

                var items = versionControl.GetItems(directory, VersionSpec.Latest, RecursionType.Full);

                //The file which want to be checked will pretend to be new file which has same path string array below.
                String[] newFileForTfs = new string[1] { sourceLocation + Path.DirectorySeparatorChar + txtPbiId.Text + ".sql" };
                //Then getting  latest version of this file will show all changes on TFS part.
                workspace.Get(newFileForTfs, VersionSpec.Latest, RecursionType.Full, GetOptions.Overwrite);
                //After that, pending changes can be implemented.
                DoPendingChanges();

                Workstation.Current.EnsureUpdateWorkspaceInfoCache(versionControl, GetWorkSpacesOwnerName());
                PendingChange[] pendingChanges = workspace.GetPendingChanges(filePathToCheckIn, RecursionType.Full);

                workspace.CheckIn(pendingChanges, txtDescription.Text, null, WIChecInInfo, null);

                MessageBox.InformationMessage("    Checked In Successfully    ");
            }
            catch (Exception ex)
            {
                MessageBox.ErrorMessage(ex.Message);
            }
        }//End of TFS check in code.
예제 #32
0
        /// <summary>
        ///		Conecta a un servidor
        /// </summary>
        public void Connect()
        {
            WindowsCredential    objWindowsCredentials = new WindowsCredential(new NetworkCredential(User.Login, User.Pasword));
            TfsClientCredentials objCredentials        = new TfsClientCredentials(objWindowsCredentials);

            // Cierra la conexión
            Close();
            // Crea una conexión
            tfsTeamProject = new TfsTeamProjectCollection(Server.FullUrl, objCredentials);
            // Autentifica
            tfsTeamProject.Authenticate();
        }
예제 #33
0
        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
        }
예제 #34
0
        public StandardFixture()
        {
            var server = new TfsTeamProjectCollection(new Uri(TFS_SERVER));

            server.Authenticate();

            if (!server.HasAuthenticated)
            {
                throw new InvalidOperationException("Not authenticated");
            }

            WorkItemStore = server.GetService <WorkItemStore>();
        }
예제 #35
0
        /// <summary>
        /// Track a changeset merged into a possible list of branches.
        /// </summary>
        /// <param name="changesetId"></param>
        /// <param name="projectPath"></param>
        /// <param name="branches"></param>
        /// <returns></returns>
        /// <example>
        /// <code>
        /// var mergeBranch = TrackChangesetIn(id, "$/project/dev", new List { "B1", "B2" });
        /// if (mergeBranch.Any())
        /// {
        ///     var targetItems = mergeBranch.Select(mb => mb.TargetItem.Item);
        /// }
        /// </code>
        /// </example>
        public ExtendedMerge[] TrackChangesetIn(int changesetId, string projectPath, IEnumerable <string> branches)
        {
            if (_projectCollection.HasAuthenticated == false)
            {
                _projectCollection.Authenticate();
            }

            var merges = _versionControlServer.TrackMerges(new int[] { changesetId },
                                                           new ItemIdentifier(projectPath),
                                                           branches.Select(b => new ItemIdentifier(b)).ToArray(), null);

            return(merges);
        }
예제 #36
0
        static void Main(string[] args)
        {
            var options = new Options();
            if (!CommandLine.Parser.Default.ParseArguments(args, options))

            {
                Console.WriteLine(options.GetUsage());

                return;
            }

            // Connect to the desired Team Foundation Server
            TfsTeamProjectCollection tfsServer = new TfsTeamProjectCollection(new Uri(options.ServerNameUrl));

            // Authenticate with the Team Foundation Server
            tfsServer.Authenticate();

            // Get a reference to a Work Item Store
            var workItemStore = new WorkItemStore(tfsServer);

            var project = GetProjectByName(workItemStore, options.ProjectName);

            if (project == null)
            {
                Console.WriteLine($"Could not find project '{options.ProjectName}'");
                return;
            }

            var query = GetWorkItemQueryByName(workItemStore, project, options.QueryPath);

            if (query == null)
            {
                Console.WriteLine($"Could not find query '{options.QueryPath}' in project '{options.ProjectName}'");
                return;
            }

            var queryText = query.QueryText.Replace("@project", $"'{project.Name}'");

            Console.WriteLine($"Executing query '{options.QueryPath}' with text '{queryText}'");

            var count = workItemStore.QueryCount(queryText);

            Console.WriteLine($"Exporting {count} work items");

            var workItems = workItemStore.Query(queryText);

            foreach (WorkItem workItem in workItems)
            {
                StoreAttachments(workItem, options.OutputPath);
            }
        }
예제 #37
0
        /// <summary>
        /// Prevents a default instance of the <see cref="TfsProjects"/> class from being created.
        /// This might change if the project name can be optional.
        /// </summary>
        public TfsProjects(string tfsUri, string username, string password, string projectName = null)
        {
            NetworkCredential netCred = new NetworkCredential(username, password);

            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(tfsUri), tfsCred);
            ProjectCollection.Authenticate();

            Store = new WorkItemStore(ProjectCollection);
            ProjectName = projectName;
        }
예제 #38
0
        private bool ConnectToTfs(String accountUri, String accessToken)
        {
            //login for VSTS
            VssCredentials creds = new VssBasicCredential(
                String.Empty,
                accessToken);

            creds.Storage = new VssClientCredentialStorage();

            // Connect to VSTS
            _tfsCollection = new TfsTeamProjectCollection(new Uri(accountUri), creds);
            _tfsCollection.Authenticate();
            return(true);
        }
        public TfsTeamProjectCollection Authorize(IDictionary<string, string> authorizeInformation)
        {
            ////TeamProjectPicker picker = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, true);
            ////picker.ShowDialog();
            ////ProjectInfo[] projects = picker.SelectedProjects[0].;

            NetworkCredential cred = new NetworkCredential(authorizeInformation["username"], authorizeInformation["password"]);

            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(this.tfsUri), cred);

            tfs.Authenticate();

            return tfs;
        }
예제 #40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TfsProjects"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="projectName">Name of the project.</param>
        public TfsProjects(ITfsContext context)
        {
            NetworkCredential netCred = new NetworkCredential(context.Username, context.Password);

            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(context.Uri), tfsCred);
            ProjectCollection.Authenticate();

            Store = new WorkItemStore(ProjectCollection);
            ProjectName = context.ProjectName;
        }
예제 #41
0
        /// <summary>
        /// Prevents a default instance of the <see cref="TfsProjects"/> class from being created.
        /// This might change if the project name can be optional.
        /// </summary>
        public TfsProjects(string tfsUri, string username, string password, string projectName = null)
        {
            NetworkCredential netCred = new NetworkCredential(username, password);

            BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(tfsUri), tfsCred);
            ProjectCollection.Authenticate();

            Store       = new WorkItemStore(ProjectCollection);
            ProjectName = projectName;
        }
예제 #42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TfsProjects"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="projectName">Name of the project.</param>
        public TfsProjects(ITfsContext context)
        {
            NetworkCredential netCred = new NetworkCredential(context.Username, context.Password);

            BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(context.Uri), tfsCred);
            ProjectCollection.Authenticate();

            Store       = new WorkItemStore(ProjectCollection);
            ProjectName = context.ProjectName;
        }
        public TfsTeamProjectCollection Authorize(IDictionary<string, string> authorizeInformation)
        {
            NetworkCredential netCred = new NetworkCredential(
                "*****@*****.**",
                "yourbasicauthpassword");
            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
                new Uri("https://YourAccountName.visualstudio.com/DefaultCollection"),
                tfsCred);

            tpc.Authenticate();
            return tpc;
        }
예제 #44
0
        public void Process(string[] projectPaths, DateTime from, Stream outStream)
        {
            var credential = new System.Net.NetworkCredential(_username, _password, _domain);
            var server = new TfsTeamProjectCollection(new Uri(_tfsUrl), credential);
            server.Authenticate();

            var history = new List<Changeset>();
            foreach (var projectPath in projectPaths)
            {
                var projectPathTemp = projectPath.Trim();

                var source = server.GetService<VersionControlServer>();
                Console.WriteLine("Searching history for project {0}", projectPathTemp);
                var projectHistory = source.QueryHistory(projectPathTemp, VersionSpec.Latest, 0, RecursionType.Full,
                                                          null, new DateVersionSpec(from), null, int.MaxValue,
                                                          true,
                                                          false, false, false).OfType<Changeset>().Reverse().ToList();
                projectHistory = projectHistory.Where(item => item.CreationDate > from).ToList();
                history.AddRange(projectHistory);
            }

            var orderedHistory = history.OrderBy(m => m.CreationDate);

            using (var writer = new StreamWriter(outStream))
            {
                foreach (var item in orderedHistory) // history.ForEach(item =>
                {
                    Console.WriteLine("Found changeset id = {0}. Committed: {1}", item.ChangesetId, item.CreationDate);

                    String committer = item.Committer;
                    if (_usernameSubstitution.ContainsKey(committer.ToLower()))
                        committer = _usernameSubstitution[committer.ToLower()];

                    foreach (Change change in item.Changes)
                    {
                        ChangeType changeType = change.ChangeType;
                        if (!AllowedTypes.Any(type => (type.Key & changeType) != 0))
                            continue;

                        KeyValuePair<ChangeType, string> code = AllowedTypes.FirstOrDefault(type => (type.Key & changeType) != 0);
                        writer.WriteLine(LogFormat, DateTimeToUnix(item.CreationDate), committer, code.Value,
                                         change.Item.ServerItem);
                    }
                }
            }
            Console.WriteLine("Processing finished");
        }
예제 #45
0
파일: Utils.cs 프로젝트: kunzimariano/V1TFS
        public static TfsTeamProjectCollection ConnectToTFS()
        {
            var config = new ConfigurationProxy().Retrieve();
            var user = config.TfsUserName;
            var domain = string.Empty;
            var pos = config.TfsUserName.IndexOf('\\');

            if (pos >= 0)
            {
                domain = config.TfsUserName.Substring(0, pos);
                user = user.Substring(pos + 1);
            }

            var creds = new NetworkCredential(user, config.TfsPassword, domain);
            var tfsServer = new TfsTeamProjectCollection(new Uri(config.TfsUrl), creds);
            tfsServer.Authenticate();
            return tfsServer;
        }
예제 #46
0
        public static NetworkCredential Authenticate()
        {
            if (credentials == null)
            {
            Start:
                NetworkCredential credential;

                if (!TryReadCredentials(out credential))
                {
                    var login = AskLogin();
                    var password = AskPassword();
                    credential = new NetworkCredential(login, password);
                }

                try
                {
                    Console.WriteLine("-----Authentication------");
                    Console.WriteLine("Started...");

                    var projectCollection = new TfsTeamProjectCollection(Config.TfsCollectionUrl, credential);
                    projectCollection.Authenticate();

                    credentials = credential;

                    WriteCredentials(credential.UserName, credential.Password);

                    Console.WriteLine("Successfully completed.");
                    Console.WriteLine("-------------------------");
                    Console.WriteLine("");
                }
                catch (Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException ex)
                {
                    ClearCredentials();

                    Console.Clear();
                    Console.WriteLine("Couldn't connect to TFS. Try again");
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("");
                    goto Start;
                }
            }

            return credentials;
        }
예제 #47
0
파일: Utils.cs 프로젝트: jcolebrand/V1TFS
        public static TfsTeamProjectCollection ConnectToTFS()
        {
            var url = RegistryProcessor.GetString(RegistryProcessor.TfsUrlParameter, string.Empty);
            var user = RegistryProcessor.GetString(RegistryProcessor.TfsUsernameParameter, string.Empty);
            var password = RegistryProcessor.GetPassword(RegistryProcessor.TfsPasswordParameter, string.Empty);

            var domain = string.Empty;
            var pos = user.IndexOf('\\');

            if (pos >= 0)
            {
                domain = user.Substring(0, pos);
                user = user.Substring(pos + 1);
            }

            var creds = new NetworkCredential(user, password, domain);
            var tfsServer = new TfsTeamProjectCollection(new Uri(url), creds);
            tfsServer.Authenticate();
            return tfsServer;
        }
예제 #48
0
        public static void MyClassInitialize(TestContext testContext)
        {
            NetworkCredential networkCredential = new NetworkCredential(@"*****@*****.**","zippyd00da");
            BasicAuthToken basicAuthToken = new BasicAuthToken(networkCredential);
            BasicAuthCredential basicAuthCredential = new BasicAuthCredential(basicAuthToken);
            TfsClientCredentials tfsClientCredentials = new TfsClientCredentials(basicAuthCredential);
            tfsClientCredentials.AllowInteractive = false;

            server2 = new TfsTeamProjectCollection(new Uri("https://rdavis.visualstudio.com/DefaultCollection"), tfsClientCredentials);

            server2.Connect(Microsoft.TeamFoundation.Framework.Common.ConnectOptions.None);
            server2.EnsureAuthenticated();

            server2.Authenticate();

            if (!server2.HasAuthenticated)
                throw new InvalidOperationException("Not authenticated");

            store = new WorkItemStore(server2);
        }
예제 #49
0
        internal UserContext()
        {
            if (string.IsNullOrEmpty(SpruceSettings.TfsServer))
                throw new ArgumentNullException("The TfsServer settings is empty, please set it in the web.config (full URL, including the port)");

            if (string.IsNullOrEmpty(SpruceSettings.DefaultProjectName))
                throw new ArgumentNullException("The DefaultProjectName settings is empty, please set it in the web.config");

            // Connect to TFS
            _users = new List<string>();
            TfsCollection = new TfsTeamProjectCollection(new Uri(SpruceSettings.TfsServer));
            TfsCollection.Authenticate();
            WorkItemStore = new WorkItemStore(TfsCollection);
            VersionControlServer = TfsCollection.GetService<VersionControlServer>();
            RegisteredLinkTypes = WorkItemStore.RegisteredLinkTypes;

            // Get the current username, and load their settings
            Name = TfsCollection.AuthorizedIdentity.DisplayName;
            Id = TfsCollection.AuthorizedIdentity.TeamFoundationId;

            // Load the user settings from the backing store (ravendb)
            Settings = UserSettings.Load(Id);
            Settings.Name = Name;

            // Set the current project, and the view settings
            if (string.IsNullOrEmpty(Settings.ProjectName) || !WorkItemStore.Projects.Contains(Settings.ProjectName))
            {
                ChangeCurrentProject(SpruceSettings.DefaultProjectName);
            }
            else
            {
                _projectName = Settings.ProjectName;
                CurrentProject = new ProjectDetails(WorkItemStore.Projects[_projectName]);
            }

            // Populate the list of project names and users - this is done per user rather
            // than per application, so new project names don't require an app restart.
            PopulateProjectNames();
            PopulateUsers();
        }
예제 #50
0
파일: Utils.cs 프로젝트: kunzimariano/V1TFS
        public static TfsTeamProjectCollection ConnectToTfs()
        {
            var config = new ConfigurationProvider();

            var url = config.TfsUrl;
            var user = config.TfsUserName;
            var password = config.TfsPassword;

            var domain = string.Empty;
            var pos = user.IndexOf('\\');

            if (pos >= 0)
            {
                domain = user.Substring(0, pos);
                user = user.Substring(pos + 1);
            }

            var creds = new NetworkCredential(user, password, domain);
            var tfsServer = new TfsTeamProjectCollection(url, creds);
            tfsServer.Authenticate();
            return tfsServer;
        }
 private TfsTeamProjectCollection CreateTeamProjectCollection()
 {
     TfsTeamProjectCollection server = new TfsTeamProjectCollection(new Uri(Settings.TeamFoundationServerPath));
     server.Authenticate();
     return server;
 }
예제 #52
0
        /// <summary>
        /// numero changeset per TP
        /// </summary>
        /// <param name="tfs">
        /// server TFS
        /// </param>
        /// <param name="tp">
        /// TP in oggetto
        /// </param>
        /// <returns>
        /// numero Changeset
        /// </returns>
        public static CSCount AllChangeset(TfsTeamProjectCollection tfs, string tp)
        {
            VersionControlServer versionControl;
            CsNoWI = new List<Change_Data>();

            // string TFSServerPath = @"http:// tfsfarm.tsf.local:8080/tfs/" + collection;
            // TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(TFSServerPath), Cred);
            tfs.Authenticate();
            versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

            // here you specify the exact time period you need to get the change set (from Date,to Date)
            VersionSpec fromDateVersion = new DateVersionSpec(DateTime.Now.AddMonths(-1));
            VersionSpec toDateVersion = new DateVersionSpec(DateTime.Now);

            // using versionControl API you can query histroy for changes set for (specific,all) User
            var data = versionControl.QueryHistory("$/" + tp, VersionSpec.Latest, 0, RecursionType.Full, null, fromDateVersion, toDateVersion, int.MaxValue, true, true);

            int i = 0;
            int old = 0;
            foreach (Microsoft.TeamFoundation.VersionControl.Client.Changeset pippo in data)
            {
                old++;
                if (pippo.WorkItems.Length == 0)
                {
                    CsNoWI.Add(new Change_Data(pippo.ChangesetId.ToString(), pippo.CommitterDisplayName, pippo.CreationDate.ToShortDateString(), pippo.Comment));
                    i++;
                }
            }

            CSCount csc = new CSCount();
            csc.All = old;
            csc.NonAssociato = i;
            return csc;
        }
        private List<KeyValuePair<string, Module>> CalculateBuildCoverageOrdered(string collectionUrl, string projectName, string buildName, string userName,
                                                   string password)
        {
            Uri collectionUri = new Uri(collectionUrl);
            var buildsCoverage = new Dictionary<string, Module>();

            using (var tfsTeamProjectCollection = new TfsTeamProjectCollection(collectionUri))
            {
                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    tfsTeamProjectCollection.ClientCredentials =
                        new TfsClientCredentials(new WindowsCredential(new NetworkCredential(userName, password)));
                    tfsTeamProjectCollection.Authenticate();
                }

                var buildService = tfsTeamProjectCollection.GetService<IBuildServer>();
                var commonStructureService = tfsTeamProjectCollection.GetService<ICommonStructureService4>();
                ProjectInfo projectInfo = commonStructureService.GetProjectFromName(projectName);

                var iterationDates = GetIterationDates(commonStructureService, projectInfo.Uri);

                foreach (var iterationDate in iterationDates)
                {
                    var builds = GetSprintBuilds(buildService, projectName, buildName, iterationDate.StartDate.Value, iterationDate.EndDate.Value);
                    if (builds.Builds.Any())
                        GetBuildCodeCoverage(tfsTeamProjectCollection, projectName, builds.Builds.Last(), buildsCoverage);
                }
            }

            var buildCoverageOrdered = buildsCoverage.OrderBy(b => b.Value.Builds.First().Name).ToList();
            return buildCoverageOrdered;
        }
        private void cmdExport_Click(object sender, EventArgs e)
        {
            Uri collectionUri = new Uri(txtCollectionUri.Text);
            string teamProject = txtTeamProject.Text;

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.CheckPathExists = true;
            dlg.Title = "Export Area/Iteration structure";
            dlg.DefaultExt = ".nodes";
            dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes";
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                string filename = dlg.FileName;

                var networkCredential = new NetworkCredential("username", "password");
                var basicAuthCredential = new BasicAuthCredential(networkCredential);
                var tfsCredential = new TfsClientCredentials(basicAuthCredential);

                using(var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential))
                //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri))
                using (WaitState waitState = new WaitState(this))
                {
                    tfs.Authenticate();
                    tfs.EnsureAuthenticated();

                    //  get the configuration server
                    var svr = tfs.ConfigurationServer;

                    //  get the configuration service
                    var svc = tfs.GetService<TeamSettingsConfigurationService>();

                    // get the common structure service
                    var css = tfs.GetService<ICommonStructureService4>();

                    //  get the spotlabs project
                    var prj = css.GetProjectFromName(txtTeamProject.Text);

                    //  get the configurations
                    var cfg = svc.GetTeamConfigurationsForUser(new[] { prj.Uri }).Single<TeamConfiguration>();

                    //  get the settings
                    var opt = cfg.TeamSettings;

                    //  get the iteration schedule
                    var schedule = css.GetIterationDates(prj.Uri);

                    Console.WriteLine(opt.ToString());

                    var store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
                    var proj = store.Projects[teamProject];

                    using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    using (StreamWriter writer = new StreamWriter(fs))
                    {
                        writer.WriteLine("NODES");
                        writer.WriteLine(String.Format("{0}, Version {1}", Application.ProductName, Application.ProductVersion));
                        writer.WriteLine("Copyright (C) 2010 " + Application.CompanyName);

                        if (chkAreaStructure.Checked)
                        {
                            WriteNodes(proj.AreaRootNodes, writer, "A");
                        }

                        if (chkIterationStructure.Checked)
                        {
                            WriteNodes(proj.IterationRootNodes, writer, "I");
                        }

                        writer.Close();
                    }
                }

                MessageBox.Show("Export successful.");
            }
        }
        /// <summary>
        /// Selects a project in a TFS Server
        /// </summary>
        /// <param name="collectionUrl">The collection's url</param>
        /// <param name="projectUri">The project Uri</param>
        /// <param name="userName">Username to connect to TFS</param>
        /// <param name="password">User's password</param>
        /// <returns>A list of builds</returns>
        public JsonResult SelectProject(string collectionUrl, string projectUri, string userName, string password)
        {
            Uri collectionUri = new Uri(collectionUrl);
            var buildListModel = new BuildListModel();

            using (var tfsTeamProjectCollection = new TfsTeamProjectCollection(collectionUri))
            {
                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                {
                    tfsTeamProjectCollection.ClientCredentials =
                        new TfsClientCredentials(new WindowsCredential(new NetworkCredential(userName, password)));
                    tfsTeamProjectCollection.Authenticate();
                }

                var buildService = tfsTeamProjectCollection.GetService<IBuildServer>();
                var builds = buildService.QueryBuildDefinitions(projectUri);
                buildListModel.Status = true;

                foreach (var build in builds)
                {
                    buildListModel.Builds.Add(new BuildModel(build.Name, build.Name));
                }
            }

            return Json(buildListModel, JsonRequestBehavior.AllowGet);
        }
예제 #56
0
        private WorkItemStore ConnectToTfs()
        {
            Uri tfsUri;
            if (!Uri.TryCreate(options.ServerName, UriKind.Absolute, out tfsUri))
                return null;

            var credentials = new System.Net.NetworkCredential();
            if (!string.IsNullOrEmpty(options.UserName))
            {
                credentials.UserName = options.UserName;
                credentials.Password = options.UserPassword;
            }

            _tfs = new TfsTeamProjectCollection(tfsUri, credentials);
            _tfs.Authenticate();

            return (WorkItemStore) _tfs.GetService(typeof (WorkItemStore));
        }
        /// <summary>
        /// Selects a collection in a TFS server
        /// </summary>
        /// <param name="collectionUrl">The collection's url</param>
        /// <param name="userName">Username to connect to TFS</param>
        /// <param name="password">User's password</param>
        /// <returns>A list of projects</returns>
        public JsonResult SelectCollection(string collectionUrl, string userName, string password)
        {
            Uri collectionUri = new Uri(collectionUrl);
            var teamProjects = new TeamProjectsModel();

            using (var tfsTeamProjectCollection = new TfsTeamProjectCollection(collectionUri))
            {
                try
                {
                    if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                    {
                        tfsTeamProjectCollection.ClientCredentials =
                            new TfsClientCredentials(new WindowsCredential(new NetworkCredential(userName, password)));
                        tfsTeamProjectCollection.Authenticate();
                    }

                    var commonStruct = tfsTeamProjectCollection.GetService<ICommonStructureService>();
                    var teamProjectInfos = commonStruct.ListAllProjects();

                    teamProjects.Status = true;
                    foreach (var teamProjectInfo in teamProjectInfos)
                    {
                        teamProjects.Projects.Add(new TeamProject(teamProjectInfo.Name, teamProjectInfo.Uri));
                    }
                }
                catch (TeamFoundationServerUnauthorizedException unauthorizedException)
                {
                    teamProjects.Status = false;
                }
            }

            return Json(teamProjects, JsonRequestBehavior.AllowGet);
        }
예제 #58
0
        private IBuildServer GetBuildServer()
        {
            var tfs = new TfsTeamProjectCollection(new Uri(tfsServerAddress), (ICredentials)credentials);
            tfs.Authenticate();

            IBuildServer buildServer = tfs.GetService<IBuildServer>();
            return buildServer;
        }
예제 #59
0
        /// <summary>
        /// da una collection l'elenco dei TP
        /// </summary>
        /// <param name="stringa">
        /// collection di ricerca
        /// </param>
        /// <returns>
        /// lista progetti
        /// </returns>
        public static List<TP> GetTP(String tfsName, string stringa)
        {
            List<TP> listTP = new List<TP>();
            using (var tfs = new TfsTeamProjectCollection(new Uri(tfsName + stringa), Cred))
            {
                tfs.Authenticate();
                var wiStore = tfs.GetService<WorkItemStore>();

                var projectCollection = wiStore.Projects;

                foreach (Project project in projectCollection)
                {
                    FindCI(listTP, tfs, project);
                }

                return listTP;
            }

            // return listTP;
        }
예제 #60
0
        /// <summary>
        /// numero utenti per il dato TP
        /// </summary>
        /// <param name="tp">
        /// progetto da controllare
        /// </param>
        /// <param name="collection">
        /// collection del progetto
        /// </param>
        /// <returns>
        /// numero utenti
        /// </returns>
        public static int Utenti(String tfsName, string tp, string collection)
        {
            int count = 0;
            using (var tfs = new TfsTeamProjectCollection(new Uri(tfsName + collection), Cred))
            {
                tfs.Authenticate();
                IGroupSecurityService gss = (IGroupSecurityService)tfs.GetService(typeof(IGroupSecurityService));
                string u = tfs.GetService<ICommonStructureService>().GetProjectFromName(tp).Uri;
                Identity[] id = gss.ListApplicationGroups(tfs.GetService<ICommonStructureService>().GetProjectFromName(tp).Uri);
                foreach (Identity identity in id)
                {
                    if (identity.AccountName != "Readers")
                    {
                        Identity sids = gss.ReadIdentity(SearchFactor.AccountName, "[" + tp + "]\\" + identity.AccountName, QueryMembership.Expanded);
                        count += sids.Members.Length;
                    }
                }

                return count;
            }
        }