예제 #1
0
        private static void ListProjects()
        {
            // URI of the team project collection
            string _myUri = @"https://bupa-international.visualstudio.com";

            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(new Uri(_myUri));

            CatalogNode catalogNode = configurationServer.CatalogNode;

            ReadOnlyCollection <CatalogNode> tpcNodes = catalogNode.QueryChildren(
                new Guid[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            // tpc = Team Project Collection
            foreach (CatalogNode tpcNode in tpcNodes)
            {
                Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(tpcId);

                // Get catalog of tp = 'Team Projects' for the tpc = 'Team Project Collection'
                var tpNodes = tpcNode.QueryChildren(
                    new Guid[] { CatalogResourceTypes.TeamProject },
                    false, CatalogQueryOptions.None);

                foreach (var p in tpNodes)
                {
                    Debug.Write(Environment.NewLine + " Team Project : " + p.Resource.DisplayName + " - " + p.Resource.Description + Environment.NewLine);
                }
            }
        }
예제 #2
0
        public void createCatalogOfProjects(CatalogNode collectionNode)
        {
            ReadOnlyCollection <CatalogNode> projectNodes = collectionNode.QueryChildren(
                new[] { CatalogResourceTypes.TeamProject },
                false, CatalogQueryOptions.None);

            _projectNodes = projectNodes;
        }
예제 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// unconsidered CatalogResourceTypes : GenericLink, ProjectServerMapping, ProjectServerRegistration, ResourceFolder, DataCollector, ProcessGuidanceSite, ProjectPortal
        /// </remarks>
        public ActionResult InfrastructureOverview()
        {
            ICatalogService serverCatalogService  = configurationServer.GetService <ICatalogService>();
            CatalogNode     organizationalCatalog = serverCatalogService.QueryRootNode(CatalogTree.Infrastructure);
            ReadOnlyCollection <CatalogNode> analysisDatabaseNode             = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.AnalysisDatabase }, true, CatalogQueryOptions.None);
            ReadOnlyCollection <CatalogNode> applicationDatabaseNode          = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.ApplicationDatabase }, true, CatalogQueryOptions.None);
            ReadOnlyCollection <CatalogNode> machineNode                      = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.Machine }, true, CatalogQueryOptions.ExpandDependencies);
            ReadOnlyCollection <CatalogNode> projectCollectionDatabaseNode    = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.ProjectCollectionDatabase }, true, CatalogQueryOptions.None);
            ReadOnlyCollection <CatalogNode> sqlAnalaysisInstanceNode         = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.SqlAnalysisInstance }, true, CatalogQueryOptions.None);
            ReadOnlyCollection <CatalogNode> sqlDatabaseInstanceNode          = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.SqlDatabaseInstance }, true, CatalogQueryOptions.None);
            ReadOnlyCollection <CatalogNode> sqlReportingNode                 = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.SqlReportingInstance }, true, CatalogQueryOptions.None);
            ReadOnlyCollection <CatalogNode> teamFoundationWebApplicationNode = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.TeamFoundationWebApplication }, true, CatalogQueryOptions.None);
            ReadOnlyCollection <CatalogNode> warehouseDatabaseNode            = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.WarehouseDatabase }, true, CatalogQueryOptions.None);

            return(PartialView());
        }
예제 #4
0
 public IEnumerable <CollectionModel> GetCollections()
 {
     using (var server = GetServer())
     {
         CatalogNode configurationServerNode           = server.CatalogNode;
         IReadOnlyCollection <CatalogNode> collections = configurationServerNode.QueryChildren(
             new[] { CatalogResourceTypes.ProjectCollection },
             false, CatalogQueryOptions.None);
         return(Map(collections));
     }
 }
