public static CatalogNode GetTeamProjectCollection(TfsConfigurationServer tfs)
        {
            ReadOnlyCollection<CatalogNode> teamProjectCatalogs = tfs.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            return teamProjectCatalogs.FirstOrDefault(p => p.Resource.DisplayName == GetConfigValue("$Instance.TeamProjectCollectionName$"));
        }
Exemple #2
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));
            }
        }
        public List <String> GetTFSProjects()
        {
            TfsConfigurationServer           server  = GetTFSServerInformation();
            ReadOnlyCollection <CatalogNode> catalog = GetTFSCollectionNodes(server);

            return(GetTFSListOfProjects(server, catalog));
        }
Exemple #4
0
 public TfsClient( Uri tfsUri, NetworkCredential credential,
                         string collenctionName, string projectName )
 {
     configurationServer =
         new TfsConfigurationServer( tfsUri, credential );
     GetTfsProject( collenctionName, projectName );
 }
Exemple #5
0
        public static TfsTeamProjectCollection Get_TeamProjectCollection(
            TfsConfigurationServer configurationServer,
            CatalogNode teamProjectCollectionNode)
        {
            Int64 startTicks = Log.DOMAINSERVICES("Enter", Common.LOG_APPNAME);

            Guid collectionId = new Guid(teamProjectCollectionNode.Resource.Properties["InstanceId"]);

            TfsTeamProjectCollection teamProjectCollection;

            try
            {
                teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
            }
            catch (TimeoutException)
            {
                throw;
            }
            catch
            {
                throw;
            }

            Log.DOMAINSERVICES("Exit", Common.LOG_APPNAME, startTicks);

            return(teamProjectCollection);
        }
Exemple #6
0
        public static TfsConfigurationServer AuthenticateToTFSService()
        {
            Uri                  tfsUri    = new Uri(GetConfigValue("$Instance.VSOnlineUri$"));
            string               username  = GetConfigValue("$Instance.Username$");
            string               password  = GetConfigValue("$Instance.Password$");
            NetworkCredential    netCred   = new NetworkCredential(username, password);
            BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive = false;

            TfsConfigurationServer configurationServer = new TfsConfigurationServer(new Uri(tfsUrl), tfsCred);

            configurationServer.Authenticate();
            return(configurationServer);

            //If you specify a provider, the user will be provided with a prompt to provide non-default credentials
            ICredentialsProvider   provider = new UICredentialsProvider();
            TfsConfigurationServer tfs      = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri, provider);

            try
            {
                //Prompts the user for credentials if they have not already been authenticated
                tfs.EnsureAuthenticated();
            }
            catch (TeamFoundationServerUnauthorizedException)
            {
                //Handle the TeamFoundationServerUnauthorizedException that is thrown when the user clicks 'Cancel'
                //in the authentication prompt or if they are otherwise unable to be successfully authenticated
                tfs = null;
            }

            return(tfs);
        }
Exemple #7
0
        internal static XlHlp.XlLocation AddSection_ConfigurationServer_Info(
            XlHlp.XlLocation insertAt,
            TfsConfigurationServer configurationServer)
        {
            insertAt.MarkStart(XlHlp.MarkType.None);

            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "Name:", configurationServer.Name);
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "Culture:", configurationServer.Culture.DisplayName);
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "InstanceId:", configurationServer.InstanceId.ToString());
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "ServerCapabilities:", configurationServer.ServerCapabilities.ToString());
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "SessionId:", configurationServer.SessionId.ToString());
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "TimeZone:", configurationServer.TimeZone.ToString());
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "UICulture", configurationServer.UICulture.ToString());
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "Uri", configurationServer.Uri.ToString());

            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "AuthorizedIdentity:", configurationServer.AuthorizedIdentity.DisplayName);
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "CatalogNode:", configurationServer.CatalogNode.FullPath);
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "HasAuthenticated:", configurationServer.HasAuthenticated.ToString());
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "IsHostedServer:", configurationServer.IsHostedServer.ToString());
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "ClientCacheDirectoryForInstance:", configurationServer.ClientCacheDirectoryForInstance);
            XlHlp.AddLabeledInfo(insertAt.AddRow(2), "ClientCacheDirectoryForUser:", configurationServer.ClientCacheDirectoryForUser);

            insertAt.MarkEnd(XlHlp.MarkType.None);

            if (!insertAt.OrientVertical)
            {
                // Skip past the info just added.
                insertAt.SetLocation(insertAt.RowStart, insertAt.MarkEndColumn + 1);
            }

            return(insertAt);
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            LogArguments(args);

            Uri    projectCollectionUri = new Uri(args.ElementAt(0));
            Guid   projectCollectionId  = Guid.Parse(args.ElementAt(1));
            Guid   requestedByUserId    = Guid.Parse(args.ElementAt(2));
            string artifactsFolder      = Path.GetFullPath(args.ElementAt(3));
            string emailSubject         = args.ElementAt(4);
            string emailBody            = args.ElementAt(5);

            Console.WriteLine("Project collection URI: " + projectCollectionUri);
            Console.WriteLine("Project collection id:  " + projectCollectionId);
            Console.WriteLine("User identifier:        " + requestedByUserId);
            Console.WriteLine("Artifacts folder:       " + artifactsFolder);
            Console.WriteLine("Email subject:          " + emailSubject);
            Console.WriteLine("Email body:             " + emailBody);

            string tfsUriFromCollectionUri             = projectCollectionUri.AbsoluteUri.Replace(projectCollectionUri.Segments.Last(), string.Empty);
            TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(tfsUriFromCollectionUri));

            TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(projectCollectionId);

            IIdentityManagementService identityServiceManager = teamProjectCollection.GetService <IIdentityManagementService>();

            TeamFoundationIdentity[] tfsIdentities = identityServiceManager.ReadIdentities(new Guid[1] {
                requestedByUserId
            }, MembershipQuery.Direct);

            SendArtifacs(tfsIdentities, emailSubject, emailBody, artifactsFolder);
        }
