コード例 #1
0
 public MyTfsProjectCollection(MyTfsServer myTfsServer, CatalogNode teamProjectCollectionNode)
 {
     try
     {
         _myTfsServer = myTfsServer;
         Name         = teamProjectCollectionNode.Resource.DisplayName;
         ServiceDefinition tpcServiceDefinition = teamProjectCollectionNode.Resource.ServiceReferences["Location"];
         var configLocationService = myTfsServer.GetConfigLocationService();
         var tpcUri = new Uri(configLocationService.LocationForCurrentConnection(tpcServiceDefinition));
         _tfsTeamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tpcUri);
         _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;
     }
 }
コード例 #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 IList <DeliveryPipeline> GetPipelines()
        {
            IList <DeliveryPipeline> pipelines = new List <DeliveryPipeline>();

            Uri collectionUri = new Uri(Uri);

            ProjectCollection = new TfsTeamProjectCollection(collectionUri);

            BuildServer            = ProjectCollection.GetService <IBuildServer>();
            CommonStructureService = ProjectCollection.GetService <ICommonStructureService>();
            Registration           = ProjectCollection.GetService <IRegistration>();
            VersionControlServer   = ProjectCollection.GetService <VersionControlServer>();
            ClientHyperlinkService = ProjectCollection.GetService <TswaClientHyperlinkService>();

            Name = ProjectCollection.CatalogNode.Resource.DisplayName;

            if (BuildServer.BuildServerVersion.ToString() == "v3")
            {
                TfsVersion = 2010;
            }
            else
            {
                TfsVersion = 2012;
            }

            foreach (ProjectInfo project in CommonStructureService.ListProjects())
            {
                foreach (IBuildDefinition definition in BuildServer.QueryBuildDefinitions(project.Name))
                {
                    if (definition.Process.ServerPath.Contains("BuildProcessTemplates/PowerDelivery"))
                    {
                        IDictionary <string, object> processParams = WorkflowHelpers.DeserializeProcessParameters(definition.ProcessParameters);

                        if (processParams.ContainsKey("PowerShellScriptPath"))
                        {
                            string scriptPath = processParams["PowerShellScriptPath"] as string;

                            string scriptName = System.IO.Path.GetFileNameWithoutExtension(scriptPath.Substring(scriptPath.LastIndexOf("/")));

                            string environmentName = definition.Name.Substring(definition.Name.LastIndexOf(" - ") + 3);

                            DeliveryPipeline pipeline = pipelines.FirstOrDefault(p => p.ScriptName == scriptName);

                            if (pipeline == null)
                            {
                                pipeline = new DeliveryPipeline(this, project, scriptName);
                                pipelines.Add(pipeline);
                            }

                            PipelineEnvironment environment = new PipelineEnvironment(pipeline, environmentName, definition);

                            pipeline.Environments.Add(environment);
                        }
                    }
                }
            }

            return(pipelines);
        }
コード例 #4
0
 public TfsBuildStatusPoll(IBuildServer buildServer, IDeployerFactory deployerFactory)
 {
     _buildServer      = buildServer;
     _deployerFactory  = deployerFactory;
     _webAccessLinks   = _buildServer.TeamProjectCollection.GetService <TswaClientHyperlinkService>();
     _structureService = _buildServer.TeamProjectCollection.GetService <ICommonStructureService>();
     _timer            = new Timer(state => PollBuildQualityChanges());
 }
コード例 #5
0
ファイル: TfsIssue.cs プロジェクト: LimpingNinja/bmx-tfs
 public TfsIssue(WorkItem workItem, HashSet<string> closedStates, TswaClientHyperlinkService hyperlinkService)
 {
     this.Id = workItem.Id;
     this.Title = workItem.Title;
     this.Description = workItem.Description;
     this.Status = workItem.State;
     this.SubmittedDate = EnsureUtc(workItem.CreatedDate);
     this.Submitter = workItem.CreatedBy;
     this.IsClosed = closedStates.Contains(workItem.State);
     this.Url = hyperlinkService.GetWorkItemEditorUrl(workItem.Id).AbsoluteUri;
 }
