Exemplo n.º 1
0
 private void Connect()
 {
     if (Uri.IsWellFormedUriString(ConnectionUri, UriKind.Absolute))
     {
         _connection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ConnectionUri));
     }
 }
		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);
		}
Exemplo n.º 3
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;
        }
        protected RepositoryBase(String username, String password, string domain, string projectCollection, String url)
        {
            string fullUrl = url;
            bool collectionExists = !String.IsNullOrEmpty(projectCollection);

            if (String.IsNullOrEmpty(username))
                throw new ArgumentNullException(username, "Username is null or empty!");
            if (String.IsNullOrEmpty(password))
                throw new ArgumentNullException(password, "Password is null or empty!");
            if (collectionExists)
                fullUrl = url.LastIndexOf('/') == url.Length - 1
                              ? String.Concat(url, projectCollection)
                              : String.Concat(url, "/", projectCollection);
            if (String.IsNullOrEmpty(url))
                throw new ArgumentNullException(url, "TFSServerUrl is null or empty!");

            var credentials = new NetworkCredential(username, password, domain);

            _configuration = new TfsConfigurationServer(new Uri(url), credentials);
            _configuration.EnsureAuthenticated();

            if (collectionExists)
            {
                _tfs = new TfsTeamProjectCollection(new Uri(fullUrl), credentials);
                _tfs.EnsureAuthenticated();
            }
        }
Exemplo n.º 5
0
        public override void Connect(string serverUri, string remotePath, string localPath, int fromChangeset, string tfsUsername, string tfsPassword, string tfsDomain)
        {
            this._serverUri = new Uri(serverUri);
            this._remotePath = remotePath;
            this._localPath = localPath;
            this._startingChangeset = fromChangeset;

            try
            {
                NetworkCredential tfsCredential = new NetworkCredential(tfsUsername, tfsPassword, tfsDomain);
                //this._teamFoundationServer = new Microsoft.TeamFoundation.Client.TeamFoundationServer(this._serverUri, tfsCredential);
                this._tfsProjectCollection = new TfsTeamProjectCollection(this._serverUri, tfsCredential);
                this._versionControlServer = this._tfsProjectCollection.GetService<VersionControlServer>();
            }
            catch (Exception ex)
            {
                throw new Exception("Error connecting to TFS", ex);
            }

            //clear hooked eventhandlers
            BeginChangeSet = null;
            EndChangeSet = null;
            FileAdded = null;
            FileEdited = null;
            FileDeleted = null;
            FileUndeleted = null;
            FileBranched = null;
            FileRenamed = null;
            FolderAdded = null;
            FolderDeleted = null;
            FolderUndeleted = null;
            FolderBranched = null;
            FolderRenamed = null;
            ChangeSetsFound = null;
        }
        public BuildDefinitionsServiceModel(ITeamPilgrimServiceModelProvider teamPilgrimServiceModelProvider, ITeamPilgrimVsService teamPilgrimVsService, TfsTeamProjectCollection collection, Project project)
            : base(teamPilgrimServiceModelProvider, teamPilgrimVsService)
        {
            BuildDefinitions = new ObservableCollection<BuildDefinitionModel>();

            _collection = collection;
            _project = project;

            OpenBuildDefintionCommand = new RelayCommand<BuildDefinitionModel>(OpenBuildDefinition, CanOpenBuildDefinition);
            ViewBuildsCommand = new RelayCommand<BuildDefinitionModel>(ViewBuilds, CanViewBuilds);
            DeleteBuildDefinitionCommand = new RelayCommand<BuildDefinitionModel>(DeleteBuildDefinition, CanDeleteBuildDefinition);
            CloneBuildDefinitionCommand = new RelayCommand<BuildDefinitionModel>(CloneBuildDefinition, CanCloneBuildDefinition);
            QueueBuildCommand = new RelayCommand<BuildDefinitionModel>(QueueBuild, CanQueueBuild);
            OpenProcessFileLocationCommand = new RelayCommand<BuildDefinitionModel>(OpenProcessFileLocation, CanOpenProcessFileLocation);
            ManageBuildDefinitionSecurityCommand = new RelayCommand<BuildDefinitionModel>(ManageBuildDefinitionSecurity, CanManageBuildDefinitionSecurity);

            NewBuildDefinitionCommand = new RelayCommand(NewBuildDefinition, CanNewBuildDefinition);
            ManageBuildControllersCommand = new RelayCommand(ManageBuildControllers, CanManageBuildControllers);
            ManageBuildQualitiesCommand = new RelayCommand(ManageBuildQualities, CanManageBuildQualities);
            ManageBuildSecurityCommand = new RelayCommand(ManageBuildSecurity, CanManageBuildSecurity);

            _populateBackgroundWorker = new BackgroundWorker();
            _populateBackgroundWorker.DoWork += PopulateBackgroundWorkerOnDoWork;
            _populateBackgroundWorker.RunWorkerAsync();
        }
        public WorkItemQueryServiceModel(ITeamPilgrimServiceModelProvider teamPilgrimServiceModelProvider, ITeamPilgrimVsService teamPilgrimVsService, TfsTeamProjectCollection projectCollection, Project project)
            : base(teamPilgrimServiceModelProvider, teamPilgrimVsService)
        {
            _projectCollection = projectCollection;
            _project = project;

            QueryItems = new ObservableCollection<WorkItemQueryChildModel>();

            NewWorkItemCommand = new RelayCommand<string>(NewWorkItem, CanNewWorkItem);

            GoToWorkItemCommand = new RelayCommand(GoToWorkItem, CanGoToWorkItem);

            NewQueryDefinitionCommand = new RelayCommand<WorkItemQueryFolderModel>(NewQueryDefinition, CanNewQueryDefinition);
            NewQueryFolderCommand = new RelayCommand<WorkItemQueryFolderModel>(NewQueryFolder, CanNewQueryFolder);

            OpenQueryDefinitionCommand = new RelayCommand<WorkItemQueryDefinitionModel>(OpenQueryDefinition, CanOpenQueryDefinition);
            EditQueryDefinitionCommand = new RelayCommand<WorkItemQueryDefinitionModel>(EditQueryDefinition, CanEditQueryDefinition);

            DeleteQueryItemCommand = new RelayCommand<WorkItemQueryChildModel>(DeleteQueryDefinition, CanDeleteQueryDefinition);
            OpenSeurityDialogCommand = new RelayCommand<WorkItemQueryChildModel>(OpenSeurityDialog, CanOpenSeurityDialog);

            _populateBackgroundWorker = new BackgroundWorker();
            _populateBackgroundWorker.DoWork +=PopulateBackgroundWorkerOnDoWork;
            _populateBackgroundWorker.RunWorkerAsync();
        }
