Example #1
0
        public TfsSourceControlClient(string projectCollectionUrl, string userName, string password, string domain, ILogSink log)
        {
            var uri = new Uri(projectCollectionUrl, UriKind.Absolute);

            if (string.IsNullOrEmpty(userName))
            {
                this.collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
            }
            else
            {
                TfsClientCredentials credentials;
                if (string.IsNullOrEmpty(domain))
                {
                    credentials = new TfsClientCredentials(new BasicAuthCredential(new NetworkCredential(userName, password)));
                }
                else
                {
                    credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(userName, password, domain)));
                }

                this.collection = new TfsTeamProjectCollection(uri, credentials);
            }

            this.log = log;
        }
Example #2
0
        public static ITestManagementTeamProject GetProject(Uri tfsUri, string projectName, string username, string password)
        {
            try
            {
                Trace.TraceInformation($"Connecting to VSTS {tfsUri.AbsoluteUri}, Project: {projectName}");

                var networkCredential          = new NetworkCredential(username, password);
                BasicAuthCredential  basicCred = new BasicAuthCredential(networkCredential);
                TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);
                tfsCred.AllowInteractive = false;

                TfsTeamProjectCollection   projectsCollection = new TfsTeamProjectCollection(tfsUri, tfsCred);
                ITestManagementService     service            = (ITestManagementService)projectsCollection.GetService(typeof(ITestManagementService));
                ITestManagementTeamProject project            = service.GetTeamProject(projectName);

                Trace.TraceInformation($"project {projectName} found");

                return(project);
            }
            catch (TestObjectNotFoundException)
            {
                Trace.TraceError($"Project {projectName} not found");
                return(null);
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                return(null);
            }
        }
Example #3
0
        private TfsTeamProjectCollection GetTeamProjectCollection()
        {
            if (this.UseSystemCredentials)
            {
                var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(this.BaseUri);
                projectCollection.EnsureAuthenticated();
                return(projectCollection);
            }
            else
            {
                TfsClientCredentials credentials;

                if (string.IsNullOrEmpty(this.Domain))
                {
                    credentials = new TfsClientCredentials(new BasicAuthCredential(new NetworkCredential(this.UserName, this.Password)));
                }
                else
                {
                    credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(this.UserName, this.Password, this.Domain)));
                }

                var projectColleciton = new TfsTeamProjectCollection(this.BaseUri, credentials);
                projectColleciton.EnsureAuthenticated();
                return(projectColleciton);
            }
        }
Example #4
0
        // see http://msdn.microsoft.com/en-us/library/bb130306.aspx

        public void Connect()
        {
            if (this.Credential != null && !string.IsNullOrWhiteSpace(this.Credential.UserName))
            {
                if (IsVSO(this.CollectionUrl))
                {
                    // source http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx
                    BasicAuthCredential  basicCred = new BasicAuthCredential(this.Credential);
                    TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);
                    tfsCred.AllowInteractive = false;
                    this.Collection          = new TfsTeamProjectCollection(this.CollectionUrl, tfsCred);
                }
                else
                {
                    this.Collection = new TfsTeamProjectCollection(this.CollectionUrl, this.Credential);
                }//if
            }
            else
            {
                if (IsVSO(this.CollectionUrl))
                {
                    throw new SecurityException("VSO requires user and password");
                }
                else
                {
                    this.Collection = new TfsTeamProjectCollection(this.CollectionUrl);
                }
            }
            this.Collection.EnsureAuthenticated();
        }
        private TfsTeamProjectCollection TfsConnect()
        {
            try
            {
                // Determine if local TFS or VSTS

                if ((!AccountURL.ToLower().Contains("https")) || AccountURL.ToLower().Contains("8080"))
                {
                    // Authenticate to on-premises TFS

                    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(AccountURL));
                    tpc.EnsureAuthenticated();
                    return(tpc);
                }
                else
                {
                    // Authenticate to VSTS

                    NetworkCredential    netCred   = new NetworkCredential(MicrosoftAccountAlias, MicrosoftAccountPassword);
                    BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
                    TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);
                    tfsCred.AllowInteractive = false;
                    TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(AccountURL), tfsCred);
                    tpc.Authenticate();
                    return(tpc);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                throw;
            }
        }
Example #6
0
        public static TfsTeamProjectCollection GetTeamProjectCollection(Uri tfsCollectionUri, ITfsCredentials tfsCredentials)
        {
            TfsTeamProjectCollection result;

            TfsClientCredentials credential = null;

            if (tfsCredentials != null)
            {
                credential = tfsCredentials.GetCredentials();
            }
            else
            {
                if (Defaults.GetDefaultCredentials(tfsCollectionUri) != null)
                {
                    credential = Defaults.GetDefaultCredentials(tfsCollectionUri).GetCredentials();
                }
            }

            if (credential != null)
            {
                result = new TfsTeamProjectCollection(tfsCollectionUri, credential);

                result.Connect(ConnectOptions.IncludeServices);
            }
            else
            {
                result = new TfsTeamProjectCollection(tfsCollectionUri);
            }

            return(result);
        }
