예제 #1
0
        protected override void ProcessRecord()
        {
            using (var collection = new TfsTeamProjectCollection(CollectionUri))
            {
                var cssService = collection.GetService<ICommonStructureService4>();
                var projectInfo = cssService.GetProjectFromName(TeamProject);

                var teamService = collection.GetService<TfsTeamService>();
                var tfsTeam = teamService.ReadTeam(projectInfo.Uri, Team, null);
                if (tfsTeam == null)
                {
                    WriteError(new ErrorRecord(new ArgumentException(string.Format("Team '{0}' not found.", Team)), "", ErrorCategory.InvalidArgument, null));
                    return;
                }

                var identityService = collection.GetService<IIdentityManagementService>();
                var identity = identityService.ReadIdentity(IdentitySearchFactor.AccountName, Member, MembershipQuery.Direct, ReadIdentityOptions.None);
                if (identity == null)
                {
                    WriteError(new ErrorRecord(new ArgumentException(string.Format("Identity '{0}' not found.", Member)), "", ErrorCategory.InvalidArgument, null));
                    return;
                }

                identityService.AddMemberToApplicationGroup(tfsTeam.Identity.Descriptor, identity.Descriptor);
                WriteVerbose(string.Format("Identity '{0}' added to team '{1}'", Member, Team));
            }
        }
 public MyTfsProjectCollection(CatalogNode teamProjectCollectionNode, TfsConfigurationServer tfsConfigurationServer, NetworkCredential networkCredential)
 {
     try
     {
         Name = teamProjectCollectionNode.Resource.DisplayName;
         ServiceDefinition tpcServiceDefinition = teamProjectCollectionNode.Resource.ServiceReferences["Location"];
         var configLocationService = tfsConfigurationServer.GetService<ILocationService>();
         var tpcUri = new Uri(configLocationService.LocationForCurrentConnection(tpcServiceDefinition));
         _tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tpcUri, new MyCredentials(networkCredential));
         _commonStructureService = _tfsTeamProjectCollection.GetService<ICommonStructureService>();
         _buildServer = _tfsTeamProjectCollection.GetService<IBuildServer>();
         _tswaClientHyperlinkService = _tfsTeamProjectCollection.GetService<TswaClientHyperlinkService>();
         CurrentUserHasAccess = true;
     }
     catch (TeamFoundationServiceUnavailableException ex)
     {
         _log.Debug("Can't access " + Name + ". This could be because the project collection is currently offline.", ex);
         CurrentUserHasAccess = false;
     }
     catch (TeamFoundationServerUnauthorizedException ex)
     {
         _log.Debug("Unauthorized access to " + teamProjectCollectionNode, ex);
         CurrentUserHasAccess = false;
     }
 }
예제 #3
0
        static void Main(string[] args)
        {
            // Try to parse options from command line
            var options = new Options();
            if (Parser.Default.ParseArguments(args, options))
            {
                try
                {
                    _collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(options.TeamCollection));
                    _buildServer = _collection.GetService<IBuildServer>();
                    _commonStructureService = _collection.GetService<ICommonStructureService>();
                    _printer = new TabbedPrinter();

                    PrintDefinitions(options);
                }
                catch (Exception ex)
                {
                    Console.WriteLine();
                    Console.WriteLine("An error occured:");
                    Console.WriteLine(ex.Message);
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("Couldn't read options");
                Console.WriteLine();
            }
        }
예제 #4
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);
            }
        }
 public MainWindowViewModel()
 {
     server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
         RegisteredTfsConnections.GetProjectCollections().First().Uri);
     workItemStore = (WorkItemStore)server.GetService(typeof(WorkItemStore));
     versionControl = server.GetService<VersionControlServer>();
     buildServer = (IBuildServer)server.GetService(typeof(IBuildServer));
     historyLoader = new HistoryLoader(versionControl);
     loadHistoryCommand = new DelegateCommand(LoadHistory);
 }
예제 #6
0
        public override void Load()
        {
            var teamFoundationServerUrl = ConfigurationManager.AppSettings["TeamFoundationServerUrl"];
            var tfsUser = ConfigurationManager.AppSettings["TFS_User"];
            var tfsPassword = ConfigurationManager.AppSettings["TFS_Password"];
            var tfs = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(teamFoundationServerUrl), new NetworkCredential(tfsUser, tfsPassword));

            Bind<IBuildServer>().ToMethod(ctx => tfs.GetService<IBuildServer>());
            Bind<VersionControlServer>().ToMethod(ctx => tfs.GetService<VersionControlServer>());
            Bind<ITestManagementService>().ToMethod(ctx => tfs.GetService<ITestManagementService>());

            Bind<IBuildService>().To<Tfs2010BuildService>().InSingletonScope();
        }
예제 #7
0
        public IList<BuildState> GetLatestBuildStates()
        {
            using (TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(_configuration.TfsUrl), new NetworkCredential(_configuration.TfsUserName, _configuration.TfsPassword)))
            {
                IBuildServer buildServer = tfs.GetService<IBuildServer>();
                ITestManagementService testServer = tfs.GetService<ITestManagementService>();
                var defs = buildServer.QueryBuildDefinitions(_configuration.TfsTeamProjectName);
                return defs
                    .Select(def => GetLatestBuildDetails(buildServer, def))
                    .Where(build => build != null)
                    .Select(build => new BuildState(build.BuildDefinition.Name, build.Status, build.FinishTime, build.Uri.AbsoluteUri, build.RequestedFor,GetTestResults(testServer, build.Uri)))
                    .ToList();

            }
        }
예제 #8
0
        private static void Main(string[] args)
        {
            var tfsUrl = "";
            var pbiNumber = 0;
            var optionSet = new OptionSet
            {
                {"pbi=", "The {PBI} Number", (int pbi) => pbiNumber = pbi},
                {"tfs=", "The {TFSURL} for the TFS Collection to use", url => { tfsUrl = url; }}
            };
            optionSet.Parse(args);

            var tpc = new TfsTeamProjectCollection(new Uri(tfsUrl));
            var workItemStore = tpc.GetService<WorkItemStore>();
            var vcServer = tpc.GetService<VersionControlServer>();

            var changesets = GetChangesets(workItemStore, vcServer, pbiNumber);

            Output("{0} changesets", changesets.Count);
            foreach (var changeset in changesets.OrderBy(n => n.Key).Select(n => n.Value))
            {
                Output("{0} - {1}", changeset.ChangesetId, changeset.Comment);
            }

            Output("");

            var files =
                changesets.Values.SelectMany(changeset => changeset.Changes,
                    (changeset, change) => new {change, changeset})
                    .Select(a => new
                    {
                        ChangeType = a.change.ChangeType.HasFlag(ChangeType.Add) ? ChangeType.Add : a.change.ChangeType,
                        FileName = a.change.Item.ServerItem.Substring(@"$/PwC-CMS/Development/Source/PwC CMS/".Length),
                        Changeset = a.changeset
                    })
                    .GroupBy(a => new {a.ChangeType, a.FileName}, a => a.Changeset)
                    .OrderBy(g => g.Key.ChangeType).ThenBy(g => g.Key.FileName)
                    .ToList();

            Output("{0} files", files.Count);
            foreach (var file in files)
            {
                Output("{0} - {1}", file.Key.ChangeType, file.Key.FileName);
                foreach (var changeset in file)
                {
                    Output("\t{0} - {1}", changeset.ChangesetId, changeset.Comment);
                }
            }
        }