Exemplo n.º 8
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);
            }
        }
Exemplo n.º 9
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();
            }
        }
Exemplo n.º 10
0
        private TfsTeamProjectCollection ConnectToTfsCollection()
        {
            var tfsCredentials = GetTfsCredentials();

            foreach (var credentials in tfsCredentials)
            {
                try
                {
                    Logger.InfoFormat("Connecting to TFS {0} using {1} credentials", _config.TfsServerConfig.CollectionUri, credentials);
                    var tfsServer = new TfsTeamProjectCollection(new Uri(_config.TfsServerConfig.CollectionUri), credentials);
                    tfsServer.EnsureAuthenticated();

                    Logger.InfoFormat("Successfully connected to TFS");

                    return tfsServer;
                }
                catch (Exception ex)
                {
                    Logger.WarnFormat("TFS connection attempt failed.\n Exception: {0}", ex);
                }
            }

            Logger.ErrorFormat("All TFS connection attempts failed");
            throw new Exception("Cannot connect to TFS");
        }
Exemplo n.º 11
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;
        }
 /// <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);
 }
        /// <summary>
        /// Main Execution. UI handled in separate method, as this is a procedural utility.
        /// </summary>
        /// <param name="args">Not used</param>
        private static void Main(string[] args)
        {
            string serverUrl, destProjectName, plansJSONPath, logPath, csvPath;
            UIMethod(out serverUrl, out destProjectName, out plansJSONPath, out logPath, out csvPath);

            teamCollection = new TfsTeamProjectCollection(new Uri(serverUrl));
            workItemStore = new WorkItemStore(teamCollection);

            Trace.Listeners.Clear();
            TextWriterTraceListener twtl = new TextWriterTraceListener(logPath);
            twtl.Name = "TextLogger";
            twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;
            ConsoleTraceListener ctl = new ConsoleTraceListener(false);
            ctl.TraceOutputOptions = TraceOptions.DateTime;
            Trace.Listeners.Add(twtl);
            Trace.Listeners.Add(ctl);
            Trace.AutoFlush = true;

            // Get Project
            ITestManagementTeamProject newTeamProject = GetProject(serverUrl, destProjectName);

            // Get Test Plans in Project
            ITestPlanCollection newTestPlans = newTeamProject.TestPlans.Query("Select * From TestPlan");

            // Inform user which Collection/Project we'll be working in
            Trace.WriteLine("Executing alignment tasks in collection \"" + teamCollection.Name 
                + "\",\n\tand Destination Team Project \"" + newTeamProject.TeamProjectName + "\"...");

            // Get and print all test case information
            GetAllTestPlanInfo(newTestPlans, plansJSONPath, logPath, csvPath);
            Console.WriteLine("Alignment completed. Check log file in:\n " + logPath 
                + "\nfor missing areas or other errors. Press enter to close.");
            Console.ReadLine();
        }
        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 Close(string itemId, string comment)
        {
            using (var collection = new TfsTeamProjectCollection(locator.Location))
            {
                var workItemId = int.Parse(itemId);
                var workItemStore = new WorkItemStore(collection, WorkItemStoreFlags.BypassRules);
                var workItem = workItemStore.GetWorkItem(workItemId);
                var workItemDefinition = workItem.Store.Projects[workItem.Project.Name].WorkItemTypes[workItem.Type.Name];

                if (workItemDefinition == null)
                {
                    throw new ArgumentException("Could not obtain work item definition to close work item");
                }

                var definitionDocument = workItemDefinition.Export(false).InnerXml;
                var xDocument = XDocument.Parse(definitionDocument);
                var graphBuilder = new StateGraphBuilder();
                var stateGraph = graphBuilder.BuildStateGraph(xDocument);
                var currentStateNode = stateGraph.FindRelative(workItem.State);

                var graphWalker = new GraphWalker<string>(currentStateNode);
                var shortestWalk = graphWalker.WalkToNode("Closed");

                foreach (var step in shortestWalk.Path)
                {
                    workItem.State = step.Value;
                    workItem.Save();
                }

                workItem.Fields[CoreField.Description].Value = comment + "<br /><br/>" + workItem.Fields[CoreField.Description].Value;
                workItem.Save();
            }
        }