예제 #5
0
        public static string GetLastSuccededDropLocation(string projName, string buildDefinitionName)
        {
            projName = GetProjectName(projName);
            var cred = new NetworkCredential("SERVICE_ACCOUNT_NAME", "SERVICE_ACCOUNT_PASSWORD", "SERVICE_ACCOUNT_DOMAIN");

            var configurationServerUri = new Uri("TFS_URL_TILL_COLLECTION");
            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);

            CatalogNode configurationServerNode = configurationServer.CatalogNode;

            // Query the children of the configuration server node for all of the team project collection nodes
            ReadOnlyCollection <CatalogNode> tpcNodes = configurationServerNode.QueryChildren(
                new Guid[] { CatalogResourceTypes.ProjectCollection },
                false,
                CatalogQueryOptions.None);

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                ServiceDefinition tpcServiceDefinition = tpcNode.Resource.ServiceReferences["Location"];

                ILocationService configLocationService = configurationServer.GetService <ILocationService>();
                Uri tpcUri = new Uri(configLocationService.LocationForCurrentConnection(tpcServiceDefinition));

                // Actually connect to the team project collection
                TfsTeamProjectCollection   tpc  = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tpcUri);
                ITestManagementService     tms  = tpc.GetService <ITestManagementService>();
                ITestManagementTeamProject proj = tms.GetTeamProject(projName);
                IBuildServer tfsBuildServer     = tpc.GetService <IBuildServer>();
                // Reading from XML
                try
                {
                    IBuildServer buildServer = (IBuildServer)tpc.GetService(typeof(IBuildServer));
                    //Specify query
                    IBuildDetailSpec spec = buildServer.CreateBuildDetailSpec(projName.Trim(), buildDefinitionName.Trim());
                    spec.InformationTypes = null;                                // for speed improvement
                    spec.QueryOrder       = BuildQueryOrder.FinishTimeAscending; //get the latest build only
                    spec.QueryOptions     = QueryOptions.All;

                    IBuildDetail bDetail = buildServer.QueryBuilds(spec).Builds.OrderBy(x => x.CompilationStatus == BuildPhaseStatus.Succeeded).Last();
                    LatestTestBuild = bDetail.DropLocation;
                    LoggerUtil.LogMessageToFile("The ip resolve");
                    IPAddress ip   = null;
                    string    arr2 = LatestTestBuild.Split('\\')[2];
                    Network.GetResolvedConnecionIPAddress(LatestTestBuild.Split('\\')[2], out ip);
                    string temp = string.Join(@"\", LatestTestBuild.Split('\\').Select(s => s.Replace(arr2, ip.ToString())).ToArray());
                    LatestTestBuild = temp;
                    LoggerUtil.LogMessageToFile(LatestTestBuild);
                    break;
                }
                catch { }
            }
            return(LatestTestBuild);
        }
        /// <summary>
        /// Get the test environment definitions contained in the child nodes of the Catalog
        /// </summary>
        /// <param name="organizationalCatalog">The catalog to browse</param>
        /// <returns>a collection of test environment definitions</returns>
        /// <remarks>
        /// test environment definitions are collection-level data
        /// </remarks>
        public static ICollection <TestEnvironmentDefinition> GetTestEnvironments(CatalogNode organizationalCatalog)
        {
            ReadOnlyCollection <CatalogNode>        testEnvironmentNode = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.TestEnvironment }, false, CatalogQueryOptions.None);
            ICollection <TestEnvironmentDefinition> collection          = new List <TestEnvironmentDefinition>();

            foreach (CatalogNode item in testEnvironmentNode)
            {
                TestEnvironmentDefinition definition = new TestEnvironmentDefinition();
                definition.Name = item.Resource.DisplayName;
                collection.Add(definition);
            }
            return(collection);
        }
        /// <summary>
        /// Get the sharepoint web application definitions contained in the child nodes of the catalog
        /// </summary>
        /// <param name="organizationalCatalog">the catalog to browse</param>
        /// <returns>the sharepoint web application definitions</returns>
        /// <remarks>
        /// sharepoint web application definitions are server-level data
        /// </remarks>
        public static ICollection <SharePointWebApplicationDefinition> GetSharePointWebApplications(CatalogNode organizationalCatalog)
        {
            ReadOnlyCollection <CatalogNode> sharePointWebApplicationNode = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.SharePointWebApplication }, false, CatalogQueryOptions.None);
            ICollection <SharePointWebApplicationDefinition> collection   = new List <SharePointWebApplicationDefinition>();

            foreach (CatalogNode item in sharePointWebApplicationNode)
            {
                SharePointWebApplicationDefinition definition = new SharePointWebApplicationDefinition();
                definition.Name = item.Resource.DisplayName;
                collection.Add(definition);
            }
            return(collection);
        }
        /// <summary>
        /// Get the reporting server definitions contained in the child nodes of the catalog
        /// </summary>
        /// <param name="organizationalCatalog">the catalog to browse</param>
        /// <returns>the reporting server defintions</returns>
        /// <remarks>
        /// the reporting server definition are server-level data
        /// </remarks>
        public static ICollection <ReportingServerDefinition> GetReportingServers(CatalogNode organizationalCatalog)
        {
            ReadOnlyCollection <CatalogNode>        reportingServerNode = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.ReportingServer }, false, CatalogQueryOptions.None);
            ICollection <ReportingServerDefinition> collection          = new List <ReportingServerDefinition>();

            foreach (CatalogNode item in reportingServerNode)
            {
                ReportingServerDefinition definition = new ReportingServerDefinition();
                definition.Name = item.Resource.DisplayName;
                collection.Add(definition);
            }
            return(collection);
        }
        /// <summary>
        /// Get the team project definitions contained in the child nodes of the catalog
        /// </summary>
        /// <param name="organizationalCatalog">
        /// the catalog to browse
        /// </param>
        /// <returns>
        /// the team project definitions
        /// </returns>
        /// <remarks>
        /// team project definitions are collection-level data
        /// </remarks>
        public static ICollection <ProjectDefinition> GetTeamProjects(CatalogNode organizationalCatalog, bool recurse)
        {
            ReadOnlyCollection <CatalogNode> teamProjectNode = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, recurse, CatalogQueryOptions.None);
            ICollection <ProjectDefinition>  collection      = new List <ProjectDefinition>();

            foreach (CatalogNode item in teamProjectNode)
            {
                ProjectDefinition definition = new ProjectDefinition();
                definition.Name  = item.Resource.DisplayName;
                definition.Id    = new Guid(item.Resource.Properties["ProjectId"]);
                definition.State = item.Resource.Properties["ProjectState"];
                definition.Uri   = item.Resource.Properties["ProjectUri"];
                collection.Add(definition);
            }
            return(collection);
        }
        /// <summary>
        /// Get the project portal definitions contained in the child nodes of the catalog
        /// </summary>
        /// <param name="organizationalCatalog">the catalog to browse</param>
        /// <returns>the project portal definitions</returns>
        /// <remarks>
        /// the project portal definitions are collection-level data
        /// </remarks>
        public static ICollection <ProjectPortalDefinition> GetProjectPortals(CatalogNode organizationalCatalog)
        {
            ReadOnlyCollection <CatalogNode>      projectPortalNode = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.ProjectPortal }, false, CatalogQueryOptions.None);
            ICollection <ProjectPortalDefinition> collection        = new List <ProjectPortalDefinition>();

            foreach (CatalogNode item in projectPortalNode)
            {
                ProjectPortalDefinition definition = new ProjectPortalDefinition();
                definition.Name = item.Resource.DisplayName;
                if (item.Resource.Properties.ContainsKey("RelativePath"))
                {
                    definition.RelativePath = item.Resource.Properties["RelativePath"];
                }
                collection.Add(definition);
            }
            return(collection);
        }
        public static ICollection <DataCollectorDefinition> GetDataCollectors(CatalogNode organizationalCatalog)
        {
            ReadOnlyCollection <CatalogNode>      dataCollectorNode       = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.DataCollector }, false, CatalogQueryOptions.None);
            ICollection <DataCollectorDefinition> dataCollectorCollection = new List <DataCollectorDefinition>();

            foreach (CatalogNode item in dataCollectorNode)
            {
                DataCollectorDefinition dataCollectorDefinition = new DataCollectorDefinition();
                dataCollectorDefinition.Name = item.Resource.DisplayName;
                if (item.Resource.Properties.ContainsKey("__Reserved_DisplayName"))
                {
                    dataCollectorDefinition.Name += (" - " + item.Resource.Properties["__Reserved_DisplayName"]);
                }
                dataCollectorCollection.Add(dataCollectorDefinition);
            }
            return(dataCollectorCollection);
        }
        /// <summary>
        /// Get project collection definitions contained in the child nodes of the catalog
        /// </summary>
        /// <param name="organizationalCatalog">the catalog to browse</param>
        /// <returns>the project collection definitions</returns>
        /// <remarks>
        /// the project collection definitions are server-level data
        /// </remarks>
        public static ICollection <ProjectCollectionDefinition> GetProjectCollections(CatalogNode organizationalCatalog)
        {
            ReadOnlyCollection <CatalogNode>          projectCollectionNode = organizationalCatalog.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);
            ICollection <ProjectCollectionDefinition> collection            = new List <ProjectCollectionDefinition>();

            foreach (CatalogNode item in projectCollectionNode)
            {
                ProjectCollectionDefinition definition = new ProjectCollectionDefinition();
                definition.Name         = item.Resource.DisplayName;
                definition.ProjectCount = item.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None).Count;
                if (item.Resource.Properties.ContainsKey("InstanceId"))
                {
                    definition.InstanceId = new Guid(item.Resource.Properties["InstanceId"]);
                }
                collection.Add(definition);
            }
            return(collection);
        }