예제 #9
0
        public WorkItem GetNewWorkItem(TfsTeamProjectCollection conn, string projectName, string WIType, string areaPath, string iterationPath, string title, string description)
        {
            try
            {
                WorkItemStore workItemStore = conn.GetService<WorkItemStore>();
                Project prj = workItemStore.Projects[projectName];
                WorkItemType workItemType = prj.WorkItemTypes[WIType];


                var WIToAdd = new WorkItem(workItemType)
                {
                    Title = title,
                    Description = description,
                    IterationPath = iterationPath,
                    AreaPath = areaPath,
                };

                return WIToAdd;
            }
            catch (Exception ex)
            {
                Logger.Fatal(new LogInfo(MethodBase.GetCurrentMethod(), "ERR", string.Format("Si è verificato un errore durante la creazione del work Item. Dettagli: {0}", ex.Message)));
                throw ex;
            }
        }
예제 #10
0
        private static BuildStatus GetBuildStatus(TfsTeamProjectCollection collection)
        {
            var buildServer = collection.GetService<IBuildServer>();

            var builds = buildServer.QueryBuilds(teamProjectName);
            return builds.OrderByDescending(b => b.StartTime).First().Status;
        }
예제 #11
0
        public Validation()
        {
            _tfsServer = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ConfigurationManager.AppSettings["TfsServer"]));
            _vsoServer = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ConfigurationManager.AppSettings["VsoServer"]));
            _vsoStore = _vsoServer.GetService<WorkItemStore>();
            _tfsStore = _tfsServer.GetService<WorkItemStore>();

            var actionValue = ConfigurationManager.AppSettings["Action"];
            if (actionValue.Equals("validate", StringComparison.OrdinalIgnoreCase))
            {
                _action = Action.Validate;
            }
            else
            {
                _action = Action.Compare;
            }

            var runDateTime = DateTime.Now.ToString("yyyy-MM-dd-HHmmss");

            var dataFilePath = ConfigurationManager.AppSettings["DataFilePath"];
            var dataDir = string.IsNullOrWhiteSpace(dataFilePath) ? Directory.GetCurrentDirectory() : dataFilePath;
            var dirName = string.Format("{0}\\Log-{1}",dataDir,runDateTime);

            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }

            _errorLog = new Logging(string.Format("{0}\\Error.txt", dirName));
            _statusLog = new Logging(string.Format("{0}\\Status.txt", dirName));
            _fullLog = new Logging(string.Format("{0}\\FullLog.txt", dirName));

            _taskList = new List<Task>();

            if (!_action.Equals(Action.Compare))
            {
                return;
            }

            _valFieldErrorLog = new Logging(string.Format("{0}\\FieldError.txt", dirName));
            _valTagErrorLog = new Logging(string.Format("{0}\\TagError.txt", dirName));
            _valPostMigrationUpdateLog = new Logging(string.Format("{0}\\PostMigrationUpdate.txt", dirName));

            _imageLog = new Logging(string.Format("{0}\\ItemsWithImage.txt", dirName));

            _commonFields = new List<string>();
            _itemTypesToValidate = new List<string>();

            var fields = ConfigurationManager.AppSettings["CommonFields"].Split(',');
            foreach (var field in fields)
            {
                _commonFields.Add(field);
            }

            var types = ConfigurationManager.AppSettings["WorkItemTypes"].Split(',');
            foreach (var type in types)
            {
                _itemTypesToValidate.Add(type);
            }
        }
        public static void Main(string[] args)
        {
            try
            {
                var options = new Options();

                if (CommandLine.Parser.Default.ParseArgumentsStrict(args, options))
                {
                    TfsTeamProjectCollection collection = new TfsTeamProjectCollection(new Uri(options.TeamProjectCollectionUrl));

                    //Call Build
                    IBuildServer buildServer = collection.GetService<IBuildServer>();

                    IBuildDefinition definition = buildServer.GetBuildDefinition(options.TeamProjectName,
                                                                                 options.BuildDefinition);

                    IBuildRequest request = definition.CreateBuildRequest();
                    request.ProcessParameters = UpdateVersion(request.ProcessParameters, options);
                    request.DropLocation = options.DropLocation;
                    buildServer.QueueBuild(request);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in calling TFS Build: " + ex.Message);
            }
        }
예제 #13
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;
        }
        private static string GetDropDownloadPath(TfsTeamProjectCollection collection, IBuildDetail buildDetail)
        {
            string droplocation = buildDetail.DropLocation;
            if (string.IsNullOrEmpty(droplocation))
            {
                throw new FailingBuildException(string.Format(CultureInfo.CurrentCulture, "No drop is available for {0}.", buildDetail.BuildNumber));
            }

            ILocationService locationService = collection.GetService<ILocationService>();
            string containersBaseAddress = locationService.LocationForAccessMapping(ServiceInterfaces.FileContainersResource, FrameworkServiceIdentifiers.FileContainers, locationService.DefaultAccessMapping);
            droplocation = BuildContainerPath.Combine(droplocation, string.Format(CultureInfo.InvariantCulture, "{0}.zip", buildDetail.BuildNumber));

            try
            {
                long containerId;
                string itemPath;
                BuildContainerPath.GetContainerIdAndPath(droplocation, out containerId, out itemPath);

                string downloadPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", containersBaseAddress, containerId, itemPath.TrimStart('/'));
                return downloadPath;
            }
            catch (InvalidPathException)
            {
                throw new FailingBuildException(string.Format(CultureInfo.CurrentCulture, "No drop is available for {0}.", buildDetail.BuildNumber));
            }
        }
        public void SetConfiguration(ConfigurationBase newConfiguration)
        {
            if (timer != null)
            {
                timer.Change(Timeout.Infinite, Timeout.Infinite);
            }

            configuration = newConfiguration as TeamFoundationConfiguration;
            if (configuration == null)
            {
                throw new ApplicationException("Configuration can not be null.");
            }

            var credentialProvider = new PlainCredentialsProvider(configuration.Username, configuration.Password);

            var teamProjectCollection = new TfsTeamProjectCollection(new Uri(configuration.CollectionUri), credentialProvider);
            buildServer = teamProjectCollection.GetService<IBuildServer>();

            if (timer == null)
            {
                timer = new Timer(Tick, null, 0, configuration.PollInterval);
            }
            else
            {
                timer.Change(0, configuration.PollInterval);
            }
        }
예제 #16
0
파일: Program.cs 프로젝트: ledgarl/Samples
        static void Main(string[] args)
        {
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("https://code-inside.visualstudio.com/DefaultCollection"));

            VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

            //Following will get all changesets since 365 days. Note : "DateVersionSpec(DateTime.Now - TimeSpan.FromDays(20))"
            System.Collections.IEnumerable history = vcs.QueryHistory("$/Grocerylist", 
                                                                      LatestVersionSpec.Instance,
                                                                      0,
                                                                      RecursionType.Full,
                                                                      null,
                                                                      new DateVersionSpec(DateTime.Now - TimeSpan.FromDays(365)),
                                                                      LatestVersionSpec.Instance,
                                                                      Int32.MaxValue,
                                                                      true,
                                                                      false);

            foreach (Changeset changeset in history)
            {
                Console.WriteLine("Changeset Id: " + changeset.ChangesetId);
                Console.WriteLine("Owner: " + changeset.Owner);
                Console.WriteLine("Date: " + changeset.CreationDate.ToString());
                Console.WriteLine("Comment: " + changeset.Comment);
                Console.WriteLine("-------------------------------------");
            }

            Console.ReadLine();
        }