Exemplo n.º 16
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));
        }
		public FolderDiffInternalsGetter(dynamic folderDiffObject, TfsTeamProjectCollection collection, string outputDirectory):base("", "", "", outputDirectory) {
			_folderDiff = new FolderDiffWrapper(folderDiffObject, FolderDiffWrapper.LoadVersonControlControlsAssemblyFromApplication());
			_collection = collection;
			SourcePath = _folderDiff.Path1; 
			TargetPath = _folderDiff.Path2;

		}
Exemplo n.º 18
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));
            }
        }
Exemplo n.º 19
0
        private void EnsureTfs(bool allowCache = true)
        {
            if (_tfs != null)
                return;

            if (allowCache)
            {
                var tfsFromCache = HttpRuntime.Cache[CacheKey] as TfsTeamProjectCollection;
                if (tfsFromCache != null)
                {
                    _tfs = tfsFromCache;
                    return;
                }
            }

            lock (_CacheLock)
            {
                if (allowCache && _tfs != null)
                    return;

                _tfs = new TfsTeamProjectCollection(
                    new Uri(_principal.TfsUrl), _principal.GetCredentialsProvider());
                    //new Uri(_principal.TfsUrl), CredentialCache.DefaultCredentials, _principal.GetCredentialsProvider());

                HttpRuntime.Cache.Add(
                    CacheKey,
                    _tfs,
                    null,
                    Cache.NoAbsoluteExpiration,
                    new TimeSpan(1, 0, 0),
                    CacheItemPriority.Normal,
                    null);
            }
        }
Exemplo n.º 20
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;
        }
        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);
            }
        }
Exemplo n.º 22
0
 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;
     }
 }
        public SourceControlWrapper(string teamProjectCollectionUrl, string teamProjectName)
        {
            this.tpcollection = new TfsTeamProjectCollection(new Uri(teamProjectCollectionUrl));
            this.teamProjectName = teamProjectName;

            this.vcserver = this.tpcollection.GetService<VersionControlServer>();
        }
        public ProjectServiceModel(ITeamPilgrimServiceModelProvider teamPilgrimServiceModelProvider, ITeamPilgrimVsService teamPilgrimVsService, TeamPilgrimServiceModel teamPilgrimServiceModel, TfsTeamProjectCollection tfsTeamProjectCollection, Project project)
            : base(teamPilgrimServiceModelProvider, teamPilgrimVsService)
        {
            TeamPilgrimServiceModel = teamPilgrimServiceModel;
            TfsTeamProjectCollection = tfsTeamProjectCollection;
            Project = project;

            ShowProjectAlertsCommand = new RelayCommand(ShowProjectAlerts, CanShowProjectAlerts);
            OpenSourceControlCommand = new RelayCommand(OpenSourceControl, CanOpenSourceControl);
            OpenPortalSettingsCommand = new RelayCommand(OpenPortalSettings, CanOpenPortalSettings);
            OpenSourceControlSettingsCommand = new RelayCommand(OpenSourceControlSettings, CanOpenSourceControlSettings);
            OpenAreasAndIterationsCommand = new RelayCommand(OpenAreasAndIterations, CanOpenAreasAndIterations);
            ShowSecuritySettingsCommand = new RelayCommand(ShowSecuritySettings, CanShowSecuritySettings);
            OpenGroupMembershipCommand = new RelayCommand(OpenGroupMembership, CanOpenGroupMembership);

            BuildDefinitionsServiceModel = new BuildDefinitionsServiceModel(teamPilgrimServiceModelProvider, teamPilgrimVsService, tfsTeamProjectCollection, project);

            WorkItemQueryServiceModel = new WorkItemQueryServiceModel(teamPilgrimServiceModelProvider, teamPilgrimVsService, tfsTeamProjectCollection, project);

            ChildObjects = new ObservableCollection<BaseModel>
                {
                    WorkItemQueryServiceModel,
                    BuildDefinitionsServiceModel,
                    new SourceControlModel()
                };

            IsActive = teamPilgrimVsService.ActiveProjectContext.ProjectName == Project.Name;
        }