예제 #13
0
        public IEnumerable <String> GetProjects(string collection)
        {
            Guard.True(IsConnected);
            Guard.NotNullOrWhiteSpace(collection);

            CatalogNode collectionNode = GetCollection(collection);

            // Get a catalog of team projects for the collection
            ReadOnlyCollection <CatalogNode> projectNodes = collectionNode.QueryChildren(
                new[] { CatalogResourceTypes.TeamProject },
                false, CatalogQueryOptions.None);

            // List the team projects in the collection
            var list = projectNodes.Select(projectNode => projectNode.Resource.DisplayName)
                       .OrderBy(x => x);

            return(list.AsReadOnly());
        }
예제 #14
0
        public List <Project> obterProjetos(Collection collection)
        {
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(this.Url + "/" + collection.Name));

            CatalogNode catalogNode = tfs.CatalogNode;
            IReadOnlyCollection <CatalogNode> tpNodes = catalogNode.QueryChildren(
                new Guid[] { CatalogResourceTypes.TeamProject },
                false,
                CatalogQueryOptions.None);

            List <Project> projetos = new List <Project>();

            foreach (CatalogNode cn in tpNodes)
            {
                projetos.Add(new Project(collection, cn.Resource.DisplayName));
            }

            return(projetos);
        }
예제 #15
0
        void DoStuffForSpecificCatalog(TfsConfigurationServer configurationServer,CatalogNode collectionNode)
        {
            // Use the InstanceId property to get the team project collection
            Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
            TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
            GetChangesets(teamProjectCollection);
            // Print the name of the team project collection
            Console.WriteLine("Collection: " + teamProjectCollection.Name);

            // Get a catalog of team projects for the collection
            ReadOnlyCollection<CatalogNode> projectNodes = collectionNode.QueryChildren(
                new[] { CatalogResourceTypes.TeamProject },
                false, CatalogQueryOptions.None);

            // List the team projects in the collection
            foreach (CatalogNode projectNode in projectNodes)
            {
                Console.WriteLine(" Team Project: " + projectNode.Resource.DisplayName);
            }
        }
예제 #16
0
        private IEnumerable <BuildInfoDto> GetBuildInfoDtosPerTeamProject(CatalogNode teamProjectCollectionNode,
                                                                          TfsConfigurationServer tfsServer, DateTime filterDate)
        {
            var buildInfoDtos = new List <BuildInfoDto>();

            try
            {
                // Use the InstanceId property to get the team project collection
                var collectionId          = new Guid(teamProjectCollectionNode.Resource.Properties["InstanceId"]);
                var teamProjectCollection = tfsServer.GetTeamProjectCollection(collectionId);

                var buildServer = (IBuildServer)teamProjectCollection.GetService(typeof(IBuildServer));
                var testService = teamProjectCollection.GetService <ITestManagementService>();

                // Get a catalog of team projects for the collection
                var teamProjectNodes = teamProjectCollectionNode.QueryChildren(
                    new[] { CatalogResourceTypes.TeamProject },
                    false, CatalogQueryOptions.None);

                // List the team projects in the collection
                Parallel.ForEach(teamProjectNodes, teamProjectNode =>
                {
                    var buildDefinitionList =
                        new List <IBuildDefinition>(buildServer.QueryBuildDefinitions(teamProjectNode.Resource.DisplayName));
                    lock (buildInfoDtos)
                    {
                        buildInfoDtos.AddRange(GetBuildInfoDtosPerBuildDefinition(buildDefinitionList, buildServer,
                                                                                  teamProjectNode,
                                                                                  teamProjectCollection, testService, filterDate));
                    }
                });
            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }


            return(buildInfoDtos);
        }
예제 #17
0
        public List <Collection> ListCollections()
        {
            var result = new List <Collection>();

            CatalogNode catalogNode = this._tfsConfigurationServer.CatalogNode;

            foreach (CatalogNode item in catalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None))
            {
                var tpcId = new Guid(item.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection tpc = this._tfsConfigurationServer.GetTeamProjectCollection(tpcId);

                result.Add(new Collection {
                    TeamProjectCollectionID = tpcId,
                    IsDefault             = item.IsDefault,
                    CollectionName        = tpc.CatalogNode.Resource.DisplayName,
                    Url                   = tpc.Uri,
                    CollectionDescription = tpc.CatalogNode.Resource.Description
                });
            }

            return(result);
        }
예제 #18
0
        private IDictionary <TfsTeamProjectCollection, ReadOnlyCollection <CatalogNode> > GetTeamProjectCollectionsWithTeamProjectCatalogNodes(TfsConfigurationServer tfs)
        {
            CatalogNode catalogNode = tfs.CatalogNode;

            // Note: this requires a dependency to Microsoft.TeamFoundation.Common. Really needed?
            ReadOnlyCollection <CatalogNode> tpcNodes =
                catalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            var tpcDictionary = new Dictionary <TfsTeamProjectCollection, ReadOnlyCollection <CatalogNode> >();

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                Guid instanceId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection tpc = tfs.GetTeamProjectCollection(instanceId);

                // Get catalog of tp = 'Team Projects' for the tpc = 'Team Project Collection'
                ReadOnlyCollection <CatalogNode> tpNodes =
                    tpcNode.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None);

                tpcDictionary.Add(tpc, new ReadOnlyCollection <CatalogNode>(tpNodes));
            }

            return(tpcDictionary);
        }
예제 #19
0
        public string GetFileContent(GeminiContext gemini, int issueid, string filename, string fullfilename, string workspace, string changesetid, string fileid, string repositoryUrl, bool getPreviousRevision = false)
        {
            ConnectByImplementingCredentialsProvider connect = new ConnectByImplementingCredentialsProvider();

            ICredentials iCred = new NetworkCredential(Username, Password);

            connect.setLoginDetails(Username, Password, workspace);

            connect.GetCredentials(new Uri(Uri), iCred);

            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(Uri));

            configurationServer.Credentials = iCred;


            if (TFS2012.IsBasicAuth)
            {
                configurationServer.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
            }
            else
            {
                configurationServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential(iCred));
            }

            configurationServer.EnsureAuthenticated();

            CatalogNode catalogNode = configurationServer.CatalogNode;

            ReadOnlyCollection <CatalogNode> tpcNodes = catalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);

                TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(tpcId);

                if (TFS2012.IsBasicAuth)
                {
                    tpc.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                }

                VersionControlServer versionControl = (VersionControlServer)tpc.GetService(typeof(VersionControlServer));

                Item file = null;

                try
                {
                    //IF file was just added in tfs
                    if (fileid.ToInt() == 0)
                    {
                        Item tmpFile = null;
                        //Need to catch error if file was deleted, we'll get an error and call the file with parameters as below.
                        //This would only happen to newly added file, which will not have a itemid as we wouldn't know what it is on first commit of a file
                        try
                        {
                            tmpFile = versionControl.GetItem(string.Concat(fullfilename, "/", filename));
                        }
                        catch (VersionControlException ex)
                        {
                            tmpFile = versionControl.GetItem(fullfilename + "/" + filename, VersionSpec.Latest, DeletedState.Deleted);
                        }

                        if (tmpFile != null)
                        {
                            fileid = tmpFile.ItemId.ToString();
                        }
                    }

                    if (fileid.ToInt() > 0)
                    {
                        if (getPreviousRevision)
                        {
                            if (changesetid.ToInt() > 1)
                            {
                                file = versionControl.GetItem(fileid.ToInt(), changesetid.ToInt() - 1, true);
                            }
                        }
                        else
                        {
                            file = versionControl.GetItem(fileid.ToInt(), changesetid.ToInt());
                        }

                        if (file != null)
                        {
                            if (file.DeletionId > 0)
                            {
                                return(string.Empty);
                            }
                            else
                            {
                                using (Stream stream = file.DownloadFile())
                                {
                                    StreamReader rdr = new StreamReader(stream);

                                    return(rdr.ReadToEnd());
                                }
                            }
                        }
                    }
                }
                catch (VersionControlException ex)
                {
                    GeminiApp.LogException(ex, false);

                    return(string.Empty);
                }
                catch (Exception ex)
                {
                    GeminiApp.LogException(ex, false);

                    return(string.Empty);
                }
            }

            return(string.Empty);
        }