Exemple #9
0
        /// <summary>
        /// Connects to the TFS server.
        /// </summary>
        public void Connect()
        {
            configurationServer = new TfsConfigurationServer(ServerUri, System.Net.CredentialCache.DefaultCredentials);

            // Get the catalog of team project collections
            ReadOnlyCollection <CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            // List the team project collections
            foreach (CatalogNode collectionNode in collectionNodes)
            {
                // Use the InstanceId property to get the team project collection
                Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);

                // Find the requested team project collection
                if (teamProjectCollection.Name.ToUpper(CultureInfo.InvariantCulture).EndsWith(this.TeamProjectCollectionName.ToUpper(CultureInfo.InvariantCulture), StringComparison.Ordinal))
                {
                    SourceControl = (VersionControlServer)teamProjectCollection.GetService(typeof(VersionControlServer));

                    this.TeamProjects = new ReadOnlyCollection <TeamProject>(SourceControl.GetAllTeamProjects(false));

                    break; // We got what we want, now exit the loop
                }
            }
        }
Exemple #10
0
    static void Main()
    {
        var tfsUri = new Uri("http://xx.xx.xx.xx:8080/tfs");
        TfsConfigurationServer configurationServer =
            TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
        // Get the catalog of team project collections
        ReadOnlyCollection <CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
            new[] { CatalogResourceTypes.ProjectCollection },
            false, CatalogQueryOptions.None);

        // List the team project collections
        foreach (CatalogNode collectionNode in collectionNodes)
        {
            // Use the InstanceId property to get the team project collection
            Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
            TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
            // 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);
            }
        }
    }
Exemple #11
0
        public static WorkItemStore GetWorkItemStore(TfsConfigurationServer tfs, CatalogNode teamProjectColCatalog)
        {
            Guid teamProjectCatalogId = new Guid(teamProjectColCatalog.Resource.Properties["InstanceId"]);
            TfsTeamProjectCollection teamProjectCollection = tfs.GetTeamProjectCollection(teamProjectCatalogId);

            return(new WorkItemStore(teamProjectCollection));
        }
Exemple #12
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));
            }
        }
 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;
     }
 }
        /// <summary>
        /// connect to a TFS Server.
        /// </summary>
        /// <param name="tfsUri">Possible URI of the TFS Server</param>
        /// <returns>The correct Tfs Uri</returns>
        public Uri ConnectToTfsServer(Uri tfsUri)
        {
            bool tfsIsConnected = false;

            //The URI we get from FoundationServerExt_ProjectContextChanged does not allow us to connect to the server
            //Trim the URI from back to front till connection can be established
            while (!tfsIsConnected && tfsUri.AbsolutePath != tfsUri.Authority)
            {
                m_TfsConfigurationServer =
                    TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
                tfsUri =
                    new Uri(
                        tfsUri.OriginalString.Substring(0, tfsUri.OriginalString.LastIndexOf('/')));

                // workaround: if  tfsConfigurationServer.EnsureAuthenticated() fails it doesn't set tfsIsConnected to true and continues to trim uri
                try
                {
                    m_TfsConfigurationServer.EnsureAuthenticated();
                    tfsIsConnected = true;
                }
                catch (TeamFoundationServerException)
                {
                    tfsIsConnected = false;
                }
            }

            if (tfsIsConnected)
            {
                FetchProjects();
            }

            return(tfsUri);
        }
        /// <summary>
        /// Lists all TFS collection from server, each collection can have project
        /// </summary>
        public void ListAllCollections()
        {
            try
            {
                TfsConfigurationServer server = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(_tfsAddress));

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

                foreach (CatalogNode node in collectionNodes)
                {
                    Guid collectionId = new Guid(node.Resource.Properties["InstanceId"]);
                    TfsTeamProjectCollection teamProjectCollection = server.GetTeamProjectCollection(collectionId);
                    Console.WriteLine("Collection: " + teamProjectCollection.Name);

                    // TODO - temporary list all projects also here
                    ReadOnlyCollection <CatalogNode> projectNodes = node.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None);
                    foreach (CatalogNode elem in projectNodes)
                    {
                        Console.WriteLine("Team project name is: " + elem.Resource.DisplayName);
                    }
                }
            }
            catch (Exception ex)
            {
                // custom exception handling - TODO throw custom exception
                _logger.Error("Tfs conection error: " + ex.Message);
                throw;
            }
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="username">Username on the service.</param>
 /// <param name="password">Password on the service.</param>
 /// <param name="domain">Domain on the service.</param>
 /// <param name="host">Root path of the service.</paparam>
 internal TeamFoundationServerService(String username, String password, String domain, String host)
 {
     _username = username;
     _configurationServer = GetConfigurationServer(username, password, domain, host);
     try
     {
         _configurationServer.Authenticate();
     }
     catch (Exception)
     {
         try
         {
             Uri url = new Uri(host);
             String ip = Dns.GetHostAddresses(url.DnsSafeHost).First().ToString();
             String newHost = url.Scheme + "://" + ip + ":" + url.Port + url.PathAndQuery;
             _configurationServer = GetConfigurationServer(username, password, domain, newHost);
             _configurationServer.Authenticate();
         }
         catch (TeamFoundationServiceUnavailableException)
         {
             //if authentication fail
             return;
         }
     }
 }