Exemplo n.º 25
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();
        }
Exemplo n.º 26
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.");
        }
Exemplo n.º 27
0
        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();
        }
Exemplo n.º 28
0
		public TfsFileHandler(TfsTeamProjectCollection tfsTeamProjectCollection, string filename)
		{
			_tfsTeamProjectCollection = tfsTeamProjectCollection;
			_filename = filename;

			FileExistsOnServer = GetFileExistsOnServer();
		}
        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);
            }
        }
Exemplo n.º 30
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;
        }
Exemplo n.º 31
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);
        }
Exemplo n.º 32
0
        public static List <Branch> GetBranches(TfsTeamProjectCollection tfs)
        {
            var rtnVal = new List <Branch>();

            using (tfs)
            {
                var vcs = tfs.GetService <VersionControlServer>();
                var bos = vcs.QueryRootBranchObjects(RecursionType.OneLevel);


                rtnVal.AddRange(bos.Select(branchObject => RecursivelyProcessBranch(branchObject, vcs)));
            }
            return(rtnVal);
        }
Exemplo n.º 33
0
        private static void GetProjectsForServerV2(Uri serverUrl)
        {
            //https://stackoverflow.com/questions/31031817/unable-to-load-dll-microsoft-witdatastore32-dll-teamfoundation-workitemtracki
            TfsTeamProjectCollection tpc           = new TfsTeamProjectCollection(serverUrl);
            WorkItemStore            workItemStore = tpc.GetService <WorkItemStore>();
            Project      teamProject  = workItemStore.Projects["ARM Basic Templates"];
            WorkItemType workItemType = teamProject.WorkItemTypes["Test Case"];

            var queryResults = workItemStore.Query(
                "Select [State], [Title] " +
                "From WorkItems " +
                "Where [Work Item Type] = 'Test Case' " +
                "Order By [State] Asc, [Changed Date] Desc");
        }
        internal static TfsTeamProjectCollectionWrapper GetInstance()
        {
            TfsTeamProjectCollection real = default(TfsTeamProjectCollection);

            RealInstanceFactory(ref real);
            var instance = (TfsTeamProjectCollectionWrapper)TfsTeamProjectCollectionWrapper.GetWrapper(real);

            InstanceFactory(ref instance);
            if (instance == null)
            {
                Assert.Inconclusive("Could not Create Test Instance");
            }
            return(instance);
        }
Exemplo n.º 35
0
        public TfsWrapper(TfsOptions options, WorkspaceInfo[] workspaces)
        {
            this.projectCollection = new TfsTeamProjectCollection(new Uri(options.ProjectCollectionUrl));
            this.projectWorkspaces = workspaces.Where(w => w.Name.StartsWith(options.ProjectCollectionName, StringComparison.OrdinalIgnoreCase)).ToList();

            if (this.projectWorkspaces.Any() == false)
            {
                throw new Exception("Unable to match to any project workspaces");
            }

            // set the dev workspace
            this.DevWorkspace      = this.SetSingleWorkspace("dev");
            this.PersonalWorkspace = this.SetPersonalWorkspace();
        }
Exemplo n.º 36
0
        /// <summary>
        /// This class gets the file stream from TFS
        /// during Adds, the files dont exist in TFS and this results in the returning of a null string
        /// </summary>
        public static System.IO.Stream get(string serverURL, string FullFileName)
        {
            Stream fileStream            = null;
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(serverURL));
            VersionControlServer     vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
            string fName = FullFileName;
            Item   it    = vcs.GetItems(fName).Items.FirstOrDefault();

            if (it != null)
            {
                fileStream = it.DownloadFile();
            }
            return(fileStream);
        }