예제 #20
0
        public void doConnectToTFS()
        {
            #region variable declarations

            UIControl UIControl1 = new UIControl(mainForm);
            UIControl1.disableProjectUIControls();
            mainForm.cancelled = false;
            mainForm.myTeamRoles.Clear();
            mainForm.myTeamProjects.Clear();

            #endregion

            #region print opening connection string

            if (mainForm.rtfMain.InvokeRequired)
            {
                mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText("Opening connection...\n"); }));
            }

            #endregion

            try
            {
                //check for cancellation
                if (mainForm.connectionBackgroundWorker.CancellationPending == true)
                {
                    mainForm.connectionBackgroundWorker.Dispose();
                    return;
                }

                #region form the URI

                Uri tfsUriNew = new Uri(mainForm.serverURI);
                mainForm.tfsConnect = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUriNew);

                #endregion

                #region establish the connection

                if (mainForm.chkTFS2010.Checked == true)
                {
                    try
                    {
                        string serverURInocollection  = string.Concat(mainForm.http, mainForm.serverName, mainForm.colon, mainForm.portNumber, mainForm.tfsDir);
                        Uri    tfs2010Urinocollection = new Uri(serverURInocollection);
                        mainForm.tfs2010Server = TfsConfigurationServerFactory.GetConfigurationServer(tfs2010Urinocollection); //for TFS 2010 only
                        CatalogNode tfsCatalog = mainForm.tfs2010Server.CatalogNode;

                        // Query the children of the configuration server node for all of the team project collection nodes
                        mainForm.tpcNodes = tfsCatalog.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);
                    }
                    catch
                    {
                        string error = "Cannot connect to specified server, check that it is actually running TFS version 2010!\n";
                        mainForm.doProcessException(error);
                    }
                }

                IBuildServer buildServer = (IBuildServer)mainForm.tfsConnect.GetService(typeof(IBuildServer));;

                if (mainForm.rtfMain.InvokeRequired)
                {
                    mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText(string.Format("\nServer {0} found.", mainForm.serverName)); }));
                }

                mainForm.tfsVersionShort = buildServer.BuildServerVersion.ToString();

                #endregion

                #region put the TFS version into meaningful language

                //put the TFS version into more meaningful verbage //TODO this may need V5...bug on finding V5 is in progress
                if (mainForm.tfsVersionShort == "V5")
                {
                    mainForm.tfsVersionReadable = "Microsoft Team Foundation Server 2013/2015";
                }
                if (mainForm.tfsVersionShort == "V4")
                {
                    mainForm.tfsVersionReadable = "Microsoft Team Foundation Server 2012/2013";
                }
                if (mainForm.tfsVersionShort == "V3")
                {
                    mainForm.tfsVersionReadable = "Microsoft Team Foundation Server 2010";
                }
                if (mainForm.tfsVersionShort == "V2")
                {
                    mainForm.tfsVersionReadable = "Microsoft Team Foundation Server 2008";
                }

                if ((mainForm.tfsVersionShort != "V2") && (mainForm.tfsVersionShort != "V3") && (mainForm.tfsVersionShort != "V4") && (mainForm.tfsVersionShort != "V5"))
                {
                    mainForm.tfsVersionReadable = "ERROR: Could not determine TFS version!";
                }

                #endregion

                #region populate arrayLists with special values for all/none

                //add special entry for all project and all roles in the ArrayList which will later populate the ComboBoxes
                mainForm.myTeamProjects.Add(mainForm.allHolder);
                mainForm.myTeamRoles.Add(mainForm.allHolder);
                mainForm.myTeamRoles.Add(mainForm.noRoleHolder);

                #endregion

                #region project discovery

                if (mainForm.rtfMain.InvokeRequired)
                {
                    mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText("\n\tWORKING: Discovering and adding TFS projects..."); }));
                }

                //get ICommonStructureService (later to be used to list all team projects)
                mainForm.iss = (ICommonStructureService)mainForm.tfsConnect.GetService(typeof(ICommonStructureService));

                //get IGroupSecurityService (later to be used to retrieve identity information)
                mainForm.gss = (IGroupSecurityService2)mainForm.tfsConnect.GetService(typeof(IGroupSecurityService2));

                mainForm.allTeamProjects = mainForm.iss.ListProjects();

                if (mainForm.cboProject.InvokeRequired)
                {
                    mainForm.cboProject.Invoke(new MethodInvoker(delegate { mainForm.cboProject.Items.Add(mainForm.allHolder); }));
                }

                //iterate through each project to populate the ArrayLists for projects and roles, avoiding duplicate roles
                foreach (ProjectInfo TFSProjectInfo in mainForm.allTeamProjects)
                {
                    //mainForm.teamProjectURI = TFSProjectInfo.Uri;
                    if (mainForm.connectionBackgroundWorker.CancellationPending == true)
                    {
                        return;
                    }
                    mainForm.myTeamProjects.Add(TFSProjectInfo.Name.ToString()); //no filtering on projects, assumed there are no duplicate projects
                }

                if (mainForm.rtfMain.InvokeRequired)
                {
                    mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText("Done.\n"); }));
                }

                #endregion

                #region roles discovery

                if (mainForm.rtfMain.InvokeRequired)
                {
                    mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText("\tWORKING: Discovering and adding TFS roles across all projects on the server."); }));
                }

                //iterate through each project to populate the ArrayLists for projects and roles, avoiding duplicate roles
                foreach (ProjectInfo TFSProjectInfo in mainForm.allTeamProjects)
                {
                    if (mainForm.connectionBackgroundWorker.CancellationPending == true)
                    {
                        mainForm.connectionBackgroundWorker.Dispose();
                        return;
                    }

                    mainForm.teamProjectUriConnect = TFSProjectInfo.Uri;

                    //for each Team project identify each security Group
                    mainForm.allProjectGroups = mainForm.gss.ListApplicationGroups(mainForm.teamProjectUriConnect);  //this guy is expensive...why?

                    //filter out duplicate project roles
                    foreach (Identity projectGroup in mainForm.allProjectGroups)
                    {
                        if (mainForm.myTeamRoles.Contains(projectGroup.DisplayName.ToString()))
                        {
                            continue;
                        }
                        else
                        {
                            mainForm.myTeamRoles.Add(projectGroup.DisplayName.ToString());
                            mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText(string.Format("\n\t\tFOUND: Role {0}", projectGroup.DisplayName.ToString())); }));
                        }
                    }
                }

                if (mainForm.rtfMain.InvokeRequired)
                {
                    mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText("\n\tWORKING: Finished TFS roles discovery."); }));
                }

                #endregion

                #region sort projects and roles, then put them in the combo boxes

                //sort the projects and roles arrays - easier to read if they're alphabetical
                mainForm.myTeamProjects.Sort();
                mainForm.myTeamRoles.Sort();

                //populate the combo boxes with the values from the ArrayLists
                if (mainForm.allCollections == false)
                {
                    if (mainForm.cboProject.InvokeRequired)
                    {
                        mainForm.cboProject.Invoke(new MethodInvoker(delegate { mainForm.cboProject.DataSource = mainForm.myTeamProjects; }));
                    }
                }
                else
                {
                    if (mainForm.cboProject.InvokeRequired)
                    {
                        mainForm.cboProject.Invoke(new MethodInvoker(delegate { mainForm.cboProject.Text = mainForm.allHolder; mainForm.cboProject.Items.Add(mainForm.allHolder); }));
                    }
                }
                if (mainForm.cboRoles.InvokeRequired)
                {
                    mainForm.cboRoles.Invoke(new MethodInvoker(delegate { mainForm.cboRoles.DataSource = mainForm.myTeamRoles; }));
                }

                //don't enable the project/role UI controls until we have a successful connection
                UIControl1.enableProjectUIControls();

                mainForm.tfsConnected = true;

                #endregion
            }
            catch (Exception ex)
            {
                #region handle connection errors

                mainForm.doProcessException(ex.Message.ToString());
                if (mainForm.rtfMain.InvokeRequired)
                {
                    mainForm.rtfMain.Invoke(new MethodInvoker(delegate { mainForm.rtfMain.AppendText("\nPlease check the status of your TFS instance and try again.\n"); }));
                }

                #endregion
            }
        }
        public void createCatalogOfProjects(CatalogNode collectionNode)
        {
            ReadOnlyCollection<CatalogNode> projectNodes = collectionNode.QueryChildren(
                          new[] { CatalogResourceTypes.TeamProject },
                          false, CatalogQueryOptions.None);

            _projectNodes = projectNodes;
        }