Exemple #17
0
        public static BuildDefinitionDtoCollection GetBuildDefinitions(this TfsConfigurationServer tfsConfigurationServer, Guid teamProjectCollectionId, string teamProjectName)
        {
            if (tfsConfigurationServer == null)
            {
                throw new ArgumentNullException("tfsConfigurationServer");
            }

            TfsTeamProjectCollection tfsTeamProjectCollection = tfsConfigurationServer.GetTeamProjectCollection(teamProjectCollectionId);
            IBuildServer             buildServer = tfsTeamProjectCollection.GetService <IBuildServer>();

            IBuildDefinition[]           buildDefinitions             = buildServer.QueryBuildDefinitions(teamProjectName);
            BuildDefinitionDtoCollection buildDefinitionDtoCollection = new BuildDefinitionDtoCollection();

            foreach (IBuildDefinition buildDefinition in buildDefinitions)
            {
                BuildDefinitionDto buildDefinitionDto = new BuildDefinitionDto();
                buildDefinitionDto.TeamProjectName = buildDefinition.TeamProject;
                buildDefinitionDto.Name            = buildDefinition.Name;
                buildDefinitionDto.Id  = buildDefinition.Id;
                buildDefinitionDto.Uri = buildDefinition.Uri;
                buildDefinitionDtoCollection.Add(buildDefinitionDto);
            }

            return(buildDefinitionDtoCollection);
        }
Exemple #18
0
        public static IEnumerable <WorkItemDto> GetWorkItemsFromTeamBuilds(this TfsConfigurationServer tfsConfigurationServer, Guid teamProjectCollectionId, IEnumerable <WorkItemSummaryDto> workItems)
        {
            if (tfsConfigurationServer == null)
            {
                throw new ArgumentNullException("tfsConfigurationServer");
            }

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

            TfsTeamProjectCollection tfsTeamProjectCollection = tfsConfigurationServer.GetTeamProjectCollection(teamProjectCollectionId);
            WorkItemStore            workItemStore            = tfsTeamProjectCollection.GetService <WorkItemStore>();
            WorkItemDtoCollection    workItemDtoCollection    = new WorkItemDtoCollection();

            foreach (WorkItemSummaryDto workItemSummaryDto in workItems)
            {
                WorkItem    workItem    = workItemStore.GetWorkItem(workItemSummaryDto.Id);
                WorkItemDto workItemDto = WorkItemDto.CreateFromWorkItem(workItem, workItemSummaryDto.AssociatedBuildNumber);
                workItemDtoCollection.Add(workItemDto);
            }

            return(workItemDtoCollection);
        }
Exemple #19
0
        public static TeamBuildDtoCollection GetTeamBuilds(this TfsConfigurationServer tfsConfigurationServer, Guid teamProjectCollectionId, string teamProjectName, IEnumerable <string> teamBuildDefinitionNames)
        {
            if (tfsConfigurationServer == null)
            {
                throw new ArgumentNullException("tfsConfigurationServer");
            }

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

            TfsTeamProjectCollection tfsTeamProjectCollection = tfsConfigurationServer.GetTeamProjectCollection(teamProjectCollectionId);
            IBuildServer             buildServer            = tfsTeamProjectCollection.GetService <IBuildServer>();
            TeamBuildDtoCollection   teamBuildDtoCollection = new TeamBuildDtoCollection();

            foreach (string teamBuildDefinitionName in teamBuildDefinitionNames)
            {
                IBuildDetailSpec buildDetailSpec = buildServer.CreateBuildDetailSpec(teamProjectName, teamBuildDefinitionName);
                buildDetailSpec.Reason             = BuildReason.All;
                buildDetailSpec.QueryOrder         = BuildQueryOrder.FinishTimeDescending;
                buildDetailSpec.QueryDeletedOption = QueryDeletedOption.ExcludeDeleted;
                IBuildQueryResult buildQueryResult = buildServer.QueryBuilds(buildDetailSpec);
                foreach (IBuildDetail buildDetail in buildQueryResult.Builds)
                {
                    TeamBuildDto teamBuildDto = new TeamBuildDto();
                    teamBuildDto.BuildNumber    = buildDetail.BuildNumber;
                    teamBuildDto.Uri            = buildDetail.Uri;
                    teamBuildDto.DefinitionName = teamBuildDefinitionName;
                    teamBuildDtoCollection.Add(teamBuildDto);
                }
            }

            return(teamBuildDtoCollection);
        }