Exemplo n.º 37
0
        private static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("\r\nEnter the URL for your TFS Server: (ie: http://tfs:8080/tfs)");
                var server = Console.ReadLine();

                Console.WriteLine("\r\nEnter the Name of your old computer and hit enter \r\n (leave blank to skip migrating tfs mappings and exit):");
                var oldComputerName = Console.ReadLine();
                if (!string.IsNullOrEmpty(oldComputerName) && !string.IsNullOrEmpty(server))
                {
                    var computername = Environment.MachineName;
                    Console.WriteLine("Old ComputerName: {0}", oldComputerName);
                    Console.WriteLine("New ComputerName: {0}", computername);

                    Console.WriteLine("Connecting to server...");
                    TfsTeamProjectCollection tfsCollection        = new TfsTeamProjectCollection(new Uri(server));
                    VersionControlServer     versionControlServer = tfsCollection.GetService <VersionControlServer>();
                    Console.WriteLine("Getting list of workspaces...");
                    Workspace[] workspaces = versionControlServer.QueryWorkspaces(null, versionControlServer.AuthorizedUser,
                                                                                  oldComputerName);
                    if (workspaces.Any())
                    {
                        foreach (var workspace in workspaces)
                        {
                            Console.WriteLine("Updating workspace: {0}", workspace.Name);
                            workspace.Update(
                                workspace.Name,               //Keep the name
                                workspace.OwnerName,          //Keep the owner
                                workspace.Comment,            //Keep the comment
                                computername,                 //New Computer name
                                workspace.Folders,            //Keep the mappings
                                workspace.PermissionsProfile, //Keep the permissions
                                false);                       //May not need to fix mappings ... if not, this will be false.
                        }
                    }
                    else
                    {
                        Console.WriteLine("No workspaces Found for that computer name.");
                    }
                }

                Console.WriteLine("All Finished! Press any key to continue.");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 38
0
        private static void Migrate(TfsTeamProjectCollection teamProjectCollection, GitWorkspace workspace)
        {
            teamProjectCollection.EnsureAuthenticated();

            var versionControlServer = teamProjectCollection.GetService <VersionControlServer>();
            var history = (from changeset in versionControlServer.QueryHistory(workspace.ServerHomePath, RecursionType.Full)
                           select versionControlServer.GetChangeset(changeset.ChangesetId))
                          .OrderBy(changeset => changeset.ChangesetId);

            using (var tfsWorkspace = new TfsWorkspace(teamProjectCollection.Uri, workspace.ServerHomePath))
            {
                ProcessChangesets(teamProjectCollection, workspace, tfsWorkspace, history);
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Get TeamProject from TFS
        /// </summary>
        /// <param name="teamProjecName">The teamProjectName object.</param>
        public void GetTeamProject(string teamProjecName)
        {
            ReadOnlyCollection <CatalogNode> collectionNodes
                = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            var  collectionNode = collectionNodes.Single();
            Guid collectionId   = new Guid(collectionNode.Resource.Properties["InstanceId"]);

            teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);

            ITestManagementService testManagementService = teamProjectCollection.GetService <ITestManagementService>();

            testProject = testManagementService.GetTeamProject(teamProjecName);
        }
        public TFSRepositoryService()
        {
            _pendingCheckIns = new Dictionary <DataAccess.IVersionControlled, string>();

            AppSettingsReader appReader = new AppSettingsReader();

            _workspacePath = appReader.GetValue("RepositoryPath", typeof(string)).ToString();

            WorkspaceInfo            sourceWorkspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(_workspacePath);
            TfsTeamProjectCollection projectCollecion    = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(sourceWorkspaceInfo.ServerUri);

            _versionControlServer = (VersionControlServer)projectCollecion.GetService(typeof(VersionControlServer));
            _workspace            = _versionControlServer.GetWorkspace(sourceWorkspaceInfo);
        }
Exemplo n.º 41
0
        /// <summary>
        /// main function
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            //string path1 = "ISH3\\ISH3_KBL\\KBL_RS2\\Test";
            string logPath = Directory.GetCurrentDirectory();
            string logfile = Path.Combine(logPath, "log-file.txt");

            if (File.Exists(logfile))
            {
                File.Delete(logfile);
            }
            ILog log = LogManager.GetLogger("testApp.Logging");

            try
            {
                Uri tfsUri = new Uri(ConfigurationManager.AppSettings["TfsUri"]);
                //Uri tfsUri = new Uri("https://tfs-alm.intel.com:8088/tfs/");
                TfsConfigurationServer configurationServer =
                    TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
                // Get the catalog of team project collections
                ReadOnlyCollection <CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);
                var collectionNode = collectionNodes.Single();
                // Use the InstanceId property to get the team project collection
                Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
                teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
                //Console.WriteLine("Collection: " + teamProjectCollection.Name);
                log.InfoFormat("Collecton: {0}", teamProjectCollection.Name);
                //log.Info("---------------------------------");
                log.Info("*********************************");
                workItemStore = teamProjectCollection.GetService <WorkItemStore>();
                //ICommonStructureService css = teamProjectCollection.GetService<ICommonStructureService>();
                //"ISH3\ISH3_KBL\KBL_RS2\Test"
                log.Info("path:" + args[0]);
                string   path   = args[0];
                string[] folder = path.Split('\\');
                for (int i = 0; i < folder.Length; i++)
                {
                    log.Info("folder[" + i + "]:" + folder[i]);
                }
                if (!CreateCycle(folder))
                {
                    return;
                }
                log.Info("Create test cycle:" + args[0] + " successfully!");
            }
            catch (Exception e)
            {
                log.Info(e.Message.ToString());
                return;
            }
        }