コード例 #6
0
ファイル: TfsIssue.cs プロジェクト: elvza/bmx-tfs
 public TfsIssue(WorkItem workItem, string[] closedStates, TswaClientHyperlinkService hyperlinkService)
 {
     this.Id            = workItem.Id;
     this.Type          = workItem.Type.Name;
     this.Title         = workItem.Title;
     this.Description   = workItem.Description;
     this.Status        = workItem.State;
     this.SubmittedDate = EnsureUtc(workItem.CreatedDate);
     this.Submitter     = workItem.CreatedBy;
     this.IsClosed      = closedStates.Contains(workItem.State, StringComparer.OrdinalIgnoreCase);
     this.Url           = hyperlinkService.GetWorkItemEditorUrl(workItem.Id).AbsoluteUri;
 }
コード例 #7
0
        /// <summary>
        /// The constructor sets up build service based on server key
        /// </summary>
        /// <param name="tfsserverKey"></param>
        public TFSBuildService(string tfsserverKey)
        {
            var tfs = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(tfsserverKey));

            this._buildServer           = tfs.GetService <IBuildServer>();
            this._versionControlServer  = tfs.GetService <VersionControlServer>();
            this._testManagementService = tfs.GetService <ITestManagementService>();
            _httpServiceTfs             = tfs.GetService <TswaClientHyperlinkService>();
            var tp = _versionControlServer.GetTeamProject(@"AllWG");

            pathofTeamProject = tp.ServerItem;
        }
コード例 #8
0
ファイル: TfsIssue.cs プロジェクト: mwpnl/bmx-tfs
 public TfsIssue(WorkItem workItem, string[] closedStates, TswaClientHyperlinkService hyperlinkService)
 {
     this.Id = workItem.Id;
     this.Type = workItem.Type.Name;
     this.Title = workItem.Title;
     this.Description = workItem.Description;
     this.Status = workItem.State;
     this.SubmittedDate = EnsureUtc(workItem.CreatedDate);
     this.Submitter = workItem.CreatedBy;
     this.IsClosed = closedStates.Contains(workItem.State, StringComparer.OrdinalIgnoreCase);
     this.Url = hyperlinkService.GetWorkItemEditorUrl(workItem.Id).AbsoluteUri;
 }
コード例 #9
0
        private async Task <WorkItemTrackingHttpClient> ConnectToTFS(Uri collectionUri) // Supressed the no await warning
        {
            VssConnection connection = new VssConnection(collectionUri, new VssClientCredentials());

            using (TfsTeamProjectCollection collection = new TfsTeamProjectCollection(collectionUri, new VssClientCredentials()))
            {
                collection.EnsureAuthenticated();
                this.hyperLinkService =
                    collection.GetService <TswaClientHyperlinkService>();
            }

            return(connection.GetClient <WorkItemTrackingHttpClient>());
        }
コード例 #10
0
		protected override void OnCreateMockObjects()
		{
			base.OnCreateMockObjects();
			MockCredentials = new Mock<ICredentials>();
			Credentials = MockCredentials.Object;
			BasicAuthCredential = new BasicAuthCredential(Credentials);
			TfsClientCredentials = new TfsClientCredentials(BasicAuthCredential);
			TfsClientCredentials.AllowInteractive = false;

			MockProjectCollection = new Mock<TfsTeamProjectCollection>(new Uri("http://localhost"), Credentials);
			ProjectCollection = MockProjectCollection.Object;

			ProjectHyperlinkService = null;
			WorkItemStore = null;
			TFSUsers = new List<Microsoft.TeamFoundation.Server.Identity>();
		}
コード例 #11
0
        protected override void OnCreateMockObjects()
        {
            base.OnCreateMockObjects();
            MockCredentials      = new Mock <ICredentials>();
            Credentials          = MockCredentials.Object;
            BasicAuthCredential  = new BasicAuthCredential(Credentials);
            TfsClientCredentials = new TfsClientCredentials(BasicAuthCredential);
            TfsClientCredentials.AllowInteractive = false;

            MockProjectCollection = new Mock <TfsTeamProjectCollection>(new Uri("http://localhost"), Credentials);
            ProjectCollection     = MockProjectCollection.Object;

            ProjectHyperlinkService = null;
            WorkItemStore           = null;
            TFSUsers = new List <Microsoft.TeamFoundation.Server.Identity>();
        }