Exemple #20
0
        public void createConfigurationServer(Uri uri)
        {
            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(uri);

            _configurationServer = configurationServer;
        }
Exemple #21
0
        public static CatalogNode GetTeamProjectCollection(TfsConfigurationServer tfs)
        {
            ReadOnlyCollection <CatalogNode> teamProjectCatalogs = tfs.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);

            return(teamProjectCatalogs.FirstOrDefault(p => p.Resource.DisplayName == GetConfigValue("$Instance.TeamProjectCollectionName$")));
        }
        private static async Task <bool> CanLogIn(string username, string password, string uri, string configType)
        {
            bool response = false;

            // VSO check
            if (configType == "VSO")
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(uri);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                               Convert.ToBase64String(
                                                                                                   Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))));
                    Debug.WriteLine("Code: " + client.GetAsync("").Result.StatusCode);
                    response = client.GetAsync("").Result.StatusCode == HttpStatusCode.OK;
                }
            }
            // TFS check
            else if (configType == "TFS")
            {
                var credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(username, password)));
                var server      = new TfsConfigurationServer(new Uri(uri), credentials);
                try
                {
                    server.EnsureAuthenticated();
                }
                catch (TeamFoundationServerUnauthorizedException e)
                {
                    return(false);
                }
                response = server.HasAuthenticated;
            }
            return(response);
        }
Exemple #23
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);
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            // Connect to Team Foundation Server
            //     Server is the name of the server that is running the application tier for Team Foundation.
            //     Port is the port that Team Foundation uses. The default port is 8080.
            //     VDir is the virtual path to the Team Foundation application. The default path is tfs.
            Uri tfsUri = (args.Length < 1) ?
                         new Uri("http://pro-pggm-manoj:8080/tfs") : new Uri(args[0]);

            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);

            // Get the catalog of team project collections
            ReadOnlyCollection <CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            // Use the InstanceId property to get the team project collection
            Guid collectionId = new Guid(collectionNodes[0].Resource.Properties["InstanceId"]);
            TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);

            ClientObjectModel.UpdateChangeSetComments(teamProjectCollection, "Updated Thru Code");

            ClientObjectModel.DisplayWorkItemsInConsole(teamProjectCollection);
        }
Exemple #25
0
 public MyTfsProjectCollection(CatalogNode teamProjectCollectionNode, TfsConfigurationServer tfsConfigurationServer, NetworkCredential networkCredential)
 {
     try
     {
         Name = teamProjectCollectionNode.Resource.DisplayName;
         ServiceDefinition tpcServiceDefinition = teamProjectCollectionNode.Resource.ServiceReferences["Location"];
         var configLocationService = tfsConfigurationServer.GetService <ILocationService>();
         var tpcUri = new Uri(configLocationService.LocationForCurrentConnection(tpcServiceDefinition));
         _tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tpcUri, new MyCredentials(networkCredential));
         _commonStructureService   = _tfsTeamProjectCollection.GetService <ICommonStructureService>();
         _buildServer = _tfsTeamProjectCollection.GetService <IBuildServer>();
         _tswaClientHyperlinkService = _tfsTeamProjectCollection.GetService <TswaClientHyperlinkService>();
         CurrentUserHasAccess        = true;
     }
     catch (TeamFoundationServiceUnavailableException ex)
     {
         _log.Debug("Can't access " + Name + ". This could be because the project collection is currently offline.", ex);
         CurrentUserHasAccess = false;
     }
     catch (TeamFoundationServerUnauthorizedException ex)
     {
         _log.Debug("Unauthorized access to " + teamProjectCollectionNode, ex);
         CurrentUserHasAccess = false;
     }
 }
        public static TfsConfigurationServer GetConfigurationServerAndAuthenticate(Uri tfsUrl)
        {
            TfsConfigurationServer tfsConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUrl);

            tfsConfigurationServer.Authenticate();
            return(tfsConfigurationServer);
        }
