Пример #1
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (txtServerUrl.Enabled)
            {
                string strServerUrl = txtServerUrl.Text;
                try
                {
                    // get the configuartion service
          #if UsingVssClientCredentials
                    // TODO: find a way for TFS 2017 to always ask for credentials
                    srvConfiguration = new TfsConfigurationServer(new Uri(strServerUrl), new Microsoft.VisualStudio.Services.Client.VssClientCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(true), Microsoft.VisualStudio.Services.Common.CredentialPromptType.PromptIfNeeded));
          #else
                    srvConfiguration = new TfsConfigurationServer(new Uri(strServerUrl), null, new UICredentialsProvider(this));
          #endif

                    // get the registry service
                    tfsRegServiceConfiguration = srvConfiguration.GetService <ITeamFoundationRegistry>();

                    ReadRegistry();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }

                EnableControls(true);
            }
            else
            {
                EnableControls(false);
            }
        }
Пример #2
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;
     }
 }
Пример #3
0
        public TFS(string servername, string domain, string username, string password)
        {
            if (string.IsNullOrEmpty(servername))
            {
                throw new ArgumentException("Parameter named:servername cannot be null or empty.");
            }

            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Parameter named:username cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Parameter named:password cannot be null or empty.");
            }

            try
            {
                var tfsConfigurationServer = new TfsConfigurationServer(new Uri(servername),
                                                                        new NetworkCredential(username, password, domain));
                store = (WorkItemStore) tfsConfigurationServer.GetService(typeof (WorkItemStore));
            }
            catch (Exception)
            {
                var tfsServer = new TeamFoundationServer(servername, new NetworkCredential(username, password, domain));
                store = (WorkItemStore) tfsServer.GetService(typeof (WorkItemStore));
            }
        }
Пример #4
0
        static void Main(string[] args)

        {
            TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("http://server:8080/tfs"));

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

            TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);

            TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None);

            using (StreamWriter file = new StreamWriter("userlist.txt"))

                foreach (TeamFoundationIdentity id in ids)

                {
                    if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity")

                    {
                        Console.WriteLine(id.DisplayName);
                    }
                    //{ Console.WriteLine(id.UniqueName); }

                    file.WriteLine("[{0}]", id.DisplayName);
                }

            var count = ids.Count(x => ids.Contains(x));

            Console.WriteLine(count);
            Console.ReadLine();
        }
 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;
     }
 }
Пример #6
0
        public TFS(string servername, string domain, string username, string password)
        {
            if (string.IsNullOrEmpty(servername))
            {
                throw new ArgumentException("Parameter named:servername cannot be null or empty.");
            }

            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Parameter named:username cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Parameter named:password cannot be null or empty.");
            }
            //ICredentialsProvider provider = new UICredentialsProvider();
            //tfsServer = TeamFoundationServerFactory.GetServer(serverName, provider);
            //if (!tfsServer.HasAuthenticated)
            //    tfsServer.Authenticate();
            try
            {
                var tfsConfigurationServer = new TfsConfigurationServer(new Uri(servername),
                                                                        new NetworkCredential(username, password, domain));
                store = (WorkItemStore) tfsConfigurationServer.GetService(typeof (WorkItemStore));
            }
            catch (Exception)
            {
                var tfsServer = new TeamFoundationServer(servername, new NetworkCredential(username, password, domain));
                store = (WorkItemStore) tfsServer.GetService(typeof (WorkItemStore));
            }
        }
Пример #7
0
        public static void GetAllCollections(string tfsCollectionUri)
        {
            Uri configurationServerUri = new Uri(tfsCollectionUri);
            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);

            ITeamProjectCollectionService tpcService = configurationServer.GetService <ITeamProjectCollectionService>();

            var tpc = tpcService.GetCollections();
        }
Пример #8
0
        public virtual void Initialize(TfsConfigurationServer tfsConfigurationServer)
        {
            _teamFoundationServerCollections = null;

            if (tfsConfigurationServer != null)
            {
                TfsConfigurationServerInstance = tfsConfigurationServer;
                TfsCollectionService           = tfsConfigurationServer.GetService <ITeamProjectCollectionService>();
            }
        }