예제 #17
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;
        }
		public string GetLastButOneRevision()
		{
			var collection = new TfsTeamProjectCollection(new Uri(ConfigHelper.Instance.FuncTestCollection));
			var vcs = collection.GetService<VersionControlServer>();
			TeamProject tp = vcs.GetTeamProject(ConfigHelper.Instance.FuncTestsProject);

			var changesets = vcs.QueryHistory(
					tp.ServerItem,
					VersionSpec.Latest,
					0,
					RecursionType.Full,
					null,
					null,
					null,
					Int32.MaxValue,
					true,
					true).Cast<Changeset>().ToArray();

			collection.Dispose();

			if (changesets.Count() == 1)
				return changesets.First().ChangesetId.ToString();

			int lastButOneChangeset = changesets.Where(x => x.ChangesetId < changesets.Max(m => m.ChangesetId)).Max(x => x.ChangesetId);

			return lastButOneChangeset.ToString(CultureInfo.InvariantCulture);
		}
예제 #19
0
        public TFSWorkItemManager(Config.InstanceConfig config)
        {
            ValidateConfig(config);

            _config = config;

            // Init TFS service objects
            _tfsServer = ConnectToTfsCollection();
            Logger.InfoFormat("Connected to TFS. Getting TFS WorkItemStore");

            _tfsStore = _tfsServer.GetService<WorkItemStore>();

            if (_tfsStore == null)
            {
                Logger.ErrorFormat("Cannot initialize TFS Store");
                throw new Exception("Cannot initialize TFS Store");
            }

            Logger.InfoFormat("Geting TFS Project");
            _tfsProject = _tfsStore.Projects[config.TfsServerConfig.Project];

            Logger.InfoFormat("Initializing WorkItems Cache");
            InitWorkItemsCache();

            _nameResolver = InitNameResolver();
        }
 /// <summary>
 /// Selects the target Team Project containing the migrated test cases.
 /// </summary>
 /// <param name="serverUrl">URL of TFS Instance</param>
 /// <param name="project">Name of Project within the TFS Instance</param>
 /// <returns>The Team Project</returns>
 private static ITestManagementTeamProject GetProject(string serverUrl, string project)
 {
     var uri = new System.Uri(serverUrl);
     TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(uri);
     ITestManagementService tms = tfs.GetService<ITestManagementService>();
     return tms.GetTeamProject(project);
 }
예제 #21
0
        /// <summary>
        /// Compares changesets
        /// </summary>
        /// <param name="localPath"></param>
        /// <param name="sourceChangesetId">Source changeset Id</param>
        /// <param name="serverUrl">Server Uri</param>
        /// <param name="srcPath">Source item path</param>
        public static void CompareLocal(string localPath, string sourceChangesetId, string serverUri, string srcPath)
        {
            if (String.IsNullOrWhiteSpace(sourceChangesetId))
                throw new ArgumentException("'sourceChangesetId' is null or empty.");
            if (String.IsNullOrWhiteSpace(serverUri))
                throw new TfsHistorySearchException("'serverUri' is null or empty.");
            if (String.IsNullOrWhiteSpace(srcPath))
                throw new TfsHistorySearchException("'srcPath' is null or empty.");
            if (String.IsNullOrWhiteSpace(localPath))
                throw new TfsHistorySearchException("'localPath' is null or empty.");

            TfsTeamProjectCollection tc = new TfsTeamProjectCollection(new Uri(serverUri));
            VersionControlServer vcs = tc.GetService(typeof(VersionControlServer)) as VersionControlServer;

            //VersionSpec sourceVersion = VersionSpec.ParseSingleSpec(sourceChangesetId, vcs.TeamFoundationServer.AuthenticatedUserName);
            VersionSpec sourceVersion = VersionSpec.ParseSingleSpec(sourceChangesetId, vcs.AuthorizedUser);

            //VersionSpec targetVersion = VersionSpec.ParseSingleSpec(targetChangesetId, vcs.TeamFoundationServer.AuthenticatedUserName);

            //Difference.DiffFiles(
            Difference.VisualDiffItems(vcs, Difference.CreateTargetDiffItem(vcs, srcPath, sourceVersion, 0, sourceVersion), Difference.CreateTargetDiffItem(vcs, localPath, null, 0, null));
            //Difference.VisualDiffFiles();
            //Difference.VisualDiffItems(vcs,
            //                           Difference.CreateTargetDiffItem(vcs, srcPath, sourceVersion, 0, sourceVersion),
            //                           Difference.CreateTargetDiffItem(vcs, targetPath, targetVersion, 0, targetVersion));
        }
예제 #22
0
        public object GetService(Type serviceType)
        {
            var collection = new TfsTeamProjectCollection(_projectCollectionUri);

            object service;

            try
            {

                if (_buildConfigurationManager.UseCredentialToAuthenticate)
                {
                    collection.Credentials = new NetworkCredential(_buildConfigurationManager.TfsAccountUserName,
                        _buildConfigurationManager.TfsAccountPassword, _buildConfigurationManager.TfsAccountDomain);
                }

                collection.EnsureAuthenticated();
                service = collection.GetService(serviceType);
            }
            catch (Exception ex)
            {
                Tracing.Client.TraceError(
                    String.Format("Error communication with TFS server: {0} detail error message {1} ",
                                  _projectCollectionUri, ex));
                throw;
            }
            Tracing.Client.TraceInformation("Connection to TFS established.");
            return service;
        }
예제 #23
0
        private ITestManagementTeamProject2 GetTestProject()
        {
            var collectionUri = SpecFlow2TFSConfig.TFS_URL + "/" + SpecFlow2TFSConfig.COLLECTION.Substring(SpecFlow2TFSConfig.COLLECTION.LastIndexOf('\\') + 1);

            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(collectionUri));

            WorkItemStore workItemStore = new WorkItemStore(tpc);

            Project project = null;

            foreach (Project p in workItemStore.Projects)
            {
                if (p.Name == SpecFlow2TFSConfig.PROJECT)
                {
                    project = p;
                    break;
                }
            }

            if (project == null)
            {
                throw new NullReferenceException("no project found for the name " + SpecFlow2TFSConfig.PROJECT);
            }

            // get test management service
            ITestManagementService2 test_service = (ITestManagementService2)tpc.GetService(typeof(ITestManagementService2));
            ITestManagementTeamProject2 test_project = test_service.GetTeamProject(project);
            return test_project;
        }
예제 #24
0
 public virtual void Connect()
 {
     WorkspaceInfo wi = Workstation.Current.GetLocalWorkspaceInfo(Environment.CurrentDirectory);
     using (var tfs = new TfsTeamProjectCollection(wi.ServerUri))
     {
         versionControlServer = tfs.GetService<VersionControlServer>();
     }
 }