Exemple #27
0
        public void ConnectToTFSServer(string ServerURL)
        {
            // Connect to Team Foundation Server
            //     Server is the name of the server that is running the application tier for Team Foundation.
            //     Port is the port that Team Foundation uses. The default port is 8080.
            //     VDir is the virtual path to the Team Foundation application. The default path is tfs.
            Uri tfsUri = new Uri(ServerURL);
            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);

            // Get the catalog of team project collections
            ReadOnlyCollection <CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            // List the team project collections
            foreach (CatalogNode collectionNode in collectionNodes)
            {
                // Use the InstanceId property to get the team project collection
                Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
                TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);

                // 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);
            }
        }
        protected RepositoryBase(String username, String password, string domain, string projectCollection, String url)
        {
            string fullUrl = url;
            bool collectionExists = !String.IsNullOrEmpty(projectCollection);

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

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

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

            if (collectionExists)
            {
                _tfs = new TfsTeamProjectCollection(new Uri(fullUrl), credentials);
                _tfs.EnsureAuthenticated();
            }
        }
Exemple #29
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);
                }
            }
        }
Exemple #30
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 static TfsConfigurationServer GetConfigurationServerAndAuthenticate(Uri tfsUrl, string domain, string userName, string password)
        {
            TfsConfigurationServer tfsConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUrl);

            tfsConfigurationServer.Credentials = new NetworkCredential(userName, password, domain);
            tfsConfigurationServer.Authenticate();
            return(tfsConfigurationServer);
        }
        public TfsTeamProjectCollection GetTfsTeamProjectCollection(Guid collectionId, Uri tfsServer)
        {
            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(tfsServer);
            var collection = configurationServer.GetTeamProjectCollection(collectionId);

            return(collection);
        }
 public void Connect()
 {
     Uri tfsUri = _serverAddress;
     TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
     configurationServer.Credentials = _credentials;
     configurationServer.EnsureAuthenticated();
     _configurationServer = configurationServer;
 }
Exemple #34
0
 public TeamProjectCollections(Uri tfsUri, ITfsCredentials tfsCredentials)
 {
     this._tfsUri                       = tfsUri;
     this._tfsCredentials               = tfsCredentials;
     this._tfsTeamProjectCollection     = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri, this._tfsCredentials);
     this._tfsConfigurationServer       = this._tfsTeamProjectCollection.GetConfigurationServer();
     this._registration                 = (IRegistration)this._tfsTeamProjectCollection.GetService(typeof(IRegistration));
     this._teamProjectCollectionService = this._tfsConfigurationServer.GetService <ITeamProjectCollectionService>();
 }
Exemple #35
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();
        }
Exemple #36
0
        public void createCatalogTeamProjectCollections(TfsConfigurationServer cs)
        {
            // Get the catalog of team project collections
            ReadOnlyCollection <CatalogNode> collectionNodes = cs.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            _collectionNodes = collectionNodes;
        }
 public TeamProjectCollections(Uri tfsUri, ITfsCredentials tfsCredentials)
 {
     this._tfsUri = tfsUri;
     this._tfsCredentials = tfsCredentials;
     this._tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri, this._tfsCredentials);
     this._tfsConfigurationServer = this._tfsTeamProjectCollection.GetConfigurationServer();
     this._registration = (IRegistration)this._tfsTeamProjectCollection.GetService(typeof(IRegistration));
     this._teamProjectCollectionService = this._tfsConfigurationServer.GetService<ITeamProjectCollectionService>();
 }
Exemple #38
0
        /// <summary>
        /// The get catalog nodes.
        /// </summary>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <returns>
        /// The <see cref="List"/>.
        /// </returns>
        private List <CatalogNode> GetCatalogNodes(Uri uri, ICredentials cred, bool anotherUser)
        {
            List <CatalogNode> catalogNodes = null;

            try
            {
                connectUri = uri;
                TfsClientCredentials tfsClientCredentials;
                if (anotherUser)
                {
                    if (connectUri.ToString().Contains(".visualstudio.com"))
                    {
                        tfsClientCredentials = new TfsClientCredentials(false);
                    }
                    else
                    {
                        Microsoft.TeamFoundation.Client.WindowsCredential wcred = new Microsoft.TeamFoundation.Client.WindowsCredential(false);
                        tfsClientCredentials = new TfsClientCredentials(wcred);
                    }
                }
                else
                {
                    if (connectUri.ToString().Contains(".visualstudio.com"))
                    {
                        tfsClientCredentials = new TfsClientCredentials();
                    }
                    else
                    {
                        Microsoft.TeamFoundation.Client.WindowsCredential wcred = new Microsoft.TeamFoundation.Client.WindowsCredential(true);
                        tfsClientCredentials = new TfsClientCredentials(wcred);
                    }
                }

                using (TfsConfigurationServer serverConfig = new TfsConfigurationServer(uri, tfsClientCredentials))
                {
                    serverConfig.Authenticate();
                    serverConfig.EnsureAuthenticated();
                    if (serverConfig.HasAuthenticated)
                    {
                        Credential   = serverConfig.Credentials;
                        catalogNodes = serverConfig.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None).OrderBy(f => f.Resource.DisplayName).ToList();
                    }
                }
            }
            catch (TeamFoundationServiceUnavailableException ex)
            {
                MessageBox.Show(ResourceHelper.GetResourceString("MSG_TFS_SERVER_IS_INACCESSIBLE") + "\n" + uri.OriginalString, ResourceHelper.GetResourceString("ERROR_TEXT"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ResourceHelper.GetResourceString("ERROR_TEXT"), MessageBoxButton.OK, MessageBoxImage.Error);
                return(catalogNodes);
            }

            return(catalogNodes);
        }