Пример #9
0
        public List <TeamProjectCollection> GetTeamProjectCollections(Uri tfsServer)
        {
            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(tfsServer);

            var tpcService = configurationServer.GetService <ITeamProjectCollectionService>();

            var tfsTeamCollection = tpcService.GetCollections().ToList();

            return(tfsTeamCollection);
        }
Пример #10
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);
        }
Пример #11
0
        protected override void ProcessRecord()
        {
            var uri = new Uri(ServerUri);
            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(uri);

            var tpcService = configurationServer.GetService <ITeamProjectCollectionService>();


            WriteObject(tpcService.GetCollections(), true);

            base.ProcessRecord();
        }
Пример #12
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);
            }
        }
Пример #13
0
        public IList <Collection> GetCollections()
        {
            Uri tfsUri = new Uri(this.Url);
            TfsConfigurationServer        configuracao = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
            ITeamProjectCollectionService tpcService   = configuracao.GetService <ITeamProjectCollectionService>();

            IList <TeamProjectCollection> tfsCollections = tpcService.GetCollections();
            IList <Collection>            collections    = new List <Collection>();

            foreach (TeamProjectCollection tpc in tfsCollections)
            {
                collections.Add(new Collection(tpc.Name));
            }

            return(collections);
        }
Пример #14
0
        private static List <User> GetAllTfsValidUsers(string tfsServerUrl)
        {
            List <User> tfsUsers = new List <User>();

            TfsConfigurationServer configServer = Connect(tfsServerUrl);

            // Get all Team Project Collections
            ITeamProjectCollectionService tpcService = configServer.GetService <ITeamProjectCollectionService>();

            foreach (TeamProjectCollection tpc in tpcService.GetCollections())
            {
                TfsTeamProjectCollection teamProjectCollection = configServer.GetTeamProjectCollection(tpc.Id);
                teamProjectCollection.EnsureAuthenticated();

                var identityManagementService = teamProjectCollection.GetService <IIdentityManagementService>();
                // Get members of Project Collection Valid Users group
                var collectionWideValidUsers = identityManagementService.ReadIdentity(IdentitySearchFactor.DisplayName,
                                                                                      "Project Collection Valid Users",
                                                                                      MembershipQuery.Expanded,
                                                                                      ReadIdentityOptions.None);
                var validMembers = identityManagementService.ReadIdentities(collectionWideValidUsers.Members,
                                                                            MembershipQuery.Expanded,
                                                                            ReadIdentityOptions.ExtendedProperties);
                var members = validMembers
                              .Where(m => !m.IsContainer &&
                                     m.Descriptor.IdentityType != "Microsoft.TeamFoundation.UnauthenticatedIdentity" &&
                                     m.Descriptor.IdentityType != "Microsoft.TeamFoundation.ServiceIdentity")
                              .Select(m => new User {
                    DisplayName = m.DisplayName, AccountName = m.UniqueName
                })
                              .ToList();

                // Collect members
                foreach (var m in members)
                {
                    if (!tfsUsers.Any(t => t.AccountName == m.AccountName))
                    {
                        tfsUsers.Add(m);
                    }
                }
            }

            tfsUsers = tfsUsers.OrderBy(m => m.DisplayName).ToList();

            return(tfsUsers);
        }
        public void ConnectToTFS(Uri serverUri, string userName)
        {
            baseUserConnection = new TfsConfigurationServer(serverUri);

            // Get the identity management service
            IIdentityManagementService ims = baseUserConnection.GetService<IIdentityManagementService>();

            identity = ims.ReadIdentity(IdentitySearchFactor.AccountName, userName, MembershipQuery.None, ReadIdentityOptions.None);

            impersonatedConnection = new TfsConfigurationServer(serverUri, identity.Descriptor);

            collectionNodes = impersonatedConnection.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            if (identity != null)
                fullName = identity.DisplayName;
        }