Exemplo n.º 42
0
        private Dictionary <string, IterationInfo> LoadIterations(TfsTeamProjectCollection tfs, Project project)
        {
            var css = tfs.GetService <ICommonStructureService4>();

            var structures     = css.ListStructures(project.Uri.ToString());
            var iterations     = structures.First(n => n.StructureType.Equals("ProjectLifecycle"));
            var iterationsTree = css.GetNodesXml(new[] { iterations.Uri }, true);

            var result = new Dictionary <string, IterationInfo>();

            BuildIterationTree(result, project.IterationRootNodes, css);

            return(result);
        }
Exemplo n.º 43
0
        public TeamManager(string teamProjectCollectionUrl, string teamProjectName, string softwareProjectName, string softwareProjectDescription)
        {
            _teamProjectCollectionUrl   = teamProjectCollectionUrl;
            _teamProjectName            = teamProjectName;
            _softwareProjectName        = softwareProjectName;
            _softwareProjectDescription = softwareProjectDescription;

            _tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(_teamProjectCollectionUrl));
            _tfsTeamProjectCollection.EnsureAuthenticated();
            _commonStructureService4          = _tfsTeamProjectCollection.GetService <ICommonStructureService4>();
            _tfsTeamService                   = _tfsTeamProjectCollection.GetService <TfsTeamService>();
            _teamSettingsConfigurationService = _tfsTeamProjectCollection.GetService <TeamSettingsConfigurationService>();
            _projectInfo = _commonStructureService4.GetProjectFromName(_teamProjectName);
        }
Exemplo n.º 44
0
        public static ITestManagementTeamProject GetProject(string serverUrl, string project)
        {
            try
            {
                TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(serverUrl));
                ITestManagementService   tms = tfs.GetService <ITestManagementService>();

                return(tms.GetTeamProject(project));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public static SortedDictionary <string, string> GetTestPlans(string collectionName, string projectName)
        {
            tfs  = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(XML.GetCollectionURL(collectionName)));
            tms  = tfs.GetService <ITestManagementService>();
            proj = tms.GetTeamProject(projectName);
            iTPC = proj.TestPlans.Query("Select * From TestPlan");
            SortedDictionary <string, string> iTP = new SortedDictionary <string, string>();

            foreach (ITestPlan itp in iTPC)
            {
                iTP.Add(itp.Id.ToString(), itp.Name);
            }
            return(iTP);
        }
        private void Connect()
        {
            if (_Collection == null)
            {
                _Telemetry.TrackEvent("TeamProjectContext.Connect",
                                      new Dictionary <string, string> {
                    { "Name", Config.Project },
                    { "Target Project", Config.Project },
                    { "Target Collection", Config.Collection.ToString() },
                    { "ReflectedWorkItemID Field Name", Config.ReflectedWorkItemIDFieldName }
                });
                Stopwatch connectionTimer = Stopwatch.StartNew();
                DateTime  start           = DateTime.Now;
                Trace.WriteLine("Creating TfsTeamProjectCollection Object ");

                if (_credentials == null)
                {
                    _Collection = new TfsTeamProjectCollection(Config.Collection);
                }
                else
                {
                    _Collection = new TfsTeamProjectCollection(Config.Collection, _credentials);
                }

                try
                {
                    Trace.WriteLine(string.Format("Connected to {0} ", _Collection.Uri.ToString()));
                    Trace.WriteLine(string.Format("validating security for {0} ", _Collection.AuthorizedIdentity.ToString()));
                    _Collection.EnsureAuthenticated();
                    connectionTimer.Stop();
                    _Telemetry.TrackDependency("TeamService", "EnsureAuthenticated", start, connectionTimer.Elapsed, true);
                    Trace.TraceInformation(string.Format(" Access granted "));
                }
                catch (TeamFoundationServiceUnavailableException ex)
                {
                    _Telemetry.TrackDependency("TeamService", "EnsureAuthenticated", start, connectionTimer.Elapsed, false);
                    _Telemetry.TrackException(ex,
                                              new Dictionary <string, string> {
                        { "CollectionUrl", Config.Collection.ToString() },
                        { "TeamProjectName", Config.Project }
                    },
                                              new Dictionary <string, double> {
                        { "ConnectionTimer", connectionTimer.ElapsedMilliseconds }
                    });
                    Trace.TraceWarning($"  [EXCEPTION] {ex}");
                    throw;
                }
            }
            ConnectStore();
        }
        public void GetParentWorkitemTest()
        {
            var           tfs           = new TfsTeamProjectCollection(new Uri("http://localhost:8080/tfs/defaultcollection"));
            WorkItemStore workItemStore = tfs.GetService <WorkItemStore>();
            var           workItem      = workItemStore.GetWorkItem(85);

            // TODO: private accessors using "Test References | .accessor" are deprecated
            // use reflection to call Invoke directly
            //GetParentWorkItem_Accessor target = new GetParentWorkItem_Accessor();
            //WorkItem expected = null; // TODO: Initialize to an appropriate value
            //WorkItem actual;
            //actual = target.GetParentWorkitem(workItem);
            //Assert.AreEqual(expected, actual);
        }