Example #7
0
        private TfsTeamProjectCollection ConnectAndCacheCredentials()
        {
            Uri serverUri = null;

            try
            {
                serverUri = new Uri(tbServer.Text);
            }
            catch (FormatException ex)
            {
                MessageBox.Show(this, "Invalid server URL: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
            TfsClientCredentials     cred      = GetCredentials(serverUri);
            TfsTeamProjectCollection cfgServer = new TfsTeamProjectCollection(serverUri, cred);

            try
            {
                cfgServer.Connect(ConnectOptions.IncludeServices);
                return(cfgServer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Cannot login: "******"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
Example #8
0
        /// <summary>
        /// Get the parameters of the test case
        /// </summary>
        /// <param name="testCaseId">Test case id (work item id#) displayed into TFS</param>
        /// <returns>Returns the test case parameters in datatable format. If there are no parameters then it will return null</returns>
        public static DataTable GetTestCaseParameters(int testCaseId)
        {
            ITestManagementService TestMgrService;
            ITestCase TestCase = null;
            DataTable TestCaseParameters = null;

            NetworkCredential netCred = new NetworkCredential(
              Constants.TFS_USER_NAME,
              Constants.TFS_USER_PASSWORD);
            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(
                new Uri(Constants.TFS_URL),
                tfsCred);

            teamProjectCollection.Authenticate();

            TestMgrService = teamProjectCollection.GetService<ITestManagementService>();
            TestCase = TestMgrService.GetTeamProject(Constants.TFS_PROJECT_NAME).TestCases.Find(testCaseId);

            if (TestCase != null)
            {
                if (TestCase.Data.Tables.Count > 0)
                {
                    TestCaseParameters = TestCase.Data.Tables[0];
                }
            }

            return TestCaseParameters;
        }
Example #9
0
        /// <inheritdoc/>
        public async Task ConfigureAsync(TfsServiceProviderConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if(string.IsNullOrEmpty(configuration.WorkItemType))
            {
                throw new ArgumentNullException(nameof(configuration.WorkItemType));
            }

            this.logger.Debug("Configure of TfsSoapServiceProvider started...");
            var networkCredential = new NetworkCredential(configuration.Username, configuration.Password);
            var tfsClientCredentials = new TfsClientCredentials(new BasicAuthCredential(networkCredential)) { AllowInteractive = false };
            var tfsProjectCollection = new TfsTeamProjectCollection(this.serviceUri, tfsClientCredentials);
            this.workItemType = configuration.WorkItemType;
            tfsProjectCollection.Authenticate();
            tfsProjectCollection.EnsureAuthenticated();
            this.logger.Debug("Authentication successful for {serviceUri}.", this.serviceUri.AbsoluteUri);

            await Task.Run(
                () =>
                    {
                        this.logger.Debug("Fetching workitem for id {parentWorkItemId}.", configuration.ParentWorkItemId);
                        this.workItemStore = new WorkItemStore(tfsProjectCollection);
                        this.parentWorkItem = this.workItemStore.GetWorkItem(configuration.ParentWorkItemId);
                        this.logger.Debug("Found parent work item '{title}'.", this.parentWorkItem.Title);
                    });
            this.logger.Verbose("Tfs service provider configuration complete.");
        }
Example #10
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);
        }
Example #11
0
        protected TfsConfigurationServer GetServer()
        {
            ICredentials         credentials    = new NetworkCredential(Principal.Login, Principal.Password, Principal.Domain);
            TfsClientCredentials tfsCredentials = new TfsClientCredentials(new WindowsCredential(credentials), new SimpleWebTokenCredential(null, null), false);

            return(new TfsConfigurationServer(new Uri(Principal.Url), tfsCredentials));
        }
        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);
        }
		public ConnectionResult Connect(string host, string user, string password)
		{
			string.Format("Connecting to TFS '{0}'", host).Debug();

			try
			{
				_projectCollectionUri = new Uri(host);
			}
			catch (UriFormatException ex)
			{
				string.Format("Invalid project URL '{0}': {1}", host, ex.Message).Error();
				return ConnectionResult.InvalidUrl;
			}

			//This is used to query TFS for new WorkItems
			try
			{
				if (_projectCollectionNetworkCredentials == null)
				{
					_projectCollectionNetworkCredentials = new NetworkCredential(user, password);

					// 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"))
					{

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

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

					}
					if (_projectCollection == null)
					{
						_projectCollection = _tfsClientCredentials != null
							? new TfsTeamProjectCollection(_projectCollectionUri, _tfsClientCredentials)
							: new TfsTeamProjectCollection(_projectCollectionUri, _projectCollectionNetworkCredentials);
					}
					_projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);

				}

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

			}
			catch (Exception e)
			{
				string.Format("Failed to connect: {0}", e.Message).Error(e);
				return ConnectionResult.FailedToConnect;
			}

			return ConnectionResult.Success;
		}