Пример #16
0
        static void Main(string[] args)
        {
            //Uri tfsUri = new Uri(@"https://tfsqa.mmm.com/tfs");
            //string teamProjectName = "Alderaan";
            //TfsTeamProjectCollection myTfsTeamProjectCollection = new TfsTeamProjectCollection(tfsUri);
            //ITestManagementService service = (ITestManagementService)myTfsTeamProjectCollection.GetService(typeof(ITestManagementService));
            //ITestManagementTeamProject myTestManagementTeamProject = service.GetTeamProject(teamProjectName);

            Uri    tfsUri          = new Uri(@"https://tfsqa.mmm.com/tfs");
            string teamProjectName = "Alderaan";

            TfsConfigurationServer configServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);

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

            ITestManagementService testManagementService = (ITestManagementService)configServer.GetService(typeof(ITestManagementService));
            //ITestManagementTeamProject myTestManagementTeamProject = service.GetTeamProject(teamProjectName);
        }
        public static ICollection <BuildServiceHostDefinition> GetAllBuildServiceHosts(TfsConfigurationServer configurationServer)
        {
            List <BuildServiceHostDefinition> buildServiceHostCollection = new List <BuildServiceHostDefinition>();
            ITeamProjectCollectionService     collectionService          = configurationServer.GetService <ITeamProjectCollectionService>();

            if (collectionService != null)
            {
                IList <TeamProjectCollection> collections = collectionService.GetCollections();
                foreach (TeamProjectCollection collection in collections)
                {
                    if (collection.State == TeamFoundationServiceHostStatus.Started)
                    {
                        TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(collection.Id);
                        buildServiceHostCollection.AddRange(BuildServerHelper.GetAllBuildServiceHosts(tpc));
                    }
                }
            }
            return(buildServiceHostCollection);
        }
Пример #18
0
        private static TfsTeamProjectCollection FindCollection(TfsConfigurationServer server, Guid?collectionId, string collectionName)
        {
            if (collectionId != null)
            {
                return(server.GetTeamProjectCollection(collectionId.Value));
            }

            var match = server
                        .GetService <ITeamProjectCollectionService>()
                        .GetCollections()
                        .FirstOrDefault(c => string.Equals(c.Name, collectionName, StringComparison.OrdinalIgnoreCase));

            if (match == null)
            {
                return(null);
            }

            return(server.GetTeamProjectCollection(match.Id));
        }
Пример #19
0
        private static string GetNameFromIdentity(string identity)
        {
            TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri(serverUrl));

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

            TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "[TEAM FOUNDATION]\\Team Foundation Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);

            TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None);

            foreach (TeamFoundationIdentity id in ids)
            {
                if (id.Descriptor.Identifier.ToString().Equals(identity))
                {
                    return(id.DisplayName);
                }
            }
            return("N/A");
        }
Пример #20
0
        private static void QueueADSyncJob()
        {
            //cHANGE THE LIBRARIES UNDER THE DLL FOLDER WITH THE VERSIONS YOU COPY FROM YOUR SERVER FOLDER.
            //EG FOR 2020, C:\Program Files\Azure DevOps Server 2020\Tools
            //THEN CHANGE THE REFERENCES
            string _myUri = @"YOUR_SERVER_URL";  //REPLACE WITH YOUR SERVER URL
            Guid   adSync = new Guid("544dd581-f72a-45a9-8de0-8cd3a5f29dfe");

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

            configurationServer.EnsureAuthenticated();
            ITeamFoundationJobService jobService = configurationServer.GetService <ITeamFoundationJobService>();

            int triggered = jobService.QueueJobNow(adSync, true);

            Console.WriteLine("Job Triggered");
            Console.ReadLine();
        }