예제 #25
0
 public WorkItemRead(TfsTeamProjectCollection tfs, Project sourceProject)
 {
     this.tfs = tfs;
     projectName = sourceProject.Name;
     store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
     queryCol = store.Projects[sourceProject.Name].QueryHierarchy;
     workItemTypes = store.Projects[sourceProject.Name].WorkItemTypes;
 }
 public static TfsTeamProjectCollection CreateImpersonatedCollection(Uri collectionToUse, string userToImpersonate)
 {
     NetworkCredential defaultNetworkCredentials = CredentialCache.DefaultNetworkCredentials;
     TfsTeamProjectCollection tfsTeamProjectCollection = new TfsTeamProjectCollection(collectionToUse, defaultNetworkCredentials);
     IIdentityManagementService service = tfsTeamProjectCollection.GetService<IIdentityManagementService>();
     TeamFoundationIdentity teamFoundationIdentity = service.ReadIdentity(IdentitySearchFactor.AccountName, userToImpersonate, MembershipQuery.None, ReadIdentityOptions.None);
     return new TfsTeamProjectCollection(collectionToUse, new TfsClientCredentials(), teamFoundationIdentity.Descriptor);
 }
예제 #27
0
        public TfsContext()
        {
            tfsServer = new TfsTeamProjectCollection(new Uri(Properties.Settings.Default.TfsAddress));

            tfsServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential());

            this.CurrentWorkItemStore = tfsServer.GetService<WorkItemStore>();
        }
 public void Initialize(TfsTeamProjectCollection tfs, string projectName)
 {
     _isInitialized = true;
     _workItemStore = tfs.GetService<WorkItemStore>();
     _project = _workItemStore.Projects
             .Cast<Project>()
             .SingleOrDefault(p => p.Name.Equals(projectName));
 }
 public AutomatedPostReview(ILog log, Configuration.Configuration config)
 {
     this.log = log;
     this.config = config;
     api = new ReviewboardApi(new Uri(config.ReviewBoardServer),
                                  new NetworkCredential(config.ReviewBoardUserName, config.ReviewBoardPassword));
     var teamProjectCollection = new TfsTeamProjectCollection(config.ServerUri);
     vcs = teamProjectCollection.GetService<VersionControlServer>();
 }
예제 #30
0
        /// <summary>
        /// Connects the specified URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="projectName">Name of the project.</param>
        /// <returns></returns>
        public TfsConnector Connect(string url, string projectName)
        {
            var tfs = new TfsTeamProjectCollection(new Uri(url));

            this.buildServer = (IBuildServer) tfs.GetService(typeof (IBuildServer));
            this.buildDetailSpec = this.buildServer.CreateBuildDetailSpec(projectName);

            return this;
        }
        public static ICollection <ProjectDefinition> GetAllProjects(TfsConfigurationServer configurationServer)
        {
            List <ProjectDefinition>      projectList       = new List <ProjectDefinition>();
            ITeamProjectCollectionService collectionService = configurationServer.GetService <ITeamProjectCollectionService>();

            if (collectionService != null)
            {
                IList <TeamProjectCollection> collections = collectionService.GetCollections();
                foreach (TeamProjectCollection collection in collections)
                {
                    if (collection.State == TeamFoundationServiceHostStatus.Started)
                    {
                        TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(collection.Id);
                        VersionControlServer     vcs = tpc.GetService <VersionControlServer>();
                        if (vcs != null)
                        {
                            TeamProject[] projects = vcs.GetAllTeamProjects(true);
                            foreach (TeamProject project in projects)
                            {
                                string name = project.Name;
                                IEnumerable <Changeset> changesets = vcs.QueryHistory(project.ServerItem, VersionSpec.Latest, 0, RecursionType.None, String.Empty, null, VersionSpec.Latest, int.MaxValue, true, false, false, true).OfType <Changeset>();
                                Changeset firstChangeset           = changesets.FirstOrDefault();
                                if (firstChangeset != null)
                                {
                                    DateTime creationDate = firstChangeset.CreationDate;

                                    ProjectDefinition projectDefinition = new ProjectDefinition();
                                    projectDefinition.Name            = project.Name;
                                    projectDefinition.CollectionName  = collection.Name;
                                    projectDefinition.UtcCreationDate = creationDate.ToUniversalTime();
                                    projectList.Add(projectDefinition);
                                }
                            }
                        }
                    }
                }
            }
            return(projectList);
        }
예제 #32
0
파일: Program.cs 프로젝트: xanthalas/TfsCli
        private static void connectToTfs()
        {
            try
            {
                // Connect to the server and the store, and get the WorkItemType object
                // for user stories from the team project where the user story will be created.
                Uri collectionUri = new Uri(tfsUrl);

                TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(collectionUri);
                workItemStore = tpc.GetService <WorkItemStore>();
                Project teamProject = workItemStore.Projects[tfsProject];
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("A problem occurred while connecting to TFS:");
                Console.WriteLine(e);
                Console.ForegroundColor = defaultColour;
                Console.WriteLine("");
                Environment.Exit(3);
            }
        }