예제 #22
0
        private static void V1()
        {
            //Initialize TFS Server object
            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(ConfigurationManager.AppSettings["TfsServer"]));

            //Get the catalog of team project collections
            CatalogNode catalogNode = configurationServer.CatalogNode;
            //Get all CatalogNodes which are ProjectCollection
            ReadOnlyCollection <CatalogNode> tpcNodes = catalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            //Get InstanceId of a ProjectCollection
            Guid tpcId = Guid.Empty;

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
                break;
            }
            Workspace currentWorkspace = null;
            //string localPath = @"C:\LOS_DEV";
            string URL = "http://sptserver.ists.com.vn:8080/tfs/iLendingPro";

            //WriteLine($"Local Path: {localPath}");
            System.Diagnostics.Debug.WriteLine($"Project Url: {URL}");
            TfsTeamProjectCollection projectCollection = new TfsTeamProjectCollection(new Uri(URL));

            //Fill list of projects in a local variable
            //TfsTeamProjectCollection projectCollection = configurationServer.GetTeamProjectCollection(tpcId);
            projectCollection.Authenticate();

            //Get WorkItem Tracking client for workitem collection for selected ProjectCollection
            WorkItemStore workItemStore = projectCollection.GetService <WorkItemStore>();
            //Get Project from Tracking client
            Project project = workItemStore.Projects[ConfigurationManager.AppSettings["TfsProjectName"]];

            //List<int> changesetIds = new List<int>();
            //foreach (var item in File.ReadAllLines("list_item.txt"))
            //{
            //    int tmp = 0;
            //    if (int.TryParse(item, out tmp))
            //    {
            //        changesetIds.Add(tmp);
            //    }
            //}

            //
            QueryFolder     teamQueryFolder = project.QueryHierarchy[ConfigurationManager.AppSettings["TfsQueryGroup"]] as QueryFolder;
            QueryItem       queryItem       = teamQueryFolder[ConfigurationManager.AppSettings["TfsQueryName"]];
            QueryDefinition queryDefinition = workItemStore.GetQueryDefinition(queryItem.Id);

            Dictionary <string, string> variables = new Dictionary <string, string> {
                { "@project", queryItem.Project.Name }
            };

            WorkItemCollection workItemCollection = workItemStore.Query(queryDefinition.QueryText, variables);

            DataTable dt = CreateDataTable();

            //Get Source Control/Version Control repository for selected project collection
            VersionControlServer versionControlServer = projectCollection.GetService <VersionControlServer>();
            //Get Details of Version Control using artifact provider
            VersionControlArtifactProvider artifactProvider = versionControlServer.ArtifactProvider;

            //Iterate through each item to get its details
            foreach (WorkItem workItem in workItemCollection)
            {
                DataRow dr = dt.NewRow();
                dr["ID"]    = workItem.Id;
                dr["Title"] = workItem.Title;

                //use linq to get the linked changesets to a workitem
                IEnumerable <Changeset> changesets = workItem.Links.OfType <ExternalLink>().Select(link => artifactProvider.GetChangeset(new Uri(link.LinkedArtifactUri)));

                //iterate through changesets' to get each changeset details
                foreach (Changeset changeset in changesets)
                {
                    dr["ChangesetId"] = changeset.ChangesetId;
                    foreach (Change changes in changeset.Changes)
                    {
                        //ServerItem is the full path of a source control file associated to changeset
                        if (changes.Item.ServerItem.Contains(ConfigurationManager.AppSettings["DevBranchName"]))
                        {
                            dr["Fix in DevBranch"] = "Yes";
                            break;
                        }
                        else if (changes.Item.ServerItem.Contains(ConfigurationManager.AppSettings["ReleaseBranchName"]))
                        {
                            dr["Fix in ReleaseBranch"] = "Yes";
                            break;
                        }
                    }
                }

                dt.Rows.Add(dr);
            }
            //Write datable to excel file using StreamWriter
            WriteToExcel(dt);
        }