Exemplo n.º 48
0
        static void Main(string[] args)
        {
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
                new Uri("http://tfsserver:8080/tfs/TestCollection"));
            WorkItemStore workItemStore = (WorkItemStore)tpc.GetService(typeof(WorkItemStore));

            string wiql         = "Select * From WorkItems Where [Work Item Type] = 'Test Case' and [System.TeamProject] = 'adam asf_test' ORDER BY [System.Tags]";
            var    queryResults = workItemStore.Query(wiql);

            Console.WriteLine(queryResults.Count);

            Console.WriteLine("press the <any> key");
            Console.ReadKey();
        }
Exemplo n.º 49
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());
     }
 }
        static void Main(string[] args)
        {
            Uri url = new Uri("https://tfsuri");
            TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(url);
            VersionControlServer     vcs  = ttpc.GetService <VersionControlServer>();
            IEnumerable <Changeset>  cses = vcs.QueryHistory("Path here could be local path or server path", RecursionType.Full);

            foreach (Changeset cs in cses)
            {
                Console.WriteLine(cs.ChangesetId);
                Console.WriteLine(cs.Comment);
            }
            Console.ReadLine();
        }
Exemplo n.º 51
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="TfsWrapper"/> class
        ///     using the specified URL.
        /// </summary>
        public TfsWrapper(TfsServerInfo serverInfo)
        {
            #region Argument Check

            if (serverInfo == null)
            {
                throw new ArgumentNullException("serverInfo");
            }

            #endregion

            _teamProjectCollection    = new TfsTeamProjectCollection(serverInfo.Uri);
            _versionControlServerLazy = new Lazy <VersionControlServer>(GetService <VersionControlServer>);
        }
        private void cmbUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            string serverName = @"https://tfsnbs.gmd.lab/tfs/nbs";

            TfsTeamProjectCollection      tfs        = new TfsTeamProjectCollection(new Uri(serverName));
            VersionControlServer          vcs        = tfs.GetService <VersionControlServer>();
            KeyValuePair <string, string> selectPair = (KeyValuePair <string, string>)cmbUser.SelectedItem;

            if (cmbUser.SelectedIndex > -1)
            {
                userName = selectPair.Value;
                this.GetShelveSetDetails(vcs);
            }
        }
Exemplo n.º 53
0
 private void EnsureCollection()
 {
     if (_collection == null)
     {
         _Telemetry.TrackEvent("TeamProjectContext.EnsureCollection",
                               new Dictionary <string, string> {
             { "Name", TfsConfig.Project },
             { "Target Project", TfsConfig.Project },
             { "Target Collection", TfsConfig.Collection.ToString() },
             { "ReflectedWorkItemID Field Name", TfsConfig.ReflectedWorkItemIDFieldName }
         }, null);
         _collection = GetDependantTfsCollection(_credentials);
     }
 }
Exemplo n.º 54
0
        /// <summary>
        /// http://stackoverflow.com/questions/10557814/how-to-get-a-specific-build-with-the-tfs-api
        /// </summary>
        /// <param name="TeamProject"></param>
        /// <param name="BuildDefinition"></param>
        /// <param name="BuildID"></param>
        /// <returns></returns>
        public string GetBuildStatus(TfsTeamProjectCollection tfs, string TeamProject, string BuildDefinition, int BuildID)
        {
            IBuildServer            buildServer = (IBuildServer)tfs.GetService(typeof(IBuildServer));
            string                  status      = string.Empty;
            IQueuedBuildSpec        qbSpec      = buildServer.CreateBuildQueueSpec(TeamProject, BuildDefinition);
            IQueuedBuildQueryResult qbResults   = buildServer.QueryQueuedBuilds(qbSpec);

            if (qbResults.QueuedBuilds.Length > 0)
            {
                IQueuedBuild build = qbResults.QueuedBuilds.Where(x => x.Id == BuildID).FirstOrDefault();
                status = build.Status.ToString();
            }
            return(status);
        }
Exemplo n.º 55
0
        public void Close()
        {
            if (m_Connection != null)
            {
                m_Connection.Close();
                m_Connection = null;
            }

            if (projectCollection != null)
            {
                projectCollection.Dispose();
                projectCollection = null;
            }
        }