예제 #33
0
        public void ConnectToTfsServer(string hostname, string teamCollection, string projectName, Regex buildDefinitionNameFilter = null)
        {
            _hostname = hostname;

            _isWebServer = _hostname.Contains("://");
            try
            {
                string url;
                if (_isWebServer)
                {
                    _hostname  = _hostname.TrimEnd('\\', '/');
                    url        = _hostname + "/" + teamCollection;
                    _urlPrefix = hostname + "/" + teamCollection + "/" + projectName + "/_build#buildUri=";
                }
                else
                {
                    url        = "http://" + _hostname + ":8080/tfs/" + teamCollection;
                    _urlPrefix = "http://" + hostname + ":8080/tfs/" + (String.IsNullOrEmpty(teamCollection) ? "" : teamCollection + "/") + "Build/Build.aspx?artifactMoniker=";
                }

                _tfsCollection = new TfsTeamProjectCollection(new Uri(url), new TfsClientCredentials());

                _buildServer = _tfsCollection.GetService <IBuildServer>();

                var buildDefs = _buildServer.QueryBuildDefinitions(projectName);

                if (buildDefs.Length != 0)
                {
                    _buildDefinitions = string.IsNullOrWhiteSpace(buildDefinitionNameFilter.ToString())
                        ? buildDefs
                        : (buildDefs.Where(b => buildDefinitionNameFilter.IsMatch(b.Name))).Cast <IBuildDefinition>().ToArray();
                }
                ConnectToTfsServer2015(hostname, teamCollection, projectName, buildDefinitionNameFilter);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
        }
예제 #34
0
        protected override bool Execute(WorkspaceInfo workspaceInfo)
        {
            var result = new List <TaskItem>();

            using var collection = new TfsTeamProjectCollection(workspaceInfo.ServerUri);

            var vcServer    = collection.GetService <VersionControlServer>();
            var changesetId = vcServer.GetLatestChangesetId().ToString();

            var workspace     = workspaceInfo.GetWorkspace(collection);
            var collectionUrl = collection.Uri.ToString();

            // TODO: eliminate redundant mappings - we can use RepositoryRoot calculation here
            // E.g. A\B -> $/X/A/B, A\C -> $/X/A/C can be reduced to A -> $/X/A

            foreach (var folder in workspace.Folders)
            {
                if (!folder.IsCloaked)
                {
                    var project = workspace.GetTeamProjectForLocalPath(folder.LocalItem);

                    // Extract GUID from ArtifactUri "vstfs:///Classification/TeamProject/{Guid}":
                    var projectId = Path.GetFileName(project.ArtifactUri.GetPath());

                    // SourceLink.AzureRepos will map each source root to:
                    // {RepositoryUrl}/_versionControl?path={ServerPath}&version={RevisionId}
                    var item = new TaskItem(folder.LocalItem);
                    item.SetMetadata("SourceControl", "tfvc");
                    item.SetMetadata("CollectionUrl", collectionUrl);
                    item.SetMetadata("ProjectId", projectId);
                    item.SetMetadata("ServerPath", folder.ServerItem);
                    item.SetMetadata("RevisionId", changesetId);
                    result.Add(item);
                }
            }

            Mapping = result.ToArray();
            return(true);
        }
예제 #35
0
        private void btnTeamProject_Click(object sender, EventArgs e)
        {
            //Displaying the Team Project selection dialog to select the desired team project.
            TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.MultiProject, false);

            tpp.ShowDialog();

            //Following actions will be executed only if a team project is selected in the the opened dialog.
            if (tpp.SelectedTeamProjectCollection != null)
            {
                this._tfs = tpp.SelectedTeamProjectCollection;
                ITestManagementService test_service = (ITestManagementService)_tfs.GetService(typeof(ITestManagementService));
                this._teamProject = test_service.GetTeamProject(tpp.SelectedProjects[0].Name);

                //Populating the text field Team Project name (txtTeamProject) with the name of the selected team project.
                txtTeamProject.Text = tpp.SelectedProjects[0].Name;
                flag1 = 1;

                //Call to method "Get_TestPlans" to get the test plans in the selected team project
                Get_TestPlans(_teamProject);
            }
        }
예제 #36
0
 private void DropMappings(TfsTeamProjectCollection collection)
 {
     try
     {
         var vcs       = collection.GetService <VersionControlServer>();
         var wss       = vcs.QueryWorkspaces(null, vcs.AuthorizedUser, null);
         var localPath = collection.GetProjectCollectionLocalPath(Globals.TfsRoot);
         var withPath  = wss.Select(workspace => Tuple.Create(workspace, workspace.TryGetWorkingFolderForServerItem(collection.Uri.AbsoluteUri)));
         foreach (var tuple in withPath)
         {
             if (tuple.Item1 != null && tuple.Item2 != null)
             {
                 $"Dropping {tuple.Item2.LocalItem} for workspace {tuple.Item1.Name}".Info();
                 tuple.Item1.DeleteMapping(tuple.Item2);
             }
         }
     }
     catch (Exception e)
     {
         e.Error();
     }
 }
예제 #37
0
        private dynamic GetTestcoverage(TfsTeamProjectCollection projectCollection, Uri uri)
        {
            var watch = Stopwatch.StartNew();

            projectCollection.EnsureAuthenticated();
            var tcm = projectCollection.GetService <ITestManagementService>();
            var testManagementTeamProject = tcm.GetTeamProject(_settings.Project);
            var runs = testManagementTeamProject.TestRuns.ByBuild(uri);

            var result = new
            {
                Statistics = runs.Select(x => new
                {
                    x.Statistics.TotalTests,
                    x.Statistics.FailedTests,
                    x.Statistics.PassedTests
                }).ToList()
            };

            Trace.WriteLine("GetTestCoverage: " + watch.Elapsed);
            return(result);
        }
예제 #38
0
        protected override string Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            string text           = context.GetValue(this.OutputFile);
            string filename       = context.GetValue(this.FileName);
            string configFilePath = context.GetValue(this.ServerName);
            //http://team:8080/tfs/WebSites

            /*
             * string BaseTFSDir = bldConfig.Rules["BaseTFSDir"].Value;
             * string BaseDeploymentDir = bldConfig.Rules["BaseDeploymentDir"].Value;
             * string BuildDeploymentDir = bldConfig.Rules["BuildDeploymentDir"].Value;
             */

            IBuildDetail bldD = context.GetValue(BuildDetail);

            TfsTeamProjectCollection tfs = bldD.BuildServer.TeamProjectCollection;
            ///new  TfsTeamProjectCollection(new Uri(context.GetValue(ServerName) as string));//
            VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

            bldD.RefreshAllDetails();
            //commensurate the zip deployment with the current build
            TeamFoundationIdentity id;

            tfs.GetAuthenticatedIdentity(out id);
            //ZipDeployer.UID = (id == null)?"UnknownUser" : id.UniqueName;

            //var changesets = InformationNodeConverters.GetAssociatedChangesets(bldD);//.OrderBy(a=> a.ChangesetId);
            var changesets = context.GetValue(this.AssocSets);


            TFSDeployerController deploy = new TFSDeployerController(tfs.Uri.AbsoluteUri, configFilePath, bldD.BuildNumber);

            return(deploy.deploy(tfs, changesets));
            /**/
            //if (string.IsNullOrEmpty(text))
            //  throw new ArgumentException("Please specify a path");
            //String.Format("{0}@$/{1}", LabelName, BuildDetail.BuildDefinition.TeamProject)
        }
예제 #39
0
        public ActionResult IdentityOverview(string id, string projectid)
        {
            if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(projectid))
            {
                return(RedirectToAction("Index"));
            }

            TfsTeamProjectCollection         tpc = configurationServer.GetTeamProjectCollection(new Guid(id));
            ReadOnlyCollection <CatalogNode> teamProjectNodes = tpc.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.TeamProject }, new[] { new KeyValuePair <string, string>("ProjectID", projectid) },
                false, CatalogQueryOptions.None);
            IIdentityManagementService ims = tpc.GetService <IIdentityManagementService>();
            string projectUri;
            IdentityOverviewModel iom = new IdentityOverviewModel();

            if (teamProjectNodes.Count() == 1)
            {
                projectUri = teamProjectNodes[0].Resource.Properties["ProjectUri"];
                IdentityServiceManagementHelper.FeedIdentityData(iom.ApplicationGroupCollection, iom.UserCollection, ims, projectUri);
            }
            return(PartialView(iom));
        }
예제 #40
0
        private IList <Project> BuildProjectItems(TfsTeamProjectCollectionUri uri)
        {
            IList <Project> projs = new List <Project>();

            if (!_projects.ContainsKey(uri))
            {
                TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(uri.Value), CredentialCache.DefaultNetworkCredentials);
                tpc.Authenticate();

                //运行路径(E:\VSTS\VS2015\ImportWorkItems\TFSideKicks\bin\Debug)下必须存在如下文件:Microsoft.WITDataStore64.dll,否则报错。另外“生成”Any CPU;去掉勾选“首选32位”选项
                WorkItemStore workItemStore = tpc.GetService <WorkItemStore>();
                foreach (Project item in workItemStore.Projects)
                {
                    if (!item.Name.StartsWith("CDSS"))
                    {
                        projs.Add(item);
                    }
                }
                _projects[uri] = projs;
            }
            return(_projects[uri]);
        }