Пример #21
0
        public override IEnumerable <IPathNode> GetNodeChildren(IProviderContext providerContext)
        {
            var nodes = new List <IPathNode>();

            var registry   = Server.GetService <ITeamFoundationRegistry>();
            var collection = registry.ReadEntries("/**");
            var re         = new Regex(@"\/[^\/]+$");
            var entries    = from entry in collection
                             let key = re.Replace(entry.Path, String.Empty)
                                       group entry by key;

            var registryNodes = CollateGroups(entries);

            nodes.AddRange(registryNodes.Children);
            //AddProjectCollectionNodes(nodes);


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

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

                                    ProjectDefinition projectDefinition = new ProjectDefinition();
                                    projectDefinition.Name            = project.Name;
                                    projectDefinition.CollectionName  = collection.Name;
                                    projectDefinition.UtcCreationDate = creationDate.ToUniversalTime();
                                    projectList.Add(projectDefinition);
                                }
                            }
                        }
                    }
                }
            }
            return(projectList);
        }
        static void Main(string[] args)

        {
            TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("http://tfsserver:8080/tfs"));

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

            TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "[TEAM FOUNDATION]\\Team Foundation Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);

            TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None);

            foreach (TeamFoundationIdentity id in ids)

            {
                if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity")

                {
                    Console.WriteLine(id.DisplayName);
                    Console.WriteLine(id.UniqueName);
                }
            }

            Console.ReadLine();
        }
Пример #24
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();
        }
        private static string GetTfsSqlServerInstance(TfsConfigurationServer server)
        {
            var catalogService = server.GetService<ICatalogService>();

            var sqlDatabaseInstanceNode = catalogService.QueryRootNode(CatalogTree.Infrastructure)
                .QueryChildren(new[] {CatalogResourceTypes.SqlDatabaseInstance}, recurse: true, queryOptions: CatalogQueryOptions.IncludeParents)
                .FirstOrDefault();

            Assert.IsNotNull(sqlDatabaseInstanceNode, "Could not find SqlDatabaseInstance catalog node.");

            var sqlServerInstance = sqlDatabaseInstanceNode.ParentNode.Resource.Properties["MachineName"];
            var instanceName = sqlDatabaseInstanceNode.Resource.Properties["InstanceName"];
            if (!string.IsNullOrEmpty(instanceName))
            {
                sqlServerInstance += @"\" + instanceName;
            }
            return sqlServerInstance;
        }
Пример #26
0
        /// <summary>
        /// restituisce l'elenco delle collection
        /// </summary>
        /// <returns>
        /// lista collection
        /// </returns>
        public static List<string> GetCollection(String tfsName)
        {
            List<string> listBox1 = new List<string>();
            using (var configurationServer = new TfsConfigurationServer(new Uri(tfsName), TFS.Cred))
            {
                var prova = configurationServer.GetService<ITeamProjectCollectionService>();
                foreach (var projectInfo in prova.GetCollections())
                {
                    listBox1.Add(projectInfo.Name);
                }

                return listBox1;
            }
        }
Пример #27
0
        private static TfsTeamProjectCollection FindCollection(TfsConfigurationServer server, Guid? collectionId, string collectionName)
        {
            if (collectionId != null)
                return server.GetTeamProjectCollection(collectionId.Value);

            var match = server
                .GetService<ITeamProjectCollectionService>()
                .GetCollections()
                .FirstOrDefault(c => string.Equals(c.Name, collectionName, StringComparison.OrdinalIgnoreCase));

            if (match == null)
                return null;

            return server.GetTeamProjectCollection(match.Id);
        }
Пример #28
0
 public ILocationService GetConfigLocationService()
 {
     return(_tfsConfigurationServer.GetService <ILocationService>());
 }