Exemplo n.º 56
0
        static void Main(string[] args)
        {
            string rootLogFolder = ConfigurationManager.AppSettings["RootLogFolder"].ToString();

            try
            {
                Console.WriteLine("*** Scanning all Team Projects in all Team Project Collections ***");

                string tfsRootUrl = ConfigurationManager.AppSettings["TfsRootUrl"].ToString();
                Console.WriteLine("Tfs Root Url: " + tfsRootUrl);

                Uri tfsConfigurationServerUri = new Uri(tfsRootUrl);
                TfsConfigurationServer        configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsConfigurationServerUri);
                ITeamProjectCollectionService tpcService          = configurationServer.GetService <ITeamProjectCollectionService>();

                string configDbConnectionString = ConfigurationManager.AppSettings["ConfigDBConnectionString"].ToString();
                Console.WriteLine("Config DB Connectionstring: " + configDbConnectionString);

                using (IVssDeploymentServiceHost deploymentServiceHost = CreateDeploymentServiceHost(configDbConnectionString))
                {
                    foreach (TeamProjectCollection tpc in tpcService.GetCollections().OrderBy(tpc => tpc.Name))
                    {
                        string nameOfLogFile           = "UpgradeTeamProjectFeatures-" + tpc.Name + ".txt";
                        string fullPathOfLogFile       = System.IO.Path.Combine(rootLogFolder, nameOfLogFile);
                        System.IO.StreamWriter logFile = new System.IO.StreamWriter(fullPathOfLogFile);

                        logFile.WriteLine(String.Format("*** scanning Team Projects in TPC {0} ***", tpc.Name));
                        logFile.WriteLine();

                        string tpcUrl = tfsRootUrl + "/" + tpc.Name;
                        TfsTeamProjectCollection tfsCollection = new TfsTeamProjectCollection(new Uri(tpcUrl));

                        WorkItemStore witStore = tfsCollection.GetService <WorkItemStore>();
                        foreach (Microsoft.TeamFoundation.WorkItemTracking.Client.Project project in witStore.Projects)
                        {
                            Console.WriteLine("Team Project " + project.Name);
                            logFile.WriteLine(">> Team Project " + project.Name);
                            RunFeatureEnablement(deploymentServiceHost, project, tfsCollection.InstanceId, logFile);
                            logFile.WriteLine();
                        }

                        logFile.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// Executes the logic for this workflow activity.
        /// </summary>
        /// <param name="context">The workflow context.</param>
        /// <returns>The <see cref="Microsoft.TeamFoundation.Build.Client.IBuildServer"/>
        /// that is specified.</returns>
        protected override IBuildServer Execute(CodeActivityContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            string serverUrl = context.GetValue(this.TeamFoundationServerUrl);

            using (TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl)))
            {
                return((IBuildServer)tfs.GetService <IBuildServer>());
            }
        }
        /// <summary>
        /// Returns a work item by ID
        /// </summary>
        /// <param name="projectCollection">Tfs Project Collection that contains the work item.</param>
        /// <param name="workItemId">Id for the work item</param>
        /// <returns>The found work item.</returns>
        /// <exception cref="ArgumentException">Occurs when the work item id is not valid.</exception>
        public static WorkItem GetWorkItemById(TfsTeamProjectCollection projectCollection, int workItemId)
        {
            ArgumentValidation.ValidateObjectIsNotNull(projectCollection, "projectCollection");
            if (workItemId <= 0)
            {
                // This is not a valid work item.
                throw new ArgumentException("Work Item Id is not valid", "workItemId");
            }

            WorkItemStore store    = projectCollection.GetService <WorkItemStore>();
            var           workItem = store.GetWorkItem(workItemId);

            return(workItem);
        }
Exemplo n.º 59
0
        private static string GetTeamProjectCollectionName(TfsTeamProjectCollection teamProjectCollection)
        {
            long   startTicks = XlHlp.DisplayInWatchWindow("Begin");
            string colName    = teamProjectCollection.Name;

            // TFS in cloud send names back with back slashes
            colName = colName.Replace('\\', '/');
            // strip all all but TeamProjectCollection name part
            colName = colName.Substring(colName.LastIndexOf('/') + 1);

            XlHlp.DisplayInWatchWindow("End", startTicks);

            return(colName);
        }
Exemplo n.º 60
0
 public CapacitySearcher(TfsTeamProjectCollection connection,
                         WorkItemStore itemStore = null,
                         IIdentityManagementService2 managementService = null,
                         TfsTeamService teamService = null,
                         WorkHttpClient workClient  = null,
                         ICommonStructureService4 structureService = null)
 {
     _connection        = connection;
     _itemStore         = itemStore;
     _managementService = managementService;
     _teamService       = teamService;
     _workClient        = workClient;
     _structureService  = structureService;
 }