예제 #41
0
        /// <summary>
        /// Get Email Address from TFS Account or Display Name
        /// </summary>
        /// <remarks>https://paulselles.wordpress.com/2014/03/24/tfs-api-tfs-user-email-address-lookup-and-reverse-lookup/</remarks>
        private string GetEmailAddress(TfsTeamProjectCollection tpc, string displayName)
        {
            if (string.IsNullOrEmpty(displayName))
            {
                return(string.Empty);
            }
            try
            {
                IIdentityManagementService IdentityManagementService = tpc.GetService <IIdentityManagementService>();
                TeamFoundationIdentity     teamFoundationIdentity    =
                    IdentityManagementService.ReadIdentity(
                        IdentitySearchFactor.AccountName | IdentitySearchFactor.DisplayName,
                        displayName,
                        MembershipQuery.None,
                        ReadIdentityOptions.None);

                return(teamFoundationIdentity.GetAttribute("Mail", null));
            } catch
            {
                return(string.Empty);
            }
        }
예제 #42
0
        public static bool AddAADGroupToTPCustomGroup(string teamProject, string tpCustomGroupName, string aadGroupName, string organizationUrl)
        {
            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            var tpc = new TfsTeamProjectCollection(new Uri(organizationUrl), creds);

            tpc.Connect(Microsoft.TeamFoundation.Framework.Common.ConnectOptions.IncludeServices);

            IIdentityManagementService ims = tpc.GetService <IIdentityManagementService>();

            string tpCustomGroupNameFull = "[" + teamProject + "]" + "\\" + tpCustomGroupName;
            string aadGroupNameFull      = "[TEAM FOUNDATION]" + "\\" + aadGroupName; //for AAD Groups

            try
            {
                var tfsGroupIdentity = ims.ReadIdentity(IdentitySearchFactor.AccountName,
                                                        tpCustomGroupNameFull,
                                                        MembershipQuery.None,
                                                        ReadIdentityOptions.IncludeReadFromSource);

                var aadGroupIdentity = ims.ReadIdentity(IdentitySearchFactor.AccountName,
                                                        aadGroupNameFull,
                                                        MembershipQuery.None,
                                                        ReadIdentityOptions.IncludeReadFromSource);

                ims.AddMemberToApplicationGroup(tfsGroupIdentity.Descriptor, aadGroupIdentity.Descriptor);

                Console.WriteLine("Group added: " + aadGroupName + " to " + tpCustomGroupName);
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Group cannot be added: " + aadGroupName + ", " + tpCustomGroupName);
                return(false);
            }
        }
예제 #43
0
        public void Init(params string[] args)
        {
            string localPath         = args[0];
            string versionFromString = args[1];

            resultsFile = args[4];
            bool isHPAS = Convert.ToBoolean(args[3]);

            if (isHPAS)
            {
                startString = "src/";
            }
            else
            {
                startString = "stingray/";
            }
            //connect to TFS
            TfsTeamProjectCollection tfs = null;

            tfs = new TfsTeamProjectCollection(new Uri("###ADD URI TO YOU TFS PROJECT COLLECTION HERE###"));
            VersionControlServer vcs = tfs.GetService <VersionControlServer>();

            try {
                var changesetItems = vcs.QueryHistory(localPath, VersionSpec.ParseSingleSpec(versionFromString, null), 0, RecursionType.Full, null, VersionSpec.ParseSingleSpec(versionFromString, null), null, Int32.MaxValue, true, false);

                foreach (Changeset csItem in changesetItems)
                {
                    ProcessChangeSet(csItem, args[2]);
                }
                var writeOutput = new WriteOutput();
                writeOutput.Init(resultsFile, Tasks);
                writeOutput.WriteOutTasksWithChangesets();
            }
            catch (Exception e) {
                Console.WriteLine("Error: " + e.Message);
                Console.ReadKey();
            }
        }
예제 #44
0
        void m_worker_DoWork(object sender, DoWorkEventArgs e)
        {
            if (e.Argument is VCServerPathNodeViewModel)
            {
                VCServerPathNodeViewModel node = e.Argument as VCServerPathNodeViewModel;
                node.GetItems(m_server);
                e.Result = node;
            }
            else
            {
                TfsTeamProjectCollection collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(m_migrationSource.ServerUrl));
                m_server = collection.GetService <VersionControlServer>();

                Item item = m_server.GetItem(VersionControlPath.RootFolder + m_migrationSource.SourceIdentifier);
                VCServerPathRootViewModel rootNode = new VCServerPathRootViewModel(item, this);
                rootNode.Load(m_server);
                rootNode.IsExpanded = true;
                SelectedNode        = rootNode;
                string[] tokens = m_filterItem.FilterString.Split(VersionControlPath.Separator);
                for (int i = 2; i < tokens.Length; i++)
                {
                    SelectedNode.Load(m_server);
                    SelectedNode.IsExpanded = true;

                    VCServerPathNodeViewModel newSelectedNode = SelectedNode.Children.FirstOrDefault(x => string.Equals(x.DisplayName, tokens[i]));

                    if (newSelectedNode != null)
                    {
                        SelectedNode = newSelectedNode;
                    }
                    else
                    {
                        break;
                    }
                }
                e.Result = rootNode;
            }
        }
예제 #45
0
        public static string getCommand()
        {
            string       id              = "";
            Uri          collectionUri   = new Uri("https://masssluis.visualstudio.com/DefaultCollection");
            const string serviceUser     = "******";
            const string servicePassword = "******";
            //const string teamProject = "MyFirstProject";

            NetworkCredential    netCred   = new NetworkCredential(serviceUser, servicePassword);
            BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive = false;

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

            tfs.Authenticate();



            WorkItemStore workItemStore = tfs.GetService <WorkItemStore>();
            Project       teamProject1  = workItemStore.Projects["MyFirstProject"];
            WorkItemType  workItemType  = teamProject1.WorkItemTypes["Bug"];

            // Create the work item.
            WorkItem userStory = new WorkItem(workItemType)
            {
                // The title is generally the only required field that doesn’t have a default value.
                // You must set it, or you can’t save the work item. If you’re working with another
                // type of work item, there may be other fields that you’ll have to set.
                Title = "this is a test bug by masss team"
            };

            // Save the new user story.
            userStory.Save();
            id = userStory.Id.ToString();
            return(id);
        }
예제 #46
0
        public void updateTasks(int fromChangeset, int toChangeset, UpdateJiraOptions options, Branch branch)
        {
            using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(options.CollectionUrl)))
            {
                string tfsRoot = options.TfsWorkspacePath;
                var    vsStore = tpc.GetService <VersionControlServer>();

                var changesets = vsStore.QueryHistory(branch.Path + "/" + options.ModelName,
                                                      VersionSpec.Latest,
                                                      0,
                                                      RecursionType.Full,
                                                      null,
                                                      VersionSpec.ParseSingleSpec(fromChangeset.ToString(), null),
                                                      VersionSpec.ParseSingleSpec(toChangeset.ToString(), null),
                                                      Int32.MaxValue,
                                                      true,
                                                      false,
                                                      true);

                foreach (Changeset changeset in changesets)
                {
                    if (changeset.ChangesetId < fromChangeset ||
                        changeset.ChangesetId > toChangeset)
                    {
                        continue;
                    }

                    int n = 0;

                    string taskNumber = getTaskNumber(changeset.Comment);

                    if (int.TryParse(taskNumber, out n))
                    {
                        UpdateTask(int.Parse(taskNumber), options).GetAwaiter().GetResult();
                    }
                }
            }
        }