コード例 #12
0
	    public Tfs(IBoardSubscriptionManager subscriptions,
	               IConfigurationProvider<Configuration> configurationProvider,
	               ILocalStorage<AppSettings> localStorage,
	               ILeanKitClientFactory leanKitClientFactory,
	               ICredentials projectCollectionNetworkCredentials,
	               BasicAuthCredential basicAuthCredential,
	               TfsClientCredentials tfsClientCredentials,
	               TfsTeamProjectCollection projectCollection,
				   TswaClientHyperlinkService projectHyperlinkService,
	               WorkItemStore projectCollectionWorkItemStore, 
                   List<Microsoft.TeamFoundation.Server.Identity> tfsUsers)
		    : base(subscriptions, configurationProvider, localStorage, leanKitClientFactory)
	    {
		    _projectCollectionNetworkCredentials = projectCollectionNetworkCredentials;
		    _projectCollection = projectCollection;
		    _projectHyperlinkService = projectHyperlinkService;
		    _projectCollectionWorkItemStore = projectCollectionWorkItemStore;
		    _basicAuthCredential = basicAuthCredential;
		    _tfsClientCredentials = tfsClientCredentials;
	        _tfsUsers = tfsUsers;
	    }
コード例 #13
0
 public Tfs(IBoardSubscriptionManager subscriptions,
            IConfigurationProvider <Configuration> configurationProvider,
            ILocalStorage <AppSettings> localStorage,
            ILeanKitClientFactory leanKitClientFactory,
            ICredentials projectCollectionNetworkCredentials,
            BasicAuthCredential basicAuthCredential,
            TfsClientCredentials tfsClientCredentials,
            TfsTeamProjectCollection projectCollection,
            TswaClientHyperlinkService projectHyperlinkService,
            WorkItemStore projectCollectionWorkItemStore,
            List <Microsoft.TeamFoundation.Server.Identity> tfsUsers)
     : base(subscriptions, configurationProvider, localStorage, leanKitClientFactory)
 {
     _projectCollectionNetworkCredentials = projectCollectionNetworkCredentials;
     _projectCollection              = projectCollection;
     _projectHyperlinkService        = projectHyperlinkService;
     _projectCollectionWorkItemStore = projectCollectionWorkItemStore;
     _basicAuthCredential            = basicAuthCredential;
     _tfsClientCredentials           = tfsClientCredentials;
     _tfsUsers = tfsUsers;
 }
コード例 #14
0
        private void ConnectToTfs(CommandLineOptions options)
        {
            Log(string.Format(CultureInfo.InvariantCulture, "Connecting to Tfs at {0}...", options.TfsServerUrl));

            // Connect to Team Foundation Server
            Uri tfsUri = new Uri(options.TfsServerUrl);
            _teamProjectCollection = new TfsTeamProjectCollection(tfsUri);

            _linkService = _teamProjectCollection.GetService<TswaClientHyperlinkService>();
            _workItemStore = _teamProjectCollection.GetService<WorkItemStore>();
            _tfsProject = _workItemStore.Projects[options.TfsProject];

            if (options.TfsQuery == null)
            {
                _tfsQueryFolder = _tfsProject.QueryHierarchy[options.TfsQueryHierarchy] as QueryFolder;
                _tfsQueryItem = _tfsQueryFolder[options.TfsQueryName];
            }
            else
            {
                _tfsQueryItem = options.TfsQuery;
            }
        }