Example #14
0
        public ConnectionResult Connect(string host, string user, string password)
        {
            string.Format("Connecting to TFS '{0}'", host).Debug();

            try
            {
                _projectCollectionUri = new Uri(host);
            }
            catch (UriFormatException ex)
            {
                string.Format("Invalid project URL '{0}': {1}", host, ex.Message).Error();
                return(ConnectionResult.InvalidUrl);
            }

            //This is used to query TFS for new WorkItems
            try
            {
                if (_projectCollectionNetworkCredentials == null)
                {
                    _projectCollectionNetworkCredentials = new NetworkCredential(user, password);

                    // 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"))
                    {
                        if (_basicAuthCredential == null)
                        {
                            _basicAuthCredential = new BasicAuthCredential(_projectCollectionNetworkCredentials);
                        }

                        if (_tfsClientCredentials == null)
                        {
                            _tfsClientCredentials = new TfsClientCredentials(_basicAuthCredential);
                            _tfsClientCredentials.AllowInteractive = false;
                        }
                    }
                    if (_projectCollection == null)
                    {
                        _projectCollection = _tfsClientCredentials != null
                                                        ? new TfsTeamProjectCollection(_projectCollectionUri, _tfsClientCredentials)
                                                        : new TfsTeamProjectCollection(_projectCollectionUri, _projectCollectionNetworkCredentials);
                    }
                    _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);
                }

                if (_projectCollectionWorkItemStore == null)
                {
                    _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection);
                }
            }
            catch (Exception e)
            {
                string.Format("Failed to connect: {0}", e.Message).Error(e);
                return(ConnectionResult.FailedToConnect);
            }

            return(ConnectionResult.Success);
        }
        public TfsTeamProjectCollection Authorize(IDictionary<string, string> authorizeInformation)
        {
            var tfsCredentials = new TfsClientCredentials();
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(this.tfsUri));

            tfs.Authenticate();
            return tfs;
        }
Example #16
0
        public void Connect()
        {
            NetworkCredential    netCred   = new NetworkCredential(m_username, m_password);
            BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            m_tpc = new TfsTeamProjectCollection(new Uri(m_url), tfsCred);
        }
Example #17
0
File: TFS.cs Project: Eun/TFSMonkey
        public TFS(Uri server, NetworkCredential credential)
        {
            BasicAuthCredential basicCred = new BasicAuthCredential(credential);
            var tfsCred = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive      = false;
            _connection.ClientCredentials = tfsCred;
            Initialize(server, tfsCred);
        }
Example #18
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);
        }
Example #19
0
		public TfsClient(string url)
		{
			if (String.IsNullOrEmpty(url))
				throw new ArgumentNullException(nameof(url));

			var credentials = new TfsClientCredentials();
			var collection = new TfsTeamProjectCollection(new Uri(url), credentials);

			m_server = collection.GetService<VersionControlServer>();
		}
Example #20
0
		public static void Main(string[] args)
		{
			var tfsUrl = "http://rufc-devbuild.cneu.cnwk:8080/tfs/sed";
			//var tfs = new TfsClient(tfsUrl);

			var credentials = new TfsClientCredentials();
			var collection = new TfsTeamProjectCollection(new Uri(tfsUrl), credentials);

			var server = collection.GetService<VersionControlServer>();
			var test = GetChildItems(server);
		}
Example #21
0
        public void Initialize(BuildConfig config)
        {
            NetworkCredential credentials = new NetworkCredential(config.Username, config.Password);
            BasicAuthCredential basicCredentials = new BasicAuthCredential(credentials);
            TfsClientCredentials cred = new TfsClientCredentials(basicCredentials);
            cred.AllowInteractive = false;
            tpc = new TfsTeamProjectCollection(new Uri(config.SourceUrl + "/" + config.Collection),cred);

            tpc.Authenticate();

            this.Server = tpc.GetService<Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer>();
        }
        public TfsClient(string url)
        {
            if (String.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            var credentials = new TfsClientCredentials();
            var collection  = new TfsTeamProjectCollection(new Uri(url), credentials);

            m_server = collection.GetService <VersionControlServer>();
        }
Example #23
0
        /// <summary>
        ///		Conecta a un servidor
        /// </summary>
        public void Connect()
        {
            WindowsCredential    objWindowsCredentials = new WindowsCredential(new NetworkCredential(User.Login, User.Pasword));
            TfsClientCredentials objCredentials        = new TfsClientCredentials(objWindowsCredentials);

            // Cierra la conexión
            Close();
            // Crea una conexión
            tfsTeamProject = new TfsTeamProjectCollection(Server.FullUrl, objCredentials);
            // Autentifica
            tfsTeamProject.Authenticate();
        }
Example #24
0
        /// <summary>
        /// Prevents a default instance of the <see cref="TfsProjects"/> class from being created.
        /// This might change if the project name can be optional.
        /// </summary>
        public TfsProjects(string tfsUri, string username, string password, string projectName = null)
        {
            NetworkCredential netCred = new NetworkCredential(username, password);

            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(tfsUri), tfsCred);
            ProjectCollection.Authenticate();

            Store = new WorkItemStore(ProjectCollection);
            ProjectName = projectName;
        }