Exemple #39
0
 public MyTfsServer(CiEntryPointSetting ciEntryPointSetting)
 {
     try {
         _tfsConfigurationServer = GetTfsConfigurationServer(ciEntryPointSetting.Url, ciEntryPointSetting.UserName, ciEntryPointSetting.GetPassword());
         _tfsConfigurationServer.EnsureAuthenticated();
     } catch (TeamFoundationServiceUnavailableException ex) {
         _log.Debug(ex);
         throw new ServerUnavailableException(ex.Message, ex);
     }
 }
 public MyTfsServer(CiEntryPointSetting ciEntryPointSetting)
 {
     try {
         _tfsConfigurationServer = GetTfsConfigurationServer(ciEntryPointSetting.Url, ciEntryPointSetting.UserName, ciEntryPointSetting.GetPassword());
         _tfsConfigurationServer.EnsureAuthenticated();
     } catch (TeamFoundationServiceUnavailableException ex) {
         _log.Debug(ex);
         throw new ServerUnavailableException(ex.Message, ex);
     }
 }
Exemple #41
0
        public static void ConnectTFServer(TFSCmdletBase cmdlet, string url, ICredentials credentials)
        {
            try
            {
                Uri uri =
                    new Uri(url);
                
                TfsConfigurationServer tfsServer =
                    new TfsConfigurationServer(
                        uri,
                        credentials);
                
                cmdlet.WriteVerbose(
                    cmdlet,
                    "Connected, checking the connection");
                
                try {
                    tfsServer.EnsureAuthenticated();
                }
                catch (Exception eTfsServerConnected) {
                    
                    cmdlet.WriteError(
                        cmdlet,
                        "Failed to connect to server '" +
                        url +
                        "'." +
                        eTfsServerConnected.Message,
                        "FailedToConnect",
                        ErrorCategory.InvalidResult,
                        true);
                }
                
                CurrentData.CurrentServer = tfsServer;
                
                cmdlet.WriteVerbose(cmdlet,
                                    "Connected to: '" +
                                    url + 
                                    "'");
                
                cmdlet.WriteObject(cmdlet, tfsServer);
            }
//            catch (TeamFoundationServerUnauthorizedException ex)
//            {
//                // handle access denied
//            }
//            catch (TeamFoundationServiceUnavailableException ex)
//            {
//                // handle service unavailable
//            }
            catch (WebException ex)
            {
                // handle other web exception
            }
        }
        private static CollectionInformation BuildCollectionInformation(TfsConfigurationServer server, string collectionName)
        {
            var sqlServer = GetTfsSqlServerInstance(server);

            var connectionStringBuilder = new SqlConnectionStringBuilder
                                          {
                                              DataSource = sqlServer,
                                              IntegratedSecurity = true,
                                              InitialCatalog = "Tfs_" + collectionName
                                          };
            return new CollectionInformation
                   {
                       Name = collectionName,
                       ConnectionString = connectionStringBuilder.ConnectionString,
                       VirtualDir = string.Format("~/{0}/", collectionName)
                   };
        }
        public static void ResetCollection(string testCollectionName, string databaseBackupFile, bool cloneCollection)
        {
            const string testServerUri = "http://localhost:8080/tfs";

            Assert.IsTrue(File.Exists(databaseBackupFile), "Collection database backup not found at '{0}'", databaseBackupFile);

            var server = new TfsConfigurationServer(new Uri(testServerUri));

            var collectionInfo = DetachCollectionWithInformation(server, testCollectionName)
                ?? BuildCollectionInformation(server, testCollectionName);

            RestoreDatabase(collectionInfo, databaseBackupFile);

            var attachedCollection = AttachCollection(server, collectionInfo, cloneCollection);

            Assert.AreEqual(TeamFoundationServiceHostStatus.Started, attachedCollection.State, "Collection not started");
        }
        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;
        }
Exemple #45
0
        private static TfsTeamProjectCollection GetProjectCollection(TfsConfigurationServer configurationServer)
        {
            // Get the catalog of team project collections
            ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            foreach (CatalogNode collectionNode in collectionNodes)
            {
                if (collectionNode.Resource.DisplayName == projectCollectionName)
                {
                    Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
                    return configurationServer.GetTeamProjectCollection(collectionId);
                }
            }

            return null;
        }