コード例 #15
0
        public ActionResult Search(string id, string search)
        {
            try
            {
                ItemWidgetArguments args = new ItemWidgetArguments(UserContext, GeminiContext, Cache, System.Web.HttpContext.Current.Request, CurrentIssue);

                TFSPicker tfsPicker = new TFSPicker();

                tfsPicker.AuthenticateUser(args);

                UserWidgetDataDetails loginDetails = tfsPicker.getLoginDetails();

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

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

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

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

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

                configurationServer.Credentials = iCred;

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

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

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

                CatalogNode catalogNode = configurationServer.CatalogNode;

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

                string url = string.Empty;

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

                TfsTeamProjectCollection tpc = null;

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

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

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

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

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

                    var result = workItemStore.Query(query);

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

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

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

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

                            queryResults.Add(item);
                        }
                    }
                }

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

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

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

                        data.AppId = Constants.AppId;

                        data.ControlId = Constants.ControlId;

                        data.IssueId = id.ToInt();

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

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

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

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

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

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

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

                successView = false;

                messageView = ex.Message;

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

            return(JsonSuccess(new { success = successView, data = dataView, message = messageView }));
        }
コード例 #16
0
        public override void Init()
        {
            if (Configuration == null) return;

	        try
	        {
		        _projectCollectionUri = new Uri(Configuration.Target.Url);
	        }
	        catch (UriFormatException ex)
	        {
		        Log.Error("Error connection to TFS. Ensure the Target Host is a valid URL: {0} - {1}", ex.GetType(), ex.Message);
		        return;
	        }

            Log.Info("Connecting to TFS...");
            //This is used to query TFS for new WorkItems
            try
            {
	            if (_projectCollectionNetworkCredentials == null)
	            {			
					// if this is hosted TFS then we need to authenticate a little different
					// see this for setup to do on visualstudio.com site:
					// http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx
		            if (_projectCollectionUri.Host.ToLowerInvariant().Contains(".visualstudio.com"))
		            {
			            _projectCollectionNetworkCredentials = new NetworkCredential(Configuration.Target.User, Configuration.Target.Password);

			            if (_basicAuthCredential == null)
				            _basicAuthCredential = new BasicAuthCredential(_projectCollectionNetworkCredentials);

			            if (_tfsClientCredentials == null)
			            {
				            _tfsClientCredentials = new TfsClientCredentials(_basicAuthCredential);
				            _tfsClientCredentials.AllowInteractive = false;
			            }

			            if (_projectCollection == null)
			            {
				            _projectCollection = new TfsTeamProjectCollection(_projectCollectionUri, _tfsClientCredentials);
							_projectHyperlinkService = _projectCollection.GetService<TswaClientHyperlinkService>();
				            _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);
			            }
		            }
		            else
		            {
                        // Check for common NTLM/Windows Auth convention
                        // ("DOMAIN\Username") in User input and separate 
                        // domain from username:
                        string domain = null;
                        string username = null;
                        if (Configuration.Target.User.Contains("\\"))
                        {
                            string[] domainUser = Configuration.Target.User.Split('\\');
                            domain = domainUser[0];
                            username = domainUser[1];
                        }
                        if (domain != null)
                        {
                            Log.Debug("Logging in using NTLM auth (using domain: {0}, username: {1})", domain, username);
						    _projectCollectionNetworkCredentials = new NetworkCredential(username, Configuration.Target.Password, domain);
                        }
                        else
                        {
						    _projectCollectionNetworkCredentials = new NetworkCredential(Configuration.Target.User, Configuration.Target.Password);
                        }
			            if (_projectCollection == null)
			            {
				            _projectCollection = new TfsTeamProjectCollection(_projectCollectionUri, _projectCollectionNetworkCredentials);
				            _projectHyperlinkService = _projectCollection.GetService<TswaClientHyperlinkService>();
				            _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);
			            }
		            }
	            }

                if (_projectCollectionWorkItemStore == null)
					_projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);

                if (_projectCollection != null && _tfsUsers == null)
                    LoadTfsUsers();

            }
            catch (Exception e)
            {
                Log.Error("Error connecting to TFS: {0} - {1}", e.GetType(), e.Message);
            }

	        // per project, if exclusions are defined, build type filter to exclude them
            foreach (var mapping in Configuration.Mappings)
            {
                mapping.ExcludedTypeQuery = "";
                if (mapping.Excludes == null) continue;
                var excludedTypes = mapping.Excludes.Split(',');
                Log.Debug("Excluded WorkItemTypes for [{0}]:", mapping.Identity.Target);
                foreach (var type in excludedTypes)
                {
                    var trimmedType = type.Trim();
                    Log.Debug(">> [{0}]", trimmedType);
                    mapping.ExcludedTypeQuery += String.Format(" AND [System.WorkItemType] <> '{0}'", trimmedType);
                }
            }
        }