Example #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TfsProjects"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="projectName">Name of the project.</param>
        public TfsProjects(ITfsContext context)
        {
            NetworkCredential netCred = new NetworkCredential(context.Username, context.Password);

            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(context.Uri), tfsCred);
            ProjectCollection.Authenticate();

            Store = new WorkItemStore(ProjectCollection);
            ProjectName = context.ProjectName;
        }
        public override void ExecuteCommand()
        {
            TfsClientCredentials cred = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(UserName, Password)), true);

            cred.AllowInteractive = true;
            tfs = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(HostUrl), cred);
            //Get data store that contains all workitems on a particular server
            store = tfs.GetService <WorkItemStore>();
            //Get particular Team Project
            project = store.Projects[ProjectName];
            Console.WriteLine("Connected to project: " + project.Name);
            CreatereportForSupportRequestsByCategory();
            CreatereportForSupportRequestSummary();
        }
Example #27
0
            public override TfsTeamProjectCollection GetCollection(Uri tfsCollectionUri)
            {
#if TFS2017
                var tfsCred = new VssCredentials(
                    new VssBasicCredential(
                        new System.Net.NetworkCredential(this.username, this.password)));
#else
                var tfsCred = new TfsClientCredentials(
                    new BasicAuthCredential(
                        new System.Net.NetworkCredential(this.username, this.password)));
                tfsCred.AllowInteractive = false;
#endif
                return(new TfsTeamProjectCollection(tfsCollectionUri, tfsCred));
            }
        internal static TfsClientCredentialsWrapper GetInstance()
        {
            var real = new TfsClientCredentials();

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

            InstanceFactory(ref instance);
            if (instance == null)
            {
                Assert.Inconclusive("Could not Create Test Instance");
            }
            return(instance);
        }
Example #29
0
        private static TfsTeamProjectCollection ConnectToTfsCollection(
            Uri endpoint,
            TfsClientCredentials credentials)
        {
            var tfsServer = new TfsTeamProjectCollection(endpoint, credentials);

            tfsServer.EnsureAuthenticated();

#if DEBUG
            // The base class TfsConnection integrates various information about the connect with TFS (as well as ways to control that connection)
            System.Diagnostics.Debug.Print($"Connected to {endpoint}");
            System.Diagnostics.Debug.Print($"Authenticated: {tfsServer.AuthorizedIdentity.Descriptor.Identifier}");
#endif
            return(tfsServer);
        }
        public static TfsTeamProjectCollection GetTeamProjectCollection(Uri collectionUri, out NetworkCredential credential)
        {
            string user     = ConfigurationManager.AppSettings["TfsClientUser"];
            string password = ConfigurationManager.AppSettings["TfsClientPassword"];

            credential = new NetworkCredential(user, password);
            BasicAuthCredential  basicCred = new BasicAuthCredential(credential);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive = false;
            TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(collectionUri, tfsCred);

            teamProjectCollection.Authenticate();
            return(teamProjectCollection);
        }
Example #31
0
        /// <summary>
        /// Prevents a default instance of the <see cref="TfsProjects"/> class from being created.
        /// This might change if the project name can be optional.
        /// </summary>
        public TfsProjects(string tfsUri, string username, string password, string projectName = null)
        {
            NetworkCredential netCred = new NetworkCredential(username, password);

            BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(tfsUri), tfsCred);
            ProjectCollection.Authenticate();

            Store       = new WorkItemStore(ProjectCollection);
            ProjectName = projectName;
        }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TfsProjects"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="projectName">Name of the project.</param>
        public TfsProjects(ITfsContext context)
        {
            NetworkCredential netCred = new NetworkCredential(context.Username, context.Password);

            BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);

            tfsCred.AllowInteractive = false;

            ProjectCollection = new TfsTeamProjectCollection(new Uri(context.Uri), tfsCred);
            ProjectCollection.Authenticate();

            Store       = new WorkItemStore(ProjectCollection);
            ProjectName = context.ProjectName;
        }
        internal static void CastNonGenericIEnumerable(TfsClientCredentials credentials)
        {
            using (TfsTeamProjectCollection projectCollection = new TfsTeamProjectCollection(
                       new Uri("https://dixin.visualstudio.com/DefaultCollection"), credentials))
            {
                const string       wiql          = "SELECT * FROM WorkItems WHERE [Work Item Type] = 'Bug' AND State != 'Closed'"; // WIQL does not support GROUP BY.
                WorkItemStore      workItemStore = (WorkItemStore)projectCollection.GetService(typeof(WorkItemStore));
                WorkItemCollection workItems     = workItemStore.Query(wiql);                                                      // WorkItemCollection implements IEnumerable.

                IEnumerable <IGrouping <string, WorkItem> > workItemGroups =
                    from WorkItem workItem in workItems
                    group workItem by workItem.CreatedBy;     // Group work items in local memory.
                // ...
            }
        }