예제 #47
0
        static void Main(string[] args)
        {
            // Auth with UserName & Password (Microsoft Acc):
            //BasicAuthCredential basicCred = new BasicAuthCredential(new NetworkCredential("*****@*****.**", "pw"));
            //TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            //tfsCred.AllowInteractive = false;
            //
            //TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("https://code-inside.visualstudio.com/DefaultCollection"), tfsCred);

            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("https://code-inside.visualstudio.com/DefaultCollection"));

            IBuildServer buildServer = (IBuildServer)tfs.GetService(typeof(IBuildServer));

            var builds = buildServer.QueryBuilds("DrinkHub");

            foreach (IBuildDetail build in builds)
            {
                var result = string.Format("Build {0}/{3} {4} - current status {1} - as of {2}",
                                           build.BuildDefinition.Name,
                                           build.Status.ToString(),
                                           build.FinishTime,
                                           build.LabelName,
                                           Environment.NewLine);

                System.Console.WriteLine(result);
            }

            // Detailed via http://www.incyclesoftware.com/2012/09/fastest-way-to-get-list-of-builds-using-ibuildserver-querybuilds-2/

            var buildSpec = buildServer.CreateBuildDetailSpec("DrinkHub", "Main.Continuous");

            buildSpec.InformationTypes = null;
            var buildDetails = buildServer.QueryBuilds(buildSpec).Builds;

            Console.WriteLine(buildDetails.First().Status);

            Console.ReadLine();
        }
예제 #48
0
        public override int RunInternal(ImportPicturesOptions opts)
        {
            if (!Directory.Exists(opts.OutPath))
            {
                Directory.CreateDirectory(opts.OutPath);
            }

            if (opts.CollectionURL.ToString().Contains("visualstudio.com"))
            {
                throw new InvalidDomainException("Unable to upload pictures to VSTS due to API/Permission restrictions.");
            }

            TfsTeamProjectCollection collection = new TfsTeamProjectCollection(opts.CollectionURL);

            collection.EnsureAuthenticated();
            IIdentityManagementService2 ims2 = (IIdentityManagementService2)collection.GetService(typeof(IIdentityManagementService2));


            var files = Directory.GetFiles(opts.OutPath);
            var regex = new Regex(Regex.Escape("-"));

            foreach (string file in files)
            {
                string ident = regex.Replace(Path.GetFileNameWithoutExtension(file), @"\", 1);
                string mess;
                if (SetProfileImage(ims2, ident, file, out mess))
                {
                    Trace.WriteLine(string.Format(" [UPDATE] New Profile for : {0} ", ident));
                    File.Delete(file);
                }
                else
                {
                    Trace.WriteLine(string.Format(" [FAIL] Unable to set: {0} ", ident));
                }
            }

            return(0);
        }
예제 #49
0
        public void ConnectToTfsServer(string hostname, string teamCollection, string projectName, string buildDefinitionName = null)
        {
            _hostname = hostname;

            _isWebServer = _hostname.Contains("://");
            try
            {
                string url;
                if (_isWebServer)
                {
                    _hostname  = _hostname.TrimEnd('\\', '/');
                    url        = _hostname + "/" + teamCollection;
                    _urlPrefix = hostname + "/" + teamCollection + "/" + projectName + "/_build#buildUri=";
                }
                else
                {
                    url        = "http://" + _hostname + ":8080/tfs/" + teamCollection;
                    _urlPrefix = "http://" + hostname + ":8080/tfs/Build/Build.aspx?artifactMoniker=";
                }

                _tfsCollection = new TfsTeamProjectCollection(new Uri(url), new TfsClientCredentials());

                _buildServer = _tfsCollection.GetService <IBuildServer>();

                var buildDefs = _buildServer.QueryBuildDefinitions(projectName);

                if (buildDefs.Length != 0)
                {
                    _buildDefinition = string.IsNullOrWhiteSpace(buildDefinitionName)
                        ? buildDefs[0]
                        : buildDefs.FirstOrDefault(b => string.Compare(b.Name, buildDefinitionName, StringComparison.InvariantCultureIgnoreCase) == 0);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
        }
예제 #50
0
        /// <summary>
        /// Opens the Common TFS Project Selection Form.
        /// </summary>
        /// <returns></returns>
        public static ITestManagementTeamProject SelectTfsProject(bool isDestinationProject)
        {
            TeamProjectPicker teamProjectPicker = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
            DialogResult      result            = teamProjectPicker.ShowDialog();

            if (result == DialogResult.OK && teamProjectPicker.SelectedTeamProjectCollection != null)
            {
                if (isDestinationProject && teamProjectPicker.SelectedTeamProjectCollection != null)
                {
                    TfsTeamProjectCollection destinationTeamProjectCollection = teamProjectPicker.SelectedTeamProjectCollection;
                    destinationTeamProjectCollection.Connect(ConnectOptions.IncludeServices);
                    _destinationStructureService = destinationTeamProjectCollection.GetService(typeof(ICommonStructureService)) as ICommonStructureService;
                }

                TfsTeamProjectCollection teamProjectCollection = teamProjectPicker.SelectedTeamProjectCollection;
                ITestManagementService   testManagementService = (ITestManagementService)teamProjectCollection.GetService(typeof(ITestManagementService));

                ITestManagementTeamProject project = testManagementService.GetTeamProject(teamProjectPicker.SelectedProjects[0].Name);

                return(project);
            }
            return(null);
        }
예제 #51
0
        // ===============================================================
        // Utility methods - could be moved elsewhere

        // For call to create TR we need Ericsson user id (also domain?) - seems like we have what we want here.
        // See http://stackoverflow.com/questions/19911368/using-the-tfs-2012-api-how-do-i-get-the-email-address-of-a-user
        static public TeamFoundationIdentity GetSignumForAssignedTo(
            Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem workItem)
        {
            TfsTeamProjectCollection tpc = workItem.Store.TeamProjectCollection;
            String userName = workItem.Fields[TFSMapper.TFS_OWNER].Value.ToString();

            IIdentityManagementService mgmntService = tpc.GetService <IIdentityManagementService>();

            TeamFoundationIdentity member = mgmntService.ReadIdentity(
                IdentitySearchFactor.DisplayName,
                userName,
                MembershipQuery.Direct,
                ReadIdentityOptions.ExtendedProperties);

            if (member == null)
            {
                HandlerSettings.LogMessage(
                    String.Format("Failed to get user identity for user: {0}", userName),
                    HandlerSettings.LoggingLevel.WARN);
            }

            return(member);
        }
예제 #52
0
        public IEnumerable <IShelveset> GetShelvesetByOwner(string serverUrl, string actingUserName, string ownerName)
        {
            TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl));

            teamProjectCollection.EnsureAuthenticated();

            VersionControlServer vcServer             = teamProjectCollection.GetService <VersionControlServer>();
            HashSet <string>     workspaceBranchNames = new HashSet <string>();

            foreach (Workspace workspace in vcServer.QueryWorkspaces(null, actingUserName, null))
            {
                workspace.Folders.ToList().ForEach(f => workspaceBranchNames.Add(f.ServerItem));
            }

            foreach (Shelveset shelveset in vcServer.QueryShelvesets(null, ownerName))
            {
                PendingSet changeSet = vcServer.QueryShelvedChanges(shelveset).FirstOrDefault();
                if (changeSet != null)
                {
                    yield return(new AdapterShelveset(shelveset, changeSet.PendingChanges, workspaceBranchNames.ToArray()));
                }
            }
        }
예제 #53
0
        private static IEnumerable <WorkingFolder> GetWorkingFolders(string tfsName, string tfsWorkSpace, string[] tfsProjects, ref Workspace workspace)
        {
            TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsName));

            tfs.Authenticate();

            VersionControlServer versionControl = tfs.GetService <VersionControlServer>();

            if (string.IsNullOrEmpty(tfsWorkSpace))
            {
                tfsWorkSpace = Environment.MachineName;
            }
            Workspace[] workSpaces = versionControl.QueryWorkspaces(tfsWorkSpace, versionControl.AuthorizedUser, Environment.MachineName);
            if (workSpaces.Length == 0)
            {
                throw new Exception($"TFS WorkSpace '{tfsWorkSpace}' not found");
            }

            workspace = workSpaces[0];
            List <WorkingFolder> folders = new List <WorkingFolder>(workspace.Folders);

            return(FindWorkingFolders(tfsProjects, folders));
        }