コード例 #17
0
        public override void Init()
        {
            if (Configuration == null)
            {
                return;
            }

            try
            {
                _projectCollectionUri = new Uri(Configuration.Target.Url);
            }
            catch (UriFormatException ex)
            {
                Log.Error("Error connection to TFS. Ensure the Target Host is a valid URL: {0} - {1}", ex.GetType(), ex.Message);
                return;
            }

            Log.Info("Connecting to TFS...");
            //This is used to query TFS for new WorkItems
            try
            {
                if (_projectCollectionNetworkCredentials == null)
                {
                    // if this is hosted TFS then we need to authenticate a little different
                    // see this for setup to do on visualstudio.com site:
                    // http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx
                    if (_projectCollectionUri.Host.ToLowerInvariant().Contains(".visualstudio.com"))
                    {
                        _projectCollectionNetworkCredentials = new NetworkCredential(Configuration.Target.User, Configuration.Target.Password);

                        if (_basicAuthCredential == null)
                        {
                            _basicAuthCredential = new BasicAuthCredential(_projectCollectionNetworkCredentials);
                        }

                        if (_tfsClientCredentials == null)
                        {
                            _tfsClientCredentials = new TfsClientCredentials(_basicAuthCredential);
                            _tfsClientCredentials.AllowInteractive = false;
                        }

                        if (_projectCollection == null)
                        {
                            _projectCollection              = new TfsTeamProjectCollection(_projectCollectionUri, _tfsClientCredentials);
                            _projectHyperlinkService        = _projectCollection.GetService <TswaClientHyperlinkService>();
                            _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);
                        }
                    }
                    else
                    {
                        _projectCollectionNetworkCredentials = new NetworkCredential(Configuration.Target.User, Configuration.Target.Password);
                        if (_projectCollection == null)
                        {
                            _projectCollection              = new TfsTeamProjectCollection(_projectCollectionUri, _projectCollectionNetworkCredentials);
                            _projectHyperlinkService        = _projectCollection.GetService <TswaClientHyperlinkService>();
                            _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);
                        }
                    }
                }

                if (_projectCollectionWorkItemStore == null)
                {
                    _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);
                }

                if (_projectCollection != null && _tfsUsers == null)
                {
                    LoadTfsUsers();
                }
            }
            catch (Exception e)
            {
                Log.Error("Error connecting to TFS: {0} - {1}", e.GetType(), e.Message);
            }

            // per project, if exclusions are defined, build type filter to exclude them
            foreach (var mapping in Configuration.Mappings)
            {
                mapping.ExcludedTypeQuery = "";
                if (mapping.Excludes == null)
                {
                    continue;
                }
                var excludedTypes = mapping.Excludes.Split(',');
                Log.Debug("Excluded WorkItemTypes for [{0}]:", mapping.Identity.Target);
                foreach (var type in excludedTypes)
                {
                    var trimmedType = type.Trim();
                    Log.Debug(">> [{0}]", trimmedType);
                    mapping.ExcludedTypeQuery += String.Format(" AND [System.WorkItemType] <> '{0}'", trimmedType);
                }
            }
        }
コード例 #18
0
        public WorkItem GetItem(string id, out string url)
        {
            url = null;

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

            ICredentials iCred = new NetworkCredential(Username, Password);

            connect.setLoginDetails(Username, Password, RepositoryUrl);

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

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


            configurationServer.Credentials = iCred;

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

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

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

            CatalogNode catalogNode = configurationServer.CatalogNode;

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

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

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

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

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

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

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

                    return(item);
                }
            }

            return(null);
        }