Example #34
0
File: TFS.cs Project: Eun/TFSMonkey
        private void Initialize(Uri server, TfsClientCredentials credential)
        {
            _connection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(server);

            if (credential != null)
            {
                _connection.ClientCredentials = credential;
            }

            _connection.EnsureAuthenticated();

            _versionControlServer = _connection.GetService <VersionControlServer>();
            _linkingService       = _connection.GetService <ILinking>();
            Url = server.AbsoluteUri;
        }
Example #35
0
        /// <inheritdoc/>
        public async Task ConfigureAsync(TfsServiceProviderConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (string.IsNullOrEmpty(configuration.WorkItemType))
            {
                throw new ArgumentNullException(nameof(configuration.WorkItemType));
            }

            this.logger.Debug("Configure of TfsSoapServiceProvider started...");
            var networkCredential = new NetworkCredential(configuration.Username, configuration.Password);
            TfsClientCredentials tfsClientCredentials = new TfsClientCredentials(new BasicAuthCredential(networkCredential))
            {
                AllowInteractive = false
            };

            var tfsProjectCollection = new TfsTeamProjectCollection(this.serviceUri, tfsClientCredentials);

            this.workItemType = configuration.WorkItemType;

            try
            {
                tfsProjectCollection.Authenticate();
            }
            catch
            {
                tfsClientCredentials = new TfsClientCredentials(); // fall back to login page
                tfsProjectCollection = new TfsTeamProjectCollection(this.serviceUri, tfsClientCredentials);
                tfsProjectCollection.Authenticate();
            }

            tfsProjectCollection.EnsureAuthenticated();
            this.logger.Debug("Authentication successful for {serviceUri}.", this.serviceUri.AbsoluteUri);

            await Task.Run(
                () =>
            {
                this.logger.Debug("Fetching workitem for id {parentWorkItemId}.", configuration.ParentWorkItemId);
                this.workItemStore  = new WorkItemStore(tfsProjectCollection);
                this.parentWorkItem = this.workItemStore.GetWorkItem(configuration.ParentWorkItemId);
                this.logger.Debug("Found parent work item '{title}'.", this.parentWorkItem.Title);
            });

            this.logger.Verbose("Tfs service provider configuration complete.");
        }
		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>();
		}
        public static TfsTeamProjectCollection GetTeamProjectCollection(Server server)
        {
            if (string.IsNullOrEmpty(server.UserName) || string.IsNullOrEmpty(server.Password))
            {
                return new TfsTeamProjectCollection(server.Uri);
            }

            var tfsCredentials = new TfsClientCredentials(new BasicAuthCredential(new NetworkCredential(server.UserName, server.Password)))
            {
                AllowInteractive = false
            };

            var teamProjectCollection = new TfsTeamProjectCollection(server.Uri, tfsCredentials);

            return teamProjectCollection;
        }
        public TfsTeamProjectCollection Authorize(IDictionary<string, string> authorizeInformation)
        {
            NetworkCredential netCred = new NetworkCredential(
                "*****@*****.**",
                "yourbasicauthpassword");
            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
                new Uri("https://YourAccountName.visualstudio.com/DefaultCollection"),
                tfsCred);

            tpc.Authenticate();
            return tpc;
        }
        private static TfsTeamProjectCollection GetProjectCollection()
        {
            var networkCredential    = new NetworkCredential(tfsServiceProviderTestUser, tfsServiceProviderTestPassword);
            var tfsClientCredentials = new TfsClientCredentials(new BasicAuthCredential(networkCredential))
            {
                AllowInteractive = false
            };

            var tfsProjectCollection = new TfsTeamProjectCollection(
                new Uri(tfsServiceProviderUri),
                tfsClientCredentials);

            tfsProjectCollection.Authenticate();

            return(tfsProjectCollection);
        }
Example #40
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>();
        }
Example #41
0
            public override TfsTeamProjectCollection GetCollection(Uri tfsCollectionUri)
            {
                // username is not important, we use it to identify ourselves to callee
#if TFS2017
                var tfsCred = new VssCredentials(
                    new VssBasicCredential(
                        new System.Net.NetworkCredential(
                            "tfsaggregator2-webhooks", this.personalToken)));
#else
                var tfsCred = new TfsClientCredentials(
                    new BasicAuthCredential(
                        new System.Net.NetworkCredential(
                            "tfsaggregator2-webhooks", this.personalToken)));
                tfsCred.AllowInteractive = false;
#endif
                return(new TfsTeamProjectCollection(tfsCollectionUri, tfsCred));
            }
Example #42
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;
        }