Exemple #46
0
        public TfsConfigurationServer GetTfsServer()
        {
            TfsConfigurationServer server = null;
            try
            {
                var tfsUri = new Uri(_configurationTfsService.Uri);
                var credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(_configurationTfsService.Username, _configurationTfsService.Password)));
                server = new TfsConfigurationServer(tfsUri, credentials);
                server.EnsureAuthenticated();

            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }
            return server;
        }
Exemple #47
0
        public bool CanConnect(Uri tfsUri, NetworkCredential credentials)
        {
            Guard.NotNull(tfsUri, credentials);

            bool canConnect;
            using (var server = new TfsConfigurationServer(tfsUri, credentials))
            {
                try
                {
                    server.EnsureAuthenticated();
                    canConnect = true;
                }
                catch (Exception)
                {
                    canConnect = false;
                }
            }

            return canConnect;
        }
        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);
            }
        }
Exemple #49
0
        public bool CanConnect(Uri tfsUri)
        {
            Guard.NotNull(tfsUri);

            bool canConnect;
            using (var server = new TfsConfigurationServer(tfsUri))
            {
                try
                {
                    server.Authenticate();
                    canConnect = server.HasAuthenticated;
                }
                catch (Exception)
                {
                    canConnect = false;
                }
            }

            return canConnect;
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            bool fromCookie = false;
            var userDataPrincipal = HttpContext.Current.User as UserDataPrincipal;
            if (userDataPrincipal == null)
            {
                userDataPrincipal = UserDataPrincipal.InitFromHeaders(actionContext.Request.Headers);
            }
            if (userDataPrincipal == null)
            {
                userDataPrincipal = UserDataPrincipal.InitFromAuthCookie(actionContext.Request.Headers);
                fromCookie = true;
            }

            if (userDataPrincipal == null)
            {
                SetUnauthorizedResponse(actionContext);
                return;
            }

            try
            {
                var configUri = new Uri(userDataPrincipal.TfsUrl);

                var provider = userDataPrincipal.GetCredentialsProvider();
                var tfsConfigServer = new TfsConfigurationServer(configUri, provider.GetCredentials(null, null), provider);

                tfsConfigServer.EnsureAuthenticated();

                HttpContext.Current.Items["TFS_CONFIG_SERVER"] = tfsConfigServer;
            }
            catch (TeamFoundationServerUnauthorizedException ex)
            {
                SetUnauthorizedResponse(actionContext, ex.Message, fromCookie);
                return;
            }

            HttpContext.Current.User = userDataPrincipal;

            base.OnActionExecuting(actionContext);
        }
Exemple #51
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;
        }
Exemple #52
0
        public IEnumerable<Node> GetTfsProjects(TfsConnection conn)
        {
            var cols = new List<Node>();
            var configServer = new TfsConfigurationServer(
                new Uri(conn.TfsUrl),
                new NetworkCredential(conn.Username, conn.Password, conn.Domain));
            configServer.Authenticate();

            var catalog = configServer.CatalogNode;
            var tpcNodes = catalog.QueryChildren(
                new Guid[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            foreach (var tpcNode in tpcNodes)
            {
                Node nd = new Node();

                Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
                nd.Properties.Add(new Item("guid", tpcId.ToString()));
                nd.Name = tpcNode.Resource.DisplayName;
                cols.Add(nd);
                var tpc = configServer.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)
                {
                    var ndProj = new Node();
                    ndProj.Name = p.Resource.DisplayName;
                    nd.Children.Add(ndProj);
                }
            }

            return cols;

            /*
            WorkItemStore workItemStore = (WorkItemStore)collection.GetService(typeof(WorkItemStore));
            string qry = "SELECT [Title] From WorkItems Where [Work Item Type] = 'Bug' " +
                " AND [Iteration Path] = 'AML_Module\\Release 3\\Sprint 4' AND [Team Project]='AML_Module'";

            var res = workItemStore.Query(qry);
            foreach (var wi in res)
            {
                string s = wi.ToString();
            }*/
        }
        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
                   };
        }
        public void createConfigurationServer(Uri uri)
        {
            TfsConfigurationServer configurationServer =
                TfsConfigurationServerFactory.GetConfigurationServer(uri);

            _configurationServer = configurationServer;
        }
        public void createCatalogTeamProjectCollections(TfsConfigurationServer cs)
        {
            // Get the catalog of team project collections
            ReadOnlyCollection<CatalogNode> collectionNodes = cs.CatalogNode.QueryChildren(
                new[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            _collectionNodes = collectionNodes;
        }
        private static async Task<bool> CanLogIn(string username, string password, string uri, string configType)
        {
            bool response = false;

            HttpClientHandler httpClientHandler = null;
            // VSO check
            if (configType == "VSO")
            {
                using (var client = CreateAuthenticationClient(uri, username, password))
                {
                    client.BaseAddress = new Uri(uri);
                    
                    Debug.WriteLine("Code: " + client.GetAsync("").Result.StatusCode);
                    response = client.GetAsync("").Result.StatusCode == HttpStatusCode.OK;
                }
            }
            // TFS check
            else if (configType == "TFS")
            {
                var credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(username, password)));
                var server = new TfsConfigurationServer(new Uri(uri), credentials);
                try
                {
                    server.EnsureAuthenticated();
                }
                catch (TeamFoundationServerUnauthorizedException e)
                {
                    return false;
                }
                response = server.HasAuthenticated;
            }
            return response;
        }