예제 #23
0
        static void Main(string[] args)
        {
            // Get the Server URL
            Console.WriteLine("************************************************************************************************************************");
            Console.Write("Enter the Server URL:\t");
            Uri configurationServerUri = new Uri(Console.ReadLine());

            Console.WriteLine("\n************************************************************************************************************************");


            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);

            CatalogNode configurationServerNode = configurationServer.CatalogNode;

            // Query the children of the configuration server node for all of the team project collection nodes
            ReadOnlyCollection <CatalogNode> tpcNodes = configurationServerNode.QueryChildren(
                new Guid[] { CatalogResourceTypes.ProjectCollection },
                false,
                CatalogQueryOptions.None);

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success : Connected to the Server");
            Console.ResetColor();

            Console.WriteLine("\n************************************************************************************************************************");
            Console.Write("Enter the CSV File Path (Press Enter for default D:\\file.csv)  :\t");

            string fileInput = Console.ReadLine();

            Console.WriteLine("\n************************************************************************************************************************");

            string filePath;

            if (string.IsNullOrEmpty(fileInput))
            {
                filePath = @"D:\file.csv";
            }
            else
            {
                filePath = fileInput;
            }

            //delete if the file exists

            if (File.Exists(filePath))
            {
                try
                {
                    File.Delete(filePath);
                }
                catch
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("Unable to remove the file, check if the file is open/in use\n");
                    Environment.Exit(1);
                }
            }

            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Created a new file at {0}\n", filePath);
            Console.ResetColor();

            // initialize counter
            int count = 0;

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                // Use tpcNode.Resource to get the details for each team project collection.
                ServiceDefinition tpcServiceDefinition = tpcNode.Resource.ServiceReferences["Location"];

                ILocationService configLocationService = configurationServer.GetService <ILocationService>();
                Uri tpcUri = new Uri(configLocationService.LocationForCurrentConnection(tpcServiceDefinition));

                // Actually connect to the team project collection
                TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tpcUri);

                CatalogNode teamProjectCollection = tpcNodes[count];

                Console.WriteLine("================================================================\n");
                Console.WriteLine("Currently in Collection '" + tpcNodes[count].Resource.DisplayName + "' :");
                Console.WriteLine();

                //    Get the Team Projects that belong to the Team Project Collection
                ReadOnlyCollection <CatalogNode> teamProjects = teamProjectCollection.QueryChildren(
                    new Guid[] { CatalogResourceTypes.TeamProject },
                    false,
                    CatalogQueryOptions.None);


                foreach (CatalogNode teamProject in teamProjects)
                {
                    string teamProj = teamProject.Resource.DisplayName;

                    // initialise an empty string
                    string info = String.Empty;

                    Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
                    Console.WriteLine("Currently in Project '" + teamProject.Resource.DisplayName + "' :");

                    //Microsoft.TeamFoundation.TeamFoundationServiceUnavailableException


                    WorkItemStore workItemStore = null;
                    try
                    {
                        workItemStore = new WorkItemStore(tpc);
                    }
                    catch (Microsoft.TeamFoundation.TeamFoundationServiceUnavailableException ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("Collection '{0}' seems to be offline, please check the status of the collection", tpcNodes[count].Resource.DisplayName);
                        Console.ResetColor();
                        continue;
                    }
                    // write the wiql query here

                    if (workItemStore != null)
                    {
                        try
                        {
                            string WitQuery = "SELECT [System.Id]," +
                                              "[System.WorkItemType]," +
                                              "[System.Title]," +
                                              "[System.AssignedTo]," +
                                              "[System.State]," +
                                              "[System.Tags]" +
                                              "FROM workitems " +
                                              "WHERE [System.TeamProject] = '" + teamProj + "' " +
                                              "AND[System.WorkItemType] <> '' " +
                                              "AND[System.State] <> '' ";

                            Query query = new Query(workItemStore, WitQuery);

                            WorkItemCollection wic = query.RunQuery();

                            foreach (WorkItem item in wic)
                            {
                                // add additional entries seperated by ','
                                info += String.Format("{0},{1},{2},{3},{4},{5}\n",
                                                      teamProj,
                                                      item.Id,
                                                      item.Title,
                                                      item.Fields[CoreField.AssignedTo].Value,
                                                      item.State, item.Tags);
                            }


                            //Console.WriteLine(info);

                            //add to csv

                            File.AppendAllText(filePath, info);

                            Console.ForegroundColor = ConsoleColor.Cyan;
                            Console.WriteLine("Updated query output to the file {0}\n", filePath);
                            Console.ResetColor();
                        }
                        catch (Microsoft.TeamFoundation.WorkItemTracking.Client.ValidationException ex)
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("An error occured while running the query:\n" + ex.Message);
                            Console.ResetColor();
                        }
                    }
                }
                Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");

                count++;
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("file {0} Successfully Updated with Query Results!\n", filePath);
            Console.ResetColor();
            Console.WriteLine("Press 'Enter' to exit\n");
            Console.Read();
        }
예제 #24
0
        private IEnumerable<BuildInfoDto> GetBuildInfoDtosPerTeamProject(CatalogNode teamProjectCollectionNode,
            TfsConfigurationServer tfsServer, DateTime filterDate)
        {
            var buildInfoDtos = new List<BuildInfoDto>();
            try
            {
                // Use the InstanceId property to get the team project collection
                var collectionId = new Guid(teamProjectCollectionNode.Resource.Properties["InstanceId"]);
                var teamProjectCollection = tfsServer.GetTeamProjectCollection(collectionId);

                var buildServer = (IBuildServer)teamProjectCollection.GetService(typeof(IBuildServer));
                var testService = teamProjectCollection.GetService<ITestManagementService>();

                // Get a catalog of team projects for the collection
                var teamProjectNodes = teamProjectCollectionNode.QueryChildren(
                    new[] { CatalogResourceTypes.TeamProject },
                    false, CatalogQueryOptions.None);

                // List the team projects in the collection
                Parallel.ForEach(teamProjectNodes, teamProjectNode =>
                {
                    var buildDefinitionList =
                        new List<IBuildDefinition>(buildServer.QueryBuildDefinitions(teamProjectNode.Resource.DisplayName));
                    lock (buildInfoDtos)
                    {
                        buildInfoDtos.AddRange(GetBuildInfoDtosPerBuildDefinition(buildDefinitionList, buildServer,
                            teamProjectNode,
                            teamProjectCollection, testService, filterDate));
                    }
                });
            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }


            return buildInfoDtos;
        }