Example #43
0
        public static void MyClassInitialize(TestContext testContext)
        {
            NetworkCredential networkCredential = new NetworkCredential(@"*****@*****.**","zippyd00da");
            BasicAuthToken basicAuthToken = new BasicAuthToken(networkCredential);
            BasicAuthCredential basicAuthCredential = new BasicAuthCredential(basicAuthToken);
            TfsClientCredentials tfsClientCredentials = new TfsClientCredentials(basicAuthCredential);
            tfsClientCredentials.AllowInteractive = false;

            server2 = new TfsTeamProjectCollection(new Uri("https://rdavis.visualstudio.com/DefaultCollection"), tfsClientCredentials);

            server2.Connect(Microsoft.TeamFoundation.Framework.Common.ConnectOptions.None);
            server2.EnsureAuthenticated();

            server2.Authenticate();

            if (!server2.HasAuthenticated)
                throw new InvalidOperationException("Not authenticated");

            store = new WorkItemStore(server2);
        }
	    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;
	    }
        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);
                }
            }
        }
		private static bool CheckTfsServerPath(string path, TfsClientCredentials credential)
		{
			TfsConfigurationServer tfsServer = null;
			try
			{
				tfsServer = new TfsConfigurationServer(new Uri(path), credential);
				tfsServer.Connect(ConnectOptions.None);
				return true;
			}
			catch
			{
				if (tfsServer != null)
					tfsServer.Dispose();
			}

			return false;
		}
        private static TfsTeamProjectCollection GetProjectCollection()
        {
            var networkCredential = new NetworkCredential(tfsServiceProviderTestUser, tfsServiceProviderTestPassword);
            var tfsClientCredentials = new TfsClientCredentials(new BasicAuthCredential(networkCredential))
                                           {
                                               AllowInteractive = false
                                           };

            var tfsProjectCollection = new TfsTeamProjectCollection(
                new Uri(tfsServiceProviderUri),
                tfsClientCredentials);
            tfsProjectCollection.Authenticate();

            return tfsProjectCollection;
        }
 private static async Task<bool> CanLogIn(string username, string password, string uri, string configType)
 {
     bool response = false;
     try
     {
         // 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);
             server.EnsureAuthenticated();
             response = server.HasAuthenticated;
         }
     }
     catch (Exception e)
     { 
         LogService.WriteError(e);
         throw;
     }
     return response;
 }
Example #49
0
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.Error.WriteLine("Expected exactly one argument, the file to annotate. " + args.Length + " given.");
                return 1;
            }

            String path = args[args.Length - 1];
            if (!File.Exists(path))
            {
                Console.Error.WriteLine("The given file does not exist: " + path);
                return 2;
            }

            if (!Workstation.Current.IsMapped(path))
            {
                Console.Error.WriteLine("The given file is not in a mapped TFS workspace: " + path);
                return 3;
            }

            WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(path);
            Uri serverUri = workspaceInfo.ServerUri;
            WorkspaceVersionSpec version = new WorkspaceVersionSpec(workspaceInfo);
            TfsClientCredentials credentials = new TfsClientCredentials(true);
            using (TfsTeamProjectCollection collection = new TfsTeamProjectCollection(serverUri, credentials))
            {
                VersionControlServer server = collection.GetService<VersionControlServer>();

                IAnnotatedFile annotatedFile = new FileAnnotator(server).Annotate(path, version);
                if (annotatedFile == null)
                {
                    Console.Error.WriteLine("The given file has not yet been checked-in: " + path);
                    return 4;
                }

                if (annotatedFile.IsBinary())
                {
                    Console.Error.WriteLine("The given file is a binary one: " + path);
                    return 5;
                }

                for (int i = 0; i < annotatedFile.Lines(); i++)
                {
                    switch (annotatedFile.State(i))
                    {
                        case AnnotationState.UNKNOWN:
                            Console.Write("unknown ");
                            break;
                        case AnnotationState.LOCAL:
                            Console.Write("local ");
                            break;
                        case AnnotationState.COMMITTED:
                            Changeset changeset = annotatedFile.Changeset(i);
                            Console.Write(changeset.ChangesetId);
                            Console.Write(' ');
                            Console.Write(changeset.Owner);
                            Console.Write(' ');
                            Console.Write(changeset.CreationDate.ToString("MM/dd/yyyy"));
                            Console.Write(' ');
                            break;
                        default:
                            throw new InvalidOperationException("Unsupported annotation state: " + annotatedFile.State(i));
                    }

                    Console.WriteLine(annotatedFile.Data(i));
                }
            }

            return 0;
        }
Example #50
0
 private static TfsClientCredentials CreateCredentials(string username, string password)
 {
     NetworkCredential netCred = new NetworkCredential(username, password);
     WindowsCredential windowsCredential = new WindowsCredential(netCred);
     TfsClientCredentials tfsCred = new TfsClientCredentials(windowsCredential) { AllowInteractive = false };
     return tfsCred;
 }
Example #51
0
        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;
        }