예제 #54
0
 /// <summary>
 /// Connects to the Project Collection
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnConnect_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (cboServer.Text != string.Empty)
         {
             Mouse.OverrideCursor = Cursors.Wait;
             _tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(cboServer.Text),
                                                                             new UICredentialsProvider());
             _tfs.EnsureAuthenticated();
             LoadProjects();
             _wis = (WorkItemStore)_tfs.GetService(typeof(WorkItemStore));
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         Mouse.OverrideCursor = null;
     }
 }
예제 #55
0
        public IEnumerable <Changeset> PullChangesets(Uri tfsConnectionstring, string projectName, DateTime startDate, DateTime endDate)
        {
            try
            {
                VersionSpec versionFrom = new DateVersionSpec(startDate);
                VersionSpec versionTo   = new DateVersionSpec(endDate);

                TfsTeamProjectCollection projectCollection =
                    TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsConnectionstring);
                VersionControlServer versionControlServer = (VersionControlServer)projectCollection.GetService(typeof(VersionControlServer));

                IEnumerable changesetHistory =
                    versionControlServer.QueryHistory("$/" + projectName + "/", VersionSpec.Latest, 0,
                                                      RecursionType.Full, null, versionFrom, versionTo, int.MaxValue,
                                                      false, false);

                return(changesetHistory.Cast <Changeset>().ToList());
            }
            catch (Exception ex)
            {
                throw new TeamFoundationException("Unable to get versionControlServer for TFS server " + tfsConnectionstring.AbsoluteUri, ex);
            }
        }
        protected override bool Execute(WorkspaceInfo workspaceInfo)
        {
            using (var collection = new TfsTeamProjectCollection(workspaceInfo.ServerUri))
            {
                var vcServer  = collection.GetService <VersionControlServer>();
                var workspace = vcServer.GetWorkspace(workspaceInfo);
                var evaluator = new LocalItemExclusionEvaluator(workspace, startLocalItem: ""); // TODO?

                var result = new List <ITaskItem>();
                foreach (var item in SourceFiles)
                {
                    if (FileSpec.IsSubItem(item.ItemSpec, evaluator.StartLocalItem) &&
                        evaluator.IsExcluded(item.ItemSpec, isFolder: false))
                    {
                        result.Add(item);
                    }
                }

                UntrackedFiles = result.ToArray();
            }

            return(true);
        }
예제 #57
0
        public void Autoassign(string id)
        {
            using (TfsTeamProjectCollection service = Service)
            {
                WorkItemStore workItemStore = service.GetService <WorkItemStore>();

                WorkItemCollection collection = GetWorkItemCollectionById(workItemStore, id);
                if (collection.Count > 0)
                {
                    WorkItem workItem = collection[0];
                    workItem.Open();

                    Autoassign(workItemStore, workItem);

                    if (!workItem.IsValid())
                    {
                        throw new ApplicationException("Errore salvataggio " + workItem.Title);
                    }

                    workItem.Save();
                }
            }
        }
예제 #58
0
        private void SearchByWorkItemId(string tfsServer, string teamProject, string[] ids)
        {
            TfsTeamProjectCollection server = this.GetServer(tfsServer);

            if (server != null)
            {
                this.lvResults.BeginUpdate();
                this.lvResults.Items.Clear();
                string str = string.Empty;
                for (int i = 0; i < ids.Length; i++)
                {
                    str = str + ids[i] + ",";
                }
                str = str.TrimEnd(new char[] { ',' });
                string        wiql    = string.Format("SELECT [System.Id], [System.WorkItemType], [System.Title], [System.State] FROM WorkItems WHERE [System.TeamProject] = '{0}'  AND  [System.Id] IN ({1}) ORDER BY [System.Id]", teamProject, str);
                WorkItemStore service = (WorkItemStore)server.GetService(typeof(WorkItemStore));
                foreach (WorkItem item in service.Query(wiql))
                {
                    this.lvResults.Items.Add(new ListViewItem(new string[] { item.Id.ToString(), item.Type.Name, item.Title, item.State }));
                }
                this.lvResults.EndUpdate();
            }
        }
        static void Main(string[] args)
        {
            var u = new Uri("http://server:8080/tfs/DefaultCollection");
            var c = new VssClientCredentials();
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(u, c);

            tpc.EnsureAuthenticated();
            ITestManagementService     itms  = tpc.GetService <ITestManagementService>();
            ITestManagementTeamProject ittp  = itms.GetTeamProject("LCScrum");
            ITestSuiteBase             suite = ittp.TestSuites.Find(352);
            ITestCaseCollection        testCaseCollection = suite.AllTestCases;

            foreach (var tc in testCaseCollection)
            {
                ITestCase testcase = ittp.TestCases.Find(tc.Id);

                foreach (ITestAction action in testcase.Actions)
                {
                    Console.WriteLine(String.Format("{0} - {1}", testcase.Id, action));
                }
            }
            Console.Read();
        }
예제 #60
0
        public static WorkItem CreateTfsWorkItem(
            TfsTeamProjectCollection collection,
            string projectName,
            string title,
            string area,
            string iteration,
            string description,
            string itemType,
            Dictionary <string, object> parameters)
        {
            WorkItem workItem = new WorkItem(collection.GetService <WorkItemStore>().Projects[projectName].WorkItemTypes[itemType]);

            workItem.Title       = title;
            workItem.Description = description;
            foreach (string key in parameters.Keys)
            {
                if (workItem.Fields.Contains(key))
                {
                    workItem.Fields[key].Value = (object)parameters[key];
                }
            }
            return(workItem);
        }