예제 #25
0
        public static void RunQuery(string tfs_url, string project_name, string query_folder, string query_name, string log_file, int take_first = 0)
        {
            _log_file = log_file;

            WriteLine("Initialize TFS Server object");
            TfsConfigurationServer configuration_server = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(tfs_url));

            WriteLine(@"Get the catalog of team project collections");
            CatalogNode catalog_node = configuration_server.CatalogNode;

            WriteLine(@"Get all CatalogNodes which are ProjectCollection");
            ReadOnlyCollection <CatalogNode> tpc_nodes = catalog_node.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            WriteLine(@"Get InstanceId of a ProjectCollection");
            Guid tpc_id = Guid.Empty;

            foreach (CatalogNode tpc_node in tpc_nodes)
            {
                tpc_id = new Guid(tpc_node.Resource.Properties["InstanceId"]);
                break;
            }

            WriteLine(@"Fill list of projects in a local variable");
            TfsTeamProjectCollection project_collection = configuration_server.GetTeamProjectCollection(tpc_id);

            project_collection.Authenticate();

            WriteLine(@"Get WorkItem Tracking client for workitem collection for selected ProjectCollection");
            WorkItemStore work_item_store = project_collection.GetService <WorkItemStore>();

            WriteLine(@"Get Project from Tracking client");

            Project project = work_item_store.Projects[project_name];

            WriteLine(@"Run Query");
            QueryFolder     team_query_folder = project.QueryHierarchy[query_folder] as QueryFolder;
            QueryItem       query_item        = team_query_folder[query_name];
            QueryDefinition queryDefinition   = work_item_store.GetQueryDefinition(query_item.Id);

            Dictionary <string, string> variables = new Dictionary <string, string> {
                { "project", query_item.Project.Name }
            };

            WorkItemCollection work_item_collection = work_item_store.Query(queryDefinition.QueryText, variables);

            WriteLine(@"Get Source Control/Version Control repository for selected project collection");
            VersionControlServer version_control_server = project_collection.GetService <VersionControlServer>();

            WriteLine(@"Get Details of Version Control using artifact provider");
            VersionControlArtifactProvider artifact_provider = version_control_server.ArtifactProvider;

            Write_to_excel(new string[] { "WorkItemID", "WorkItemTitle", "ChangesetId", "CreationDate", "ChangeType", "File" });

            WriteLine(@"Iterate through each item to get its details");

            IEnumerable <WorkItem> work_items = take_first > 0 ? work_item_collection.OfType <WorkItem>().Take(take_first) : work_item_collection.OfType <WorkItem>();

            foreach (WorkItem work_item in work_items)
            {
                WriteLine($"    ->{work_item.Id}");
                IEnumerable <Changeset> changesets = work_item.Links.OfType <ExternalLink>().Select(link =>
                {
                    Changeset set;
                    try
                    {
                        set = artifact_provider.GetChangeset(new Uri(link.LinkedArtifactUri));
                    }
                    catch (Exception ex)
                    {
                        BackgroundColor = ConsoleColor.Red;
                        WriteLine(ex.Message);
                        BackgroundColor = ConsoleColor.Black;
                        set             = null;
                    }
                    return(set);
                })
                                                     .Where(s => s != null);

                foreach (Changeset changeset in changesets)
                {
                    WriteLine($"        {changeset.ChangesetId}");
                    foreach (Change change in changeset.Changes)
                    {
                        WriteLine($"           {change.Item.ServerItem}");

                        var data = new string[] {
                            work_item.Id.ToString(),
                            work_item.Title,
                            changeset.ChangesetId.ToString(),
                            changeset.CreationDate.ToString(),
                            change.ChangeType.ToString(),
                            change.Item.ServerItem
                        };
                        Write_to_excel(data);
                    }
                }
            }
        }
예제 #26
0
        public WorkItem GetItem(string id, out string url)
        {
            url = null;

            TFSPicker.ConnectByImplementingCredentialsProvider connect = new TFSPicker.ConnectByImplementingCredentialsProvider();

            ICredentials iCred = new NetworkCredential(Username, Password);

            connect.setLoginDetails(Username, Password, RepositoryUrl);

            connect.GetCredentials(new Uri(RepositoryUrl), iCred);

            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(RepositoryUrl));


            configurationServer.Credentials = iCred;

            if (TFSPicker.IsBasicAuth)
            {
                configurationServer.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
            }
            else
            {
                configurationServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential(iCred));
            }

            try
            {
                configurationServer.EnsureAuthenticated();
            }
            catch
            {
                System.Threading.Thread.Sleep(1000);
                configurationServer             = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(RepositoryUrl));
                configurationServer.Credentials = iCred;

                if (TFSPicker.IsBasicAuth)
                {
                    configurationServer.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                }
                else
                {
                    configurationServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential(iCred));
                }
                configurationServer.EnsureAuthenticated();
            }

            CatalogNode catalogNode = configurationServer.CatalogNode;

            ReadOnlyCollection <CatalogNode> tpcNodes = catalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(new Guid(tpcNode.Resource.Properties["InstanceId"]));
                //TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(string.Concat(RepositoryUrl, '/', tpcNode.Resource.DisplayName)), iCred);

                if (TFSPicker.IsBasicAuth)
                {
                    tpc.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                }

                WorkItemStore workItemStore = (WorkItemStore)tpc.GetService(typeof(WorkItemStore));

                WorkItemCollection queryResults = workItemStore.Query(string.Format("Select [Id], [Work Item Type], [Title], [State] From WorkItems WHERE [Id] = '{0}' Order By [Id] Asc", id));

                if (queryResults.Count >= 1)
                {
                    var item = queryResults[0];

                    try
                    {
                        TswaClientHyperlinkService hyperlinkService = (TswaClientHyperlinkService)tpc.GetService(typeof(TswaClientHyperlinkService));
                        url = hyperlinkService.GetWorkItemEditorUrl(item.Id).ToString();
                    }
                    catch
                    {
                    }

                    return(item);
                }
            }

            return(null);
        }