Example #52
0
        static int Main(string[] args)
        {
            Console.InputEncoding = Encoding.UTF8;
            Console.OutputEncoding = Encoding.UTF8;

            if (args.Length != 0)
            {
                Console.Error.WriteLine("This program is only expected to be called by the SonarQube TFS SCM plugin.");
                return 1;
            }

            Console.WriteLine("Enter your credentials");
            Console.Out.Flush();
            var username = Console.ReadLine();
            var password = Console.ReadLine();

            TfsClientCredentials credentials;
            if (!String.IsNullOrEmpty(username) || !String.IsNullOrEmpty(password))
            {
                credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(username, password)));
            }
            else
            {
                credentials = new TfsClientCredentials(true);
            }
            credentials.AllowInteractive = false;

            Console.WriteLine("Enter the Collection URI");
            Console.Out.Flush();
            var serverUriString = Console.ReadLine();

            if (!string.IsNullOrEmpty(serverUriString))
            {
                if (!SetServerUri(serverUriString))
                {
                    return 1;
                }
            }

            using (var cache = new TfsCache(credentials))
            {
                if (serverUri != null)
                {
                    if (!UpdateCache(cache, serverUri))
                    {
                        return 1;
                    }
                }

                Console.Out.WriteLine("Enter the paths to annotate");
                Console.Out.Flush();

                string path;
                while ((path = Console.ReadLine()) != null)
                {
                    Console.Out.Flush();
                    Console.WriteLine(path);

                    if (!File.Exists(path))
                    {
                        FailOnFile("does not exist: " + path);
                        continue;
                    }

                    if (!Workstation.Current.IsMapped(path))
                    {
                        FailOnFile("is not in a mapped TFS workspace: " + path);
                        continue;
                    }

                    WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(path);
                    WorkspaceVersionSpec version = new WorkspaceVersionSpec(workspaceInfo);

                    if (serverUri == null || workspaceInfo.ServerUri.AbsoluteUri != serverUri.AbsoluteUri)
                    {
                        serverUri = workspaceInfo.ServerUri;
                        if (!UpdateCache(cache, serverUri))
                        {
                            return 1;
                        }
                    }

                    var versionControlServer = cache.GetVersionControlServer(serverUri);

                    IAnnotatedFile annotatedFile = new FileAnnotator(versionControlServer).Annotate(path, version);
                    if (annotatedFile == null)
                    {
                        FailOnFile("is not yet checked-in: " + path);
                        continue;
                    }

                    if (annotatedFile.IsBinary())
                    {
                        FailOnFile("is a binary one: " + path);
                        continue;
                    }

                    bool failed = false;
                    for (int i = 0; !failed && i < annotatedFile.Lines(); i++)
                    {
                        var state = annotatedFile.State(i);
                        if (state != AnnotationState.COMMITTED)
                        {
                            FailOnFile("line " + (i + 1) + " has not yet been checked-in (" + state + "): " + path);
                            failed = true;
                        }
                    }
                    if (failed)
                    {
                        continue;
                    }

                    Console.WriteLine(annotatedFile.Lines());
                    for (int i = 0; i < annotatedFile.Lines(); i++)
                    {
                        Changeset changeset = annotatedFile.Changeset(i);
                        Console.Write(changeset.ChangesetId);
                        Console.Write('\t');
                        Console.Write(cache.GetEmailOrAccountName(serverUri, changeset.Owner));
                        Console.Write('\t');
                        Console.Write(ToUnixTimestampInMs(changeset.CreationDate));
                        Console.Write('\t');
                        Console.WriteLine(annotatedFile.Data(i));
                    }
                }
                Console.Out.Flush();
            }

            return 0;
        }