Exemple #57
0
        private void Test()
        {
            TfsConfigurationServer configServer = new TfsConfigurationServer(
                new Uri("https://cmr.wkglobal.com:8088/tfs"),
                new NetworkCredential("Shafqat.Ahmed", "Hello123", "NA"));
            configServer.Authenticate();

            var catalog = configServer.CatalogNode;
            var tpcNodes = catalog.QueryChildren(
                new Guid[] { CatalogResourceTypes.ProjectCollection },
                false, CatalogQueryOptions.None);

            TfsTeamProjectCollection collection = null;
            foreach (var tpcNode in tpcNodes)
            {
                Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
                var tpc = configServer.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)
                {
                    if (p.Resource.DisplayName == "AML_Module")
                    {
                        collection = tpc;
                    }
                }
            }

            WorkItemStore workItemStore = (WorkItemStore) collection.GetService(typeof(WorkItemStore));
            string qry = "SELECT [Title] From WorkItems Where [Work Item Type] = 'Bug' "  +
                " AND [Iteration Path] = 'AML_Module\\Release 3\\Sprint 4' AND [Team Project]='AML_Module'";

            var res = workItemStore.Query (qry);
            foreach ( var wi in res)
            {
                string s = wi.ToString();
            }
        }
Exemple #58
0
        /// <summary>
        /// The get catalog nodes.
        /// </summary>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <returns>
        /// The <see cref="List"/>.
        /// </returns>
        private List<CatalogNode> GetCatalogNodes(Uri uri, ICredentials cred, bool anotherUser)
        {
            List<CatalogNode> catalogNodes = null;
            try
            {

                connectUri = uri;
                TfsClientCredentials tfsClientCredentials;
                if (anotherUser)
                {
                    
                    tfsClientCredentials = new TfsClientCredentials(false);
                    ICredentialsProvider provider = new UICredentialsProvider();
                    WindowsCredential wcred = new WindowsCredential(cred, provider);
                    tfsClientCredentials.Windows = wcred;
                    //Credential = tfsClientCredentials;
                }
                else
                {
                    tfsClientCredentials = new TfsClientCredentials(true);
                    ICredentialsProvider provider = new UICredentialsProvider();
                    WindowsCredential wcred = new WindowsCredential(cred, provider);
                    tfsClientCredentials.Windows = wcred;
                }

                using (TfsConfigurationServer serverConfig = new TfsConfigurationServer(uri, tfsClientCredentials))
                {
                    serverConfig.EnsureAuthenticated();
                    if (serverConfig.HasAuthenticated)
                    {
                        Credential = serverConfig.Credentials;
                        catalogNodes = serverConfig.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None).OrderBy(f => f.Resource.DisplayName).ToList();
                    }
                }
            }
            catch (TeamFoundationServiceUnavailableException ex)
            {
                MessageBox.Show(ResourceHelper.GetResourceString("MSG_TFS_SERVER_IS_INACCESSIBLE") + "\n" + uri.OriginalString, ResourceHelper.GetResourceString("ERROR_TEXT"), MessageBoxButton.OK, MessageBoxImage.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ResourceHelper.GetResourceString("ERROR_TEXT"), MessageBoxButton.OK, MessageBoxImage.Error);
                return catalogNodes;
            }

            return catalogNodes;
        }
 public TfsTeamProjectCollection tfsTeamProjectCollectionConfigServer(TfsConfigurationServer configurationServer, Guid collectionId)
 {
     TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
     return teamProjectCollection;
 }
        public void Connect(Uri tfsUri)
        {
            var projectCollectionName = tfsUri.Segments[tfsUri.Segments.Length - 1];
            var tfsConnection = tfsUri.AbsoluteUri.Substring(0, tfsUri.AbsoluteUri.Length - projectCollectionName.Length);

            m_configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(tfsConnection));
            //m_configurationServer.Connect(ConnectOptions.IncludeServices);

            CatalogNode configurationServerNode = m_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)
            {
                if (tpcNode.Resource.DisplayName.ToUpper() == GetWithoutTralingSlash(projectCollectionName).ToUpper())
                {
                    Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);
                    TfsTeamProjectCollection tpc = m_configurationServer.GetTeamProjectCollection(tpcId);                
                    m_versionControlServer = tpc.GetService<VersionControlServer>();   
                    break;
                }
            }
            if (m_versionControlServer == null)
            {
                throw new Exception(string.Format("Project collection name '{0}' not found",projectCollectionName));
            }
        }