Пример #29
0
        public static void ListAllMembers()
        {
            // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            // Connect to Azure DevOps Services
            connection = new VssConnection(new Uri(collectionUrl), creds);

            /*
             * ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
             * TeamHttpClient teamClient = connection.GetClient<TeamHttpClient>();
             *
             * IEnumerable<TeamProjectReference> projects = projectClient.GetProjects(top: 10000).Result;
             *
             * var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(collectionUrl));
             * var ims = tpc.GetService<IIdentityManagementService>();
             * //IGroupSecurityService gss = tpc.GetService<IGroupSecurityService>();
             * IIdentityManagementService gss = tpc.GetService<IIdentityManagementService>();*/


            Uri configurationServerUri = new Uri(serverUrl);
            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
            var tpcService = configurationServer.GetService <ITeamProjectCollectionService>();

            string[,] members = new string[100000, 5];
            int i = 0;

            foreach (Microsoft.TeamFoundation.Framework.Client.TeamProjectCollection tpc in tpcService.GetCollections())
            {
                var tfsProjectCollection = new TfsTeamProjectCollection(new Uri(serverUrl + "/" + tpc.Name));

                ProjectHttpClient projectClient                 = connection.GetClient <ProjectHttpClient>();
                IEnumerable <TeamProjectReference> projects     = projectClient.GetProjects(top: 10000).Result;
                List <TeamProjectReference>        teamProjects = new List <TeamProjectReference>(projects);

                var sec = tfsProjectCollection.GetService <IGroupSecurityService>();


                foreach (var teamProject in teamProjects)
                {
                    Microsoft.TeamFoundation.Core.WebApi.TeamProject projectdet = projectClient.GetProject(teamProject.Name).Result;

                    Uri proj      = new Uri(teamProject.Url);
                    var appGroups = sec.ListApplicationGroups(proj.AbsoluteUri);;

                    foreach (var group in appGroups)
                    {
                        Identity[] groupMembers = sec.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);
                        foreach (Identity member in groupMembers)
                        {
                            if (member.Members != null)
                            {
                                foreach (string memberSid in member.Members)
                                {
                                    Identity memberInfo = sec.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.Expanded);
                                    if (memberInfo.Type != IdentityType.WindowsUser)
                                    {
                                        continue;
                                    }

                                    members[i, 0] = tfsProjectCollection.Name;
                                    members[i, 1] = teamProject.Name;
                                    members[i, 2] = memberInfo.AccountName;
                                    members[i, 3] = memberInfo.Domain;
                                    members[i, 4] = group.DisplayName;
                                    Console.WriteLine(tfsProjectCollection.Name + " " + teamProject.Name + " " + memberInfo.AccountName + " " + memberInfo.DisplayName + " " + group.DisplayName);
                                    i++;
                                }
                            }
                        }
                    }
                }
            }

            /*string[,] members = new string[100000, 4];
             *
             * int i = 0;
             *
             * foreach (var project in projects)
             * {
             *  try
             *  {
             *      Identity[] appGroups = gss.ListApplicationGroups(  .ListApplicationGroups(project.Url);
             *
             *      foreach (var appGroup in appGroups)
             *      {
             *
             *          //string adminGroupName = "[" + project.Name.ToString() + "]" + "\\Project Administrators";
             *          //Identity SIDS = gss.ReadIdentity(SearchFactor.AccountName, adminGroupName, QueryMembership.Expanded);
             *
             *          Identity SIDS = gss.ReadIdentity(SearchFactor.AccountName, appGroup.AccountName, QueryMembership.Expanded);
             *          Identity[] userIds = gss.ReadIdentities(SearchFactor.Sid, SIDS.Members, QueryMembership.None);
             *
             *          foreach (Identity id in userIds)
             *          {
             *              members[i, 0] = project.Name;
             *              members[i, 1] = id.AccountName;
             *              members[i, 2] = id.DisplayName;
             *              members[i, 3] = appGroup.AccountName;
             *              Console.WriteLine(project.Name + " " + id.AccountName + " " + id.DisplayName + " " +appGroup.AccountName);
             *              i++;
             *          }
             *          Console.WriteLine("Number of total members: " + i);
             *      }
             *  }
             *  catch (Exception ex)
             *  {
             *      members[i, 0] = project.Name;
             *      members[i, 1] = "N/A";
             *      members[i, 2] = "N/A";
             *      members[i, 3] = "N/A";
             *      i++;
             *  }
             * }*/
        }