Example #53
0
 public TfsCache(TfsClientCredentials credentials)
 {
     this.credentials = credentials;
 }
        private void cmdExport_Click(object sender, EventArgs e)
        {
            Uri collectionUri = new Uri(txtCollectionUri.Text);
            string teamProject = txtTeamProject.Text;

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.CheckPathExists = true;
            dlg.Title = "Export Area/Iteration structure";
            dlg.DefaultExt = ".nodes";
            dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes";
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                string filename = dlg.FileName;

                var networkCredential = new NetworkCredential("username", "password");
                var basicAuthCredential = new BasicAuthCredential(networkCredential);
                var tfsCredential = new TfsClientCredentials(basicAuthCredential);

                using(var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential))
                //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri))
                using (WaitState waitState = new WaitState(this))
                {
                    tfs.Authenticate();
                    tfs.EnsureAuthenticated();

                    //  get the configuration server
                    var svr = tfs.ConfigurationServer;

                    //  get the configuration service
                    var svc = tfs.GetService<TeamSettingsConfigurationService>();

                    // get the common structure service
                    var css = tfs.GetService<ICommonStructureService4>();

                    //  get the spotlabs project
                    var prj = css.GetProjectFromName(txtTeamProject.Text);

                    //  get the configurations
                    var cfg = svc.GetTeamConfigurationsForUser(new[] { prj.Uri }).Single<TeamConfiguration>();

                    //  get the settings
                    var opt = cfg.TeamSettings;

                    //  get the iteration schedule
                    var schedule = css.GetIterationDates(prj.Uri);

                    Console.WriteLine(opt.ToString());

                    var store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
                    var proj = store.Projects[teamProject];

                    using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    using (StreamWriter writer = new StreamWriter(fs))
                    {
                        writer.WriteLine("NODES");
                        writer.WriteLine(String.Format("{0}, Version {1}", Application.ProductName, Application.ProductVersion));
                        writer.WriteLine("Copyright (C) 2010 " + Application.CompanyName);

                        if (chkAreaStructure.Checked)
                        {
                            WriteNodes(proj.AreaRootNodes, writer, "A");
                        }

                        if (chkIterationStructure.Checked)
                        {
                            WriteNodes(proj.IterationRootNodes, writer, "I");
                        }

                        writer.Close();
                    }
                }

                MessageBox.Show("Export successful.");
            }
        }
        private IEnumerable<TfsClientCredentials> GetServiceIdentityPatCredentials()
        {
            if (string.IsNullOrWhiteSpace(_config.TfsServerConfig.ServiceIdentityPatFile))
            {
                return new List<TfsClientCredentials>();
            }

            var netCred = new NetworkCredential("", GetPatFromConfig());
            var basicCred = new BasicAuthCredential(netCred);
            var patCred = new TfsClientCredentials(basicCred) {AllowInteractive = false};

            return new List<TfsClientCredentials> {patCred};
        }
Example #56
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;
        }
        private void cmdImport_Click(object sender, EventArgs e)
        {
            Uri collectionUri = new Uri(txtCollectionUri.Text);
            string teamProject = txtTeamProject.Text;

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.CheckFileExists = true;
            dlg.Title = "Import Area/Iteration structure";
            dlg.DefaultExt = ".nodes";
            dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes";
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                string filename = dlg.FileName;

                var networkCredential = new NetworkCredential("username", "password");
                var basicAuthCredential = new BasicAuthCredential(networkCredential);
                var tfsCredential = new TfsClientCredentials(basicAuthCredential);
                using (var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential))
                //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri, new UICredentialsProvider()))
                using (WaitState waitState = new WaitState(this))
                {
                    tfs.Authenticate();
                    tfs.EnsureAuthenticated();

                    WorkItemStore store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
                    Project proj = store.Projects[teamProject];

                    NodeInfo rootAreaNode = null;
                    NodeInfo rootIterationNode = null;

                    var css = (ICommonStructureService4)tfs.GetService(typeof(ICommonStructureService4));
                    foreach (NodeInfo info in css.ListStructures(proj.Uri.ToString()))
                    {
                        if (info.StructureType == "ProjectModelHierarchy")
                        {
                            rootAreaNode = info;
                        }
                        else if (info.StructureType == "ProjectLifecycle")
                        {
                            rootIterationNode = info;
                        }
                    }

                    using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                    using (StreamReader reader = new StreamReader(fs))
                    {
                        string nextLine = reader.ReadLine();
                        if (nextLine != "NODES")
                        {
                            MessageBox.Show("Wrong file format!");
                            return;
                        }

                        reader.ReadLine();
                        reader.ReadLine();

                        while (!reader.EndOfStream)
                        {
                            nextLine = reader.ReadLine();
                            if (nextLine.StartsWith("A") && chkAreaStructure.Checked)
                            {
                                CreateNode(css, nextLine.Substring(2), rootAreaNode);
                            }
                            else if (nextLine.StartsWith("I") && chkIterationStructure.Checked)
                            {
                                CreateNode(css, nextLine.Substring(2), rootIterationNode);
                            }
                            else
                            { // Ignore other lines
                            }
                        }
                        reader.Close();
                    }

                    MessageBox.Show("Import successful.");
                }
            }
        }
        private IEnumerable<TfsClientCredentials> GetBasicAuthCredentials()
        {
            var usernameAndPassword = GetAltAuthUsernameAndPasswordFromConfig();
            if (usernameAndPassword == null)
            {
                return new List<TfsClientCredentials>();
            }

            NetworkCredential netCred = new NetworkCredential(usernameAndPassword.Item1, usernameAndPassword.Item2);
            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;

            return new List<TfsClientCredentials>
            {
                tfsCred
            };
        }
Example #59
0
        private IBuildServer GetBuildServer()
        {
            BasicAuthCredential basicCredentials = new BasicAuthCredential(credentialsProvider);
            TfsClientCredentials tfsCredentials = new TfsClientCredentials(basicCredentials);
            tfsCredentials.AllowInteractive = false;

            var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsServerAddress));
            tfs.ClientCredentials = tfsCredentials;
            tfs.Authenticate();

            IBuildServer buildServer = tfs.GetService<IBuildServer>();
            return buildServer;
        }