예제 #27
0
        private async Task<List<BuildInfoDto>>  GetBuildInfoDtosPerTeamProject(CatalogNode teamProjectCollectionNode,
            TfsConfigurationServer tfsServer, DateTime filterDate)
        {
            var buildInfoDtos = new List<BuildInfoDto>();
            try
            {
                // Use the InstanceId property to get the team project collection
                var collectionId = new Guid(teamProjectCollectionNode.Resource.Properties["InstanceId"]);
                var teamProjectCollection = tfsServer.GetTeamProjectCollection(collectionId);

                var buildServer = (IBuildServer)teamProjectCollection.GetService(typeof(IBuildServer));
                var testService = teamProjectCollection.GetService<ITestManagementService>();



                // Get a catalog of team projects for the collection


                if (tfsServer.ServerDataProvider.ServerVersion == null)
                {


                    var teamProjectNodes = teamProjectCollectionNode.QueryChildren(new[] {CatalogResourceTypes.TeamProject}, false, CatalogQueryOptions.None);

                    // List the team projects in the collection
                    Parallel.ForEach(teamProjectNodes, teamProjectNode =>
                    {
                        var buildDefinitionList = buildServer.QueryBuildDefinitions(teamProjectNode.Resource.DisplayName).ToList();

                        lock (buildInfoDtos)
                        {
                            buildInfoDtos.AddRange(GetBuildInfoDtosPerBuildDefinition(buildDefinitionList, buildServer, teamProjectNode, teamProjectCollection, testService, filterDate));
                        }
                    });
                }
                else
                {
                    var commonStructureService = teamProjectCollection.GetService<ICommonStructureService>();
                    var httpClient = teamProjectCollection.GetClient<BuildHttpClient>();
                    var listAllProjects = commonStructureService.ListAllProjects().ToList();
                    foreach (var project in listAllProjects)
                    {
                        var definitionReferences = await httpClient.GetDefinitionsAsync(project: project.Name).ConfigureAwait(false);
                        
                        var buildInfos = await GetBuildInfoDtosPerBuildDefinitionRest(teamProjectCollection, definitionReferences, httpClient);
                        lock (buildInfoDtos)
                        {
                            buildInfoDtos.AddRange(buildInfos);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }


            return await Task.FromResult(buildInfoDtos);
        }
예제 #28
0
        public ActionResult Search(string id, string search)
        {
            try
            {
                ItemWidgetArguments args = new ItemWidgetArguments(UserContext, GeminiContext, Cache, System.Web.HttpContext.Current.Request, CurrentIssue);

                TFSPicker tfsPicker = new TFSPicker();

                tfsPicker.AuthenticateUser(args);

                UserWidgetDataDetails loginDetails = tfsPicker.getLoginDetails();

                TFSPicker.ConnectByImplementingCredentialsProvider connect = new TFSPicker.ConnectByImplementingCredentialsProvider();

                ICredentials iCred = new NetworkCredential(loginDetails.Username, loginDetails.Password);

                connect.setLoginDetails(loginDetails.Username, loginDetails.Password, loginDetails.RepositoryUrl);

                connect.GetCredentials(new Uri(loginDetails.RepositoryUrl), iCred);

                TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(loginDetails.RepositoryUrl));

                configurationServer.Credentials = iCred;

                if (TFSPicker.IsBasicAuth)
                {
                    configurationServer.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                }
                else
                {
                    configurationServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential(iCred));
                }

                try
                {
                    configurationServer.EnsureAuthenticated();
                }
                catch
                {
                    System.Threading.Thread.Sleep(1000);
                    configurationServer             = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(loginDetails.RepositoryUrl));
                    configurationServer.Credentials = iCred;

                    if (TFSPicker.IsBasicAuth)
                    {
                        configurationServer.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                    }
                    else
                    {
                        configurationServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential(iCred));
                    }
                    configurationServer.EnsureAuthenticated();
                }

                CatalogNode catalogNode = configurationServer.CatalogNode;

                ReadOnlyCollection <CatalogNode> tpcNodes = catalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

                string url = string.Empty;

                List <WorkItem2> queryResults = new List <WorkItem2>();

                TfsTeamProjectCollection tpc = null;

                string query = "Select [Id], [Work Item Type], [Title], [State] From WorkItems Where [Title] Contains '" + search + "' Order By [Id] Asc";

                if (search.Trim().Length == 0)
                {
                    query = "Select [Id], [Work Item Type], [Title], [Description] From WorkItems Order By [Id] Asc";
                }

                foreach (CatalogNode tpcNode in tpcNodes)
                {
                    tpc = configurationServer.GetTeamProjectCollection(new Guid(tpcNode.Resource.Properties["InstanceId"]));
                    //tpc = new TfsTeamProjectCollection(new Uri(string.Concat(loginDetails.RepositoryUrl, '/', tpcNode.Resource.DisplayName)), iCred);

                    if (TFSPicker.IsBasicAuth)
                    {
                        tpc.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                    }

                    WorkItemStore workItemStore = (WorkItemStore)tpc.GetService(typeof(WorkItemStore));

                    var result = workItemStore.Query(query);

                    if (result != null)
                    {
                        TswaClientHyperlinkService hyperlinkService = null;

                        try
                        {
                            hyperlinkService = ((TswaClientHyperlinkService)tpc.GetService(typeof(TswaClientHyperlinkService)));
                        }
                        catch
                        {
                        }

                        foreach (WorkItem res in result)
                        {
                            WorkItem2 item = new WorkItem2()
                            {
                                Item = res, BaseUrl = string.Concat(tpcNode.Resource.DisplayName, '/', res.AreaPath)
                            };

                            try
                            {
                                if (hyperlinkService != null)
                                {
                                    item.FullUrl = hyperlinkService.GetWorkItemEditorUrl(res.Id);
                                }
                            }
                            catch
                            {
                            }

                            queryResults.Add(item);
                        }
                    }
                }

                Dictionary <string, WorkItem> details = new Dictionary <string, WorkItem>();

                if (queryResults.Count > 0)
                {
                    IssueWidgetData <List <string> > data = GeminiContext.IssueWidgetStore.Get <List <string> >(id.ToInt(), Constants.AppId, Constants.ControlId);

                    if (data == null || data.Value == null)
                    {
                        data = new IssueWidgetData <List <string> >();

                        data.AppId = Constants.AppId;

                        data.ControlId = Constants.ControlId;

                        data.IssueId = id.ToInt();

                        data.Value = new List <string>();
                    }

                    foreach (WorkItem2 item in queryResults)
                    {
                        //check if we are not already there!
                        if (data.Value.Contains(item.Item.Id.ToString()))
                        {
                            continue;
                        }

                        /*if (isTfs2012)
                         * {*/
                        if (item.FullUrl != null && item.FullUrl.ToString().HasValue())
                        {
                            url = item.FullUrl.ToString();
                        }
                        else
                        {
                            url = string.Format("{0}/{1}/_workitems#_a=edit&id={2}", loginDetails.RepositoryUrl, item.BaseUrl, item.Item.Id);
                        }

                        details.Add(url, item.Item);
                    }
                }

                Dictionary <string, TfsPickerItem> tfsPickerModel = ConvertWorkItemsToTfsPickerItems(details);

                dataView = Content(BaseController.RenderPartialViewToString(this, AppManager.Instance.GetAppUrl("782D003D-D9F0-455F-AF09-74417D6DFD2B", "views/search.cshtml"), tfsPickerModel));
            }
            catch (Exception ex)
            {
                Pair <int, string> authenticationModel = new Pair <int, string>(CurrentIssue.Entity.Id, string.Concat(UserContext.Url, "/apps/tfspicker/authenticate/", CurrentIssue.Entity.Id));

                dataView = Content(BaseController.RenderPartialViewToString(this, AppManager.Instance.GetAppUrl("782D003D-D9F0-455F-AF09-74417D6DFD2B", "views/authenticationForm.cshtml"), authenticationModel));

                successView = false;

                messageView = ex.Message;

                GeminiApp.LogException(new Exception(ex.Message)
                {
                    Source = "TFS Picker"
                }, false);
            }

            return(JsonSuccess(new { success = successView, data = dataView, message = messageView }));
        }