Пример #30
0
        public static void AddCollectionMembers(string collectionName, string groupName, string fromDomain, string toDomain)
        {
            VssCredentials creds = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();

            // Connect to Azure DevOps Services
            connection = new VssConnection(new Uri(serverUrl), creds);

            Uri configurationServerUri = new Uri(serverUrl);
            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(configurationServerUri);
            var tpcService = configurationServer.GetService <ITeamProjectCollectionService>();


            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\TfsAdminAutomationData\out_CollectionMembersAdd.txt"))
            {
                file.WriteLine("Collection # Group # Domain # AccountName # DisplayName");
                foreach (Microsoft.TeamFoundation.Framework.Client.TeamProjectCollection tpc in tpcService.GetCollections())
                {
                    if (!tpc.Name.Equals(collectionName))
                    {
                        continue;
                    }

                    var tfsProjectCollection = new TfsTeamProjectCollection(new Uri(serverUrl + "/" + tpc.Name));

                    ProjectHttpClient projectClient = connection.GetClient <ProjectHttpClient>();

                    var sec = tfsProjectCollection.GetService <IGroupSecurityService>();

                    var appGroups = sec.ListApplicationGroups(null);

                    foreach (var group in appGroups)
                    {
                        if (!group.DisplayName.Equals(groupName))
                        {
                            continue;
                        }

                        try
                        {
                            Identity[] groupMembers = sec.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);
                            foreach (Identity member in groupMembers)
                            {
                                if (member.Members != null)
                                {
                                    foreach (string memberSid in member.Members)
                                    {
                                        try
                                        {
                                            Identity memberInfo = sec.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.Expanded);
                                            if (memberInfo.Type != IdentityType.WindowsUser)
                                            {
                                                continue;
                                            }

                                            file.WriteLine(tpc.Name + " # " + group.DisplayName + " # " + memberInfo.Domain + " # " + memberInfo.AccountName + " # " + memberInfo.DisplayName);

                                            if (memberInfo.Domain.Equals(fromDomain))
                                            {
                                                string username  = toDomain + "\\" + memberInfo.AccountName;
                                                string groupname = "[" + tpc.Name + "]\\" + group.DisplayName;
                                                var    result    = AddUserToGroup(username, groupname, tfsProjectCollection.Name);
                                                if (result)
                                                {
                                                    file.WriteLine("Added");
                                                }
                                                else
                                                {
                                                    file.WriteLine("Cannot be added");
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            file.WriteLine("Could not read member info");
                                            file.WriteLine(ex.InnerException);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            file.WriteLine("Could not read group members: " + group.AccountName);
                            file.WriteLine(ex.InnerException);
                            continue;
                        }
                    }
                }
            }
        }
Пример #31
0
        private static void ListUsers(string[] args)
        {
            _users.Clear();

            Log("Here your users:", ConsoleColor.White);

            var collectionNodes = _server.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            foreach (var collectionNode in collectionNodes)
            {
                var collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
                var collection   = _server.GetTeamProjectCollection(collectionId);
                if (_ignoredCollections.Contains(collection.Name))
                {
                    Log($"{collection.Name} ignored.", ConsoleColor.DarkRed);
                    continue;
                }
                else
                {
                    Log($"Collection: {collection.Name}");
                }

                var iservice = collection.GetService <IIdentityManagementService>();

                if (iservice == null)
                {
                    Log("Identity Service not found.", ConsoleColor.Red);
                    Console.ReadKey();
                    return;
                }

                var teamService = _server.GetService <TfsTeamService>();
                if (teamService == null)
                {
                    Log("Team Service not found.", ConsoleColor.Red);
                    Console.ReadKey();
                    return;
                }

                var identity = iservice.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);

                if (identity == null)
                {
                    Log($"Project Collection Valid Users not found for {collection.Name}", ConsoleColor.Red);
                    continue;
                }

                foreach (var member in identity.Members)
                {
                    if (member.IdentityType.Equals("Microsoft.TeamFoundation.UnauthenticatedIdentity") ||
                        member.IdentityType.Equals("Microsoft.TeamFoundation.Identity"))
                    {
                        continue;
                    }

                    var identityDescriptor = new IdentityDescriptor(member.IdentityType, member.Identifier);
                    var identityMember     = iservice.ReadIdentity(identityDescriptor, MembershipQuery.None, ReadIdentityOptions.IncludeReadFromSource);

                    if (!_users.Contains(identityMember.UniqueName))
                    {
                        _users.Add(identityMember.UniqueName);
                    }
                }
            }

            Log("Users:");

            _users = _users.OrderBy(a => a).ToList();
            foreach (var item in _users)
            {
                Log($"{item}", ConsoleColor.White);
            }

            Log("Completed.", ConsoleColor.DarkGreen);
        }
 private static TeamProjectCollection AttachCollection(TfsConfigurationServer server, CollectionInformation collectionInfo, bool cloneCollection)
 {
     var collectionService = server.GetService<ITeamProjectCollectionService>();
     var jobDetail = collectionService.QueueAttachCollection(collectionInfo.ConnectionString, null, cloneCollection, collectionInfo.Name, null, collectionInfo.VirtualDir);
     return collectionService.WaitForCollectionServicingToComplete(jobDetail);
 }
Пример #33
0
        static void Main(string[] args)
        {
            //Get Office VSTS Projects
            IEnumerable <TeamProjectReference> projects = GetVstsProjects();

            //Access VSTS Groups
            TfsConfigurationServer     tcs = new TfsConfigurationServer(new Uri(ConfigurationManager.AppSettings["Uri"]));
            IIdentityManagementService ims = tcs.GetService <IIdentityManagementService>();

            //Create Table for Storing Excel Data
            DataTable admins = new DataTable();

            admins.Clear();
            admins.Columns.Add("ProjectName");
            admins.Columns.Add("Email");

            //List for storing json strings
            List <Project> projectList = new List <Project>();

            //Iterate through projects to get admins
            foreach (TeamProjectReference project in projects)
            {
                string projectInfo = $"[{project.Name}]\\{ConfigurationManager.AppSettings["Group"]}";
                TeamFoundationIdentity        tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, projectInfo, MembershipQuery.Direct, ReadIdentityOptions.None);
                List <TeamFoundationIdentity> ids = new List <TeamFoundationIdentity>();

                foreach (IdentityDescriptor identity in tfi.Members)
                {
                    try
                    {
                        TeamFoundationIdentity group = ims.ReadIdentity(identity,
                                                                        MembershipQuery.ExpandedDown, ReadIdentityOptions.None);
                        GetAllProjectAdmins(group, ims, ref ids);
                    }
                    catch
                    {
                        TeamFoundationIdentity single = ims.ReadIdentity(identity, MembershipQuery.None, ReadIdentityOptions.None);
                        ids.Add(single);
                    }
                }

                Console.WriteLine($"Members of {projectInfo}");
                Project proj = new Project {
                    Name = project.Name
                };
                proj.Administrators = new List <string>();

                foreach (TeamFoundationIdentity identity in ids)
                {
                    if (!proj.Administrators.Contains(identity.UniqueName))
                    {
                        //Add admin to DataTable
                        DataRow admin = admins.NewRow();
                        admin["ProjectName"] = project.Name;
                        admin["Email"]       = identity.UniqueName;
                        admins.Rows.Add(admin);

                        //Add admin to Project Admin List
                        proj.Administrators.Add(identity.UniqueName);

                        Console.WriteLine(identity.UniqueName);
                    }
                }

                projectList.Add(proj);
            }

            //SaveAsExcel(admins);
            SaveAsJson(projectList);
        }
        private static CollectionInformation DetachCollectionWithInformation(TfsConfigurationServer server, string collectionName)
        {
            var collectionService = server.GetService<ITeamProjectCollectionService>();
            var collection = collectionService.GetCollections()
                .FirstOrDefault(c => c.Name.Equals(collectionName, StringComparison.OrdinalIgnoreCase));

            if (collection == null) return null;

            string connectionString;
            var jobDetail = collectionService.QueueDetachCollection(collection, null, null, out connectionString);
            var detachedCollection = collectionService.WaitForCollectionServicingToComplete(jobDetail);

            return new CollectionInformation
                   {
                       Name = detachedCollection.Name,
                       ConnectionString = connectionString,
                       VirtualDir = detachedCollection.VirtualDirectory
                   };
        }