예제 #1
0
        public object GetService(Type serviceType)
        {
            var collection = new TfsTeamProjectCollection(_projectCollectionUri);

            object service;

            try
            {

                if (_buildConfigurationManager.UseCredentialToAuthenticate)
                {
                    collection.Credentials = new NetworkCredential(_buildConfigurationManager.TfsAccountUserName,
                        _buildConfigurationManager.TfsAccountPassword, _buildConfigurationManager.TfsAccountDomain);
                }

                collection.EnsureAuthenticated();
                service = collection.GetService(serviceType);
            }
            catch (Exception ex)
            {
                Tracing.Client.TraceError(
                    String.Format("Error communication with TFS server: {0} detail error message {1} ",
                                  _projectCollectionUri, ex));
                throw;
            }
            Tracing.Client.TraceInformation("Connection to TFS established.");
            return service;
        }
예제 #2
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.");
        }
        protected RepositoryBase(String username, String password, string domain, string projectCollection, String url)
        {
            string fullUrl = url;
            bool collectionExists = !String.IsNullOrEmpty(projectCollection);

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

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

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

            if (collectionExists)
            {
                _tfs = new TfsTeamProjectCollection(new Uri(fullUrl), credentials);
                _tfs.EnsureAuthenticated();
            }
        }
예제 #4
0
        public static bool CollectionExists(Uri collectionUri, ICredentials credentials, out bool isAuthorized)
        {
            TfsTeamProjectCollection collection = null;

            try
            {
                collection = new TfsTeamProjectCollection(collectionUri, credentials);
                collection.EnsureAuthenticated();
                isAuthorized = true;

                return true;
            }
            catch (TeamFoundationServerUnauthorizedException)
            {
                isAuthorized = false;

                return true;
            }
            catch
            {
                isAuthorized = false;

                return false;
            }
            finally
            {
                collection.Dispose();
                collection = null;
            }
        }
예제 #5
0
        private TfsTeamProjectCollection ConnectToTfsCollection()
        {
            var tfsCredentials = GetTfsCredentials();

            foreach (var credentials in tfsCredentials)
            {
                try
                {
                    Logger.InfoFormat("Connecting to TFS {0} using {1} credentials", _config.TfsServerConfig.CollectionUri, credentials);
                    var tfsServer = new TfsTeamProjectCollection(new Uri(_config.TfsServerConfig.CollectionUri), credentials);
                    tfsServer.EnsureAuthenticated();

                    Logger.InfoFormat("Successfully connected to TFS");

                    return tfsServer;
                }
                catch (Exception ex)
                {
                    Logger.WarnFormat("TFS connection attempt failed.\n Exception: {0}", ex);
                }
            }

            Logger.ErrorFormat("All TFS connection attempts failed");
            throw new Exception("Cannot connect to TFS");
        }
        public TfsRepository(TfsTeamProjectCollection tfs, ITfsProjectProvider projectProvider, string projectName)
        {
            _tfs = tfs;
            _tfs.EnsureAuthenticated();

            _projectProvider = projectProvider;
            _projectProvider.Initialize(_tfs, projectName);
        }
예제 #7
0
        public void Conectar(Uri uri, NetworkCredential credential)
        {
            TeamProjectCollection = credential == null ?
                new TfsTeamProjectCollection(uri) :
                new TfsTeamProjectCollection(uri, credential);

            TeamProjectCollection.EnsureAuthenticated();
        }
예제 #8
0
        /// <summary>
        /// Create a new instance of TFSAPI Class
        /// </summary>
        /// <param name="TfsCollectionURI">URI to access the TFS Server and project collection</param>
        /// <param name="ProjectName">Default project</param>
        public TFSAPI(Uri TfsCollectionURI, string ProjectName)
        {
            teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(TfsCollectionURI);
            teamProjectCollection.Connect(Microsoft.TeamFoundation.Framework.Common.ConnectOptions.IncludeServices);
            teamProjectCollection.EnsureAuthenticated();

            wiStore = new WorkItemStore(teamProjectCollection);

            workItemTypeCollection = wiStore.Projects[ProjectName].WorkItemTypes;
        }
		private static WorkItemStore GetWorkItemStore(ISourceControlConnectionSettingsSource settings)
		{
			TfsConnectionParameters parameters = TfsConnectionHelper.GetTfsConnectionParameters(settings);

			var teamProjectCollection = new TfsTeamProjectCollection(parameters.TfsCollectionUri, parameters.Credential);
			teamProjectCollection.EnsureAuthenticated();

			var workItemStore = teamProjectCollection.GetService<WorkItemStore>();

			return workItemStore;
		}
예제 #10
0
 private void UpdateServer()
 {
     if (string.IsNullOrEmpty(Url))
     {
         server = null;
     }
     else
     {
         server = new TfsTeamProjectCollection(new Uri(Url), new UICredentialsProvider());
         server.EnsureAuthenticated();
     }
 }
        private void ChangeConnection()
        {
            if (!string.IsNullOrEmpty(this.ctx.ActiveConnection))
            {
                var collection = new TfsTeamProjectCollection(TfsTeamProjectCollection.GetFullyQualifiedUriForName(this.ctx.ActiveConnection), new TfsClientCredentials());
                collection.EnsureAuthenticated();

                var view = this.Content as MainView;
                view.InitializeContext(this.ctx);
                view.InitializeRepository(new TfsClientRepository(collection));
            }
        }
예제 #12
0
 private void Authenticate(string tfsUrl)
 {
     try
     {
         var credentials = new UICredentialsProvider();
         m_tpc = new TfsTeamProjectCollection(new Uri(tfsUrl), credentials);
         m_tpc.EnsureAuthenticated();
     }
     catch
     {
         m_tpc = null;
         throw;
     }
 }
예제 #13
0
        public TFS2010(string servername, string domain, string username, string password)
        {
            if (string.IsNullOrEmpty(servername))
                throw new ArgumentException("Parameter named:servername cannot be null or empty.");

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

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

            //ICredentialsProvider provider = new UICredentialsProvider();
            //tfsConfigurationServer = TeamFoundationServerFactory.GetServer(serverName, provider);
            //if (!tfsConfigurationServer.HasAuthenticated)
            //    tfsConfigurationServer.Authenticate();

            //tfsConfigurationServer = new TfsConfigurationServer(new Uri(string.Concat("http://", servername)),
            //                                                    new NetworkCredential(username, password, domain));

            //TeamProjectPicker pp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);

            //pp.ShowDialog();

            //var coll = new TfsTeamProjectCollection(new Uri(string.Concat("http://", servername)), new UICredentialsProvider());
            var tfsTeamProjectCollection = new TfsTeamProjectCollection(new Uri(string.Concat("http://", servername)), new NetworkCredential(username, password, domain));
            tfsTeamProjectCollection.EnsureAuthenticated();
            store = (WorkItemStore)tfsTeamProjectCollection.GetService(typeof(WorkItemStore));

            //var processTemplates = (IProcessTemplates)tfsTeamProjectCollection.GetService(typeof(IProcessTemplates));
            //var node = processTemplates.GetTemplateNames();

            //ICommonStructureService css = (ICommonStructureService)tfsTeamProjectCollection.GetService(typeof(ICommonStructureService));
            //ProjectInfo projectInfo = css.GetProjectFromName(store.Projects[5].Name);
            //String projectName;
            //String prjState;
            //int templateId = 0;
            //ProjectProperty[] projectProperties;

            //css.GetProjectProperties(
            //        projectInfo.Uri, out projectName, out prjState, out templateId, out projectProperties);

            // //tfsConfigurationServer.Authenticate();
            // var tpcService = tfsConfigurationServer.GetService<ITeamProjectCollectionService>();
            //var  collections = tpcService.GetCollections();
            // //var wstore= ((TfsTeamProjectCollection )collections[0]).GetService(typeof (WorkItemStore));
            // var ws=tpcService.GetServicingOperation("WorkItemStore");

            // store = (WorkItemStore) tfsConfigurationServer.GetService(typeof (WorkItemStore));
        }
예제 #14
0
 internal static TfsTeamProjectCollection GetTeamProjectCollection(TfsConfigurer configurer)
 {
     if (configurer.UseSystemCredentials)
     {
         var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(configurer.BaseUri);
         projectCollection.EnsureAuthenticated();
         return projectCollection;
     }
     else
     {
         var projectCollection = new TfsTeamProjectCollection(configurer.BaseUri, new TfsClientCredentials(new WindowsCredential(new NetworkCredential(configurer.UserName, configurer.Password, configurer.Domain))));
         projectCollection.EnsureAuthenticated();
         return projectCollection;
     }
 }
예제 #15
0
        public TFS2010(string servername, string domain, string username, string password)
        {
            if (string.IsNullOrEmpty(servername))
                throw new ArgumentException("Parameter named:servername cannot be null or empty.");

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

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

            tfsTeamProjectCollection = new TfsTeamProjectCollection(new Uri(string.Concat("http://", servername)),
                                                                    new NetworkCredential(username, password, domain));
            tfsTeamProjectCollection.EnsureAuthenticated();
            store = (WorkItemStore) tfsTeamProjectCollection.GetService(typeof (WorkItemStore));
        }
 protected override TfsTeamProjectCollection GetTeamProjectCollection()
 {
     try
     {
         var tfs = new TfsTeamProjectCollection(
             this.BaseUri,
             new TfsClientCredentials(
                 this.UseBasicAuthentication ? this.CreateCredentials() : new SimpleWebTokenCredential(this.UserName, this.Password)
             )
         );
         tfs.EnsureAuthenticated();
         return tfs;
     }
     catch (TypeLoadException)
     {
         throw new NotAvailableException("Basic authentication requires Visual Studio 2012 Update 1 or newer.");
     }
 }
예제 #17
0
        public TfsApiRepository(string uri)
        {
            var tfsUri = new Uri(uri);
            //var credential = new NetworkCredential("*****@*****.**", "kubekstolik40");
            //_tfs = new TfsTeamProjectCollection(tfsUri,credential);
            _tfs = new TfsTeamProjectCollection(tfsUri);

            try
            {
                _tfs.EnsureAuthenticated();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Autentykacja sie nie powiodla.({0})", ex.Message));
            }

            _buildServer = (IBuildServer)_tfs.GetService(typeof(IBuildServer));
        }
        public object GetService(Type serviceType)
        {
            var collection = new TfsTeamProjectCollection(projectCollectionUri);
            object service = null;

            try
            {
                collection.EnsureAuthenticated();
                service = collection.GetService(serviceType);
            }
            catch (Exception ex)
            {
                log.Error("Error communication with TFS server: " + projectCollectionUri.ToString());
                log.Error(ex.ToString());
            }

            log.Information("Connection to TFS established.");
            return service;
        }
예제 #19
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);
        }
예제 #20
0
        public void Connect(string url, string project, string workItemQuery, string ignoreRemainingArea, string activeState, string closedState)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException("url");
            }
            if (string.IsNullOrWhiteSpace(project))
            {
                throw new ArgumentNullException("project");
            }
            if (string.IsNullOrWhiteSpace(workItemQuery))
            {
                throw new ArgumentNullException("workItemQuery");
            }
            if (string.IsNullOrWhiteSpace(ignoreRemainingArea))
            {
                throw new ArgumentNullException("ignoreRemainingArea");
            }
            if (string.IsNullOrWhiteSpace(activeState))
            {
                throw new ArgumentNullException("activeState");
            }
            if (string.IsNullOrWhiteSpace(closedState))
            {
                throw new ArgumentNullException("closedState");
            }

            _url                 = url;
            _project             = project;
            _ignoreRemainingArea = ignoreRemainingArea;
            _activeState         = activeState;
            _closedState         = closedState;

            _tfs = new TfsTeamProjectCollection(new Uri(url));
            _tfs.EnsureAuthenticated();

            _workItemStore          = _tfs.GetService <WorkItemStore>();
            _commonStructureService = _tfs.GetService <ICommonStructureService4>();

            _workitemQueryText = GetWorkitemQueryText(workItemQuery);
        }
        public object GetService(Type serviceType)
        {
            var collection = new TfsTeamProjectCollection(_projectCollectionUri);

            object service;

            try
            {
                collection.EnsureAuthenticated();
                service = collection.GetService(serviceType);
            }
            catch (Exception ex)
            {
                Tracing.Client.TraceError(
                    String.Format("Error communication with TFS server: {0} detail error message {1} ",
                                  _projectCollectionUri, ex));
                throw;
            }
            Tracing.Client.TraceInformation("Connection to TFS established.");
            return service;
        }
        public BuildDefinitionUpdater()
        {
            try
              {
            TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false);
            tpp.ShowDialog();

            if (tpp.SelectedTeamProjectCollection != null)
            {
              tfpCollection = tpp.SelectedTeamProjectCollection;
              tfpCollection.EnsureAuthenticated();
              selectedProject = tpp.SelectedProjects[0].Name;

              buildServer = (IBuildServer)tfpCollection.GetService(typeof(IBuildServer));
            }
              }
              catch (Exception pokeballExc)
              {
            LogExc(pokeballExc);
              }
        }
예제 #23
0
        public void AssureFileCheckout(string path, string pattern = "*.*")
        {
            try
            {
                var teamFoundationServices = new TfsTeamProjectCollection(new Uri(HydraConstants.TFS_MCTEAM_PROJECT_COLLECTION_V2_URL), System.Net.CredentialCache.DefaultCredentials);

                teamFoundationServices.EnsureAuthenticated();

                var versionControlServer = (VersionControlServer)teamFoundationServices.GetService(typeof(VersionControlServer));

                if (File.Exists(path))
                {
                    var workspace = versionControlServer.GetWorkspace(Path.GetDirectoryName(path));
                    workspace.PendEdit(path);
                }
                else if (Directory.Exists(path))
                {
                    foreach (var file in Directory.GetFiles(path, pattern))
                    {
                        var workspace = versionControlServer.GetWorkspace(Path.GetDirectoryName(file));
                        workspace.PendEdit(file);
                    }
                }
            }
            catch (Exception ex)
            {
                var error = string.Format("Error checking out files from TFS. {0}", ex);

                if (this.BuildEngine != null)
                {
                    var message = new BuildErrorEventArgs(string.Empty, string.Empty, string.Empty, 0, 0, 0, 0, error, "", "", DateTime.Now);
                    this.BuildEngine.LogErrorEvent(message);
                }
                else
                {
                    Console.WriteLine(error);
                    throw new Exception(error);
                }
            }
        }
예제 #24
0
 public void Connect()
 {
     if (_Collection == null)
     {
         Telemetry.Current.TrackEvent("TeamProjectContext.Connect",
                                      new Dictionary <string, string> {
             { "Name", Name },
             { "Target Project", this._TeamProjectName },
             { "Target Collection", this._CollectionUrl.ToString() }
         });
         Stopwatch connectionTimer = new Stopwatch();
         connectionTimer.Start();
         DateTime start = DateTime.Now;
         Trace.WriteLine("Creating TfsTeamProjectCollection Object ");
         _Collection = new TfsTeamProjectCollection(_CollectionUrl);
         try
         {
             Trace.WriteLine(string.Format("Connected to {0} ", _Collection.Uri.ToString()));
             Trace.WriteLine(string.Format("validating security for {0} ", _Collection.AuthorizedIdentity.ToString()));
             _Collection.EnsureAuthenticated();
             connectionTimer.Stop();
             Telemetry.Current.TrackDependency("TeamService", "EnsureAuthenticated", start, connectionTimer.Elapsed, true);
             Trace.TraceInformation(string.Format(" Access granted "));
         }
         catch (TeamFoundationServiceUnavailableException ex)
         {
             Telemetry.Current.TrackDependency("TeamService", "EnsureAuthenticated", start, connectionTimer.Elapsed, false);
             Telemetry.Current.TrackException(ex,
                                              new Dictionary <string, string> {
                 { "CollectionUrl", _CollectionUrl.ToString() },
                 { "TeamProjectName", _TeamProjectName }
             },
                                              new Dictionary <string, double> {
                 { "ConnectionTimer", connectionTimer.ElapsedMilliseconds }
             });
             Trace.TraceWarning(string.Format("  [EXCEPTION] {0}", ex.Message));
             throw;
         }
     }
 }
 private TfsTeamProjectCollection GetTfsCollection()
 {
     if (_Collection is null)
     {
         var            startTime = DateTime.UtcNow;
         var            timer     = System.Diagnostics.Stopwatch.StartNew();
         VssCredentials vssCredentials;
         try
         {
             if (!string.IsNullOrEmpty(_Options.AccessToken))
             {
                 Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection: Using PAT Authentication ", _Options.Organisation);
                 vssCredentials = new VssBasicCredential(string.Empty, _Options.AccessToken);
             }
             else
             {
                 Log.LogDebug("TfsWorkItemEndPoint::EnsureDataSource: Using Interactive Authentication ", _Options.Organisation);
                 vssCredentials = new VssCredentials();
             }
             Log.LogDebug(Microsoft.TeamFoundation.Framework.Common.LocationServiceConstants.ApplicationLocationServiceIdentifier.ToString());
             Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection: Connecting to {CollectionUrl} ", _Options.Organisation);
             _Collection = new TfsTeamProjectCollection(new Uri(_Options.Organisation), vssCredentials);
             Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection: Connected ");
             Log.LogDebug("TfsWorkItemEndPoint::GetTfsCollection: validating security for {@AuthorizedIdentity} ", _Collection.AuthorizedIdentity);
             _Collection.EnsureAuthenticated();
             timer.Stop();
             Log.LogInformation("TfsWorkItemEndPoint::GetTfsCollection: Access granted to {CollectionUrl} for {Name} ({Account})", _Options.Organisation, _Collection.AuthorizedIdentity.DisplayName, _Collection.AuthorizedIdentity.UniqueName);
             Telemetry.TrackDependency(new DependencyTelemetry("TfsObjectModel", _Options.Organisation, "GetTfsCollection", null, startTime, timer.Elapsed, "200", true));
         }
         catch (Exception ex)
         {
             timer.Stop();
             Telemetry.TrackDependency(new DependencyTelemetry("TfsObjectModel", _Options.Organisation, "GetTfsCollection", null, startTime, timer.Elapsed, "500", false));
             Log.LogError(ex, "Unable to connect to {Organisation}", _Options.Organisation);
             throw;
         }
     }
     return(_Collection);
 }
예제 #26
0
        public static bool UpdateTask(int taskId, string developer)
        {
            try
            {
                NetworkCredential networkCredential = new NetworkCredential(ConfigurationManager.AppSettings["TFSUsername"], ConfigurationManager.AppSettings["TFSPassword"]);
                var tfs = new TfsTeamProjectCollection(new Uri(ConfigurationManager.AppSettings["TFSServerURL"]), networkCredential);
                tfs.EnsureAuthenticated();

                //Get data store that contains all workitems on a particular server
                WorkItemStore store = tfs.GetService <WorkItemStore>();
                WorkItem      task  = store.GetWorkItem(taskId);

                task.Fields["Assigned To"].Value = developer;
                task.Save();
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Error creating a TFS Task {0}. Exception : {1}\r\n{2}", taskId, ex.Message, ex.InnerException);
                return(false);
            }
            return(true);
        }
        static void Main(string[] args)
        {
            TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri("http://server:8080/tfs/DefaultCollection"));

            tfs.EnsureAuthenticated();

            IGroupSecurityService gss = tfs.GetService <IGroupSecurityService>();

            Identity SIDS = gss.ReadIdentity(SearchFactor.AccountName, "Project Collection Valid Users", QueryMembership.Expanded);

            Identity[] UserId = gss.ReadIdentities(SearchFactor.Sid, SIDS.Members, QueryMembership.Direct);

            foreach (Identity user in UserId)
            {
                if (user != null)
                {
                    Console.WriteLine(user.AccountName);
                    Console.WriteLine(user.Domain);
                }
            }
            Console.ReadKey();
        }
예제 #28
0
        public ActionResult Index()
        {
            List <TaskStickyNote> notes = new List <TaskStickyNote>();

            //connect to tfs server
            // The url to the tfs server
            Uri tfsUri = new Uri(TFSURL);

            // Load the tfs project collection
            var mojo = new TfsTeamProjectCollection(tfsUri);

            // Log in to TFS
            mojo.EnsureAuthenticated();

            var wit = mojo.GetService <WorkItemStore>();

            Guid qguid           = new Guid(ConfigurationManager.AppSettings["QueryGUID"]);
            var  queryDefinition = wit.GetQueryDefinition(qguid);

            string wiql = queryDefinition.QueryText;

            System.Collections.Hashtable context = new System.Collections.Hashtable();

            context.Add("project", queryDefinition.Project.Name);

            var queryReturn = new Query(wit, wiql, context);
            var wic         = queryReturn.RunQuery(); //.RunLinkQuery();

            foreach (WorkItem wi in wic)
            {
                TaskStickyNote sn = new TaskStickyNote(wi, StateManager.GetState(wi.Id));
                sn.EditURL = WORKITEMEDITURL + String.Format(WORKITEMEDITPARAMSTRING, wi.Id.ToString());
                notes.Add(sn);
            }

            notes = notes.OrderBy(x => (x.RemainingTime == "0" && x.AssignedTo == String.Empty ? "" : x.RemainingTime)).OrderBy(x => x.AssignedTo).OrderBy(x => x.State).ToList();

            return(View(notes));
        }
        static void Main(string[] args)
        {
            var u                        = new Uri("http://172.17.16.163:8080/tfs/DefaultCollection");
            var c                        = new VssClientCredentials();
            int SharedStepsID            = 748;
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(u, c);

            tpc.EnsureAuthenticated();
            WorkItemStore  wistore  = tpc.GetService <WorkItemStore>();
            WorkItem       wi       = wistore.GetWorkItem(SharedStepsID);
            WorkItemServer wiserver = tpc.GetService <WorkItemServer>();
            int            atc      = wi.Attachments.Count;

            for (int i = 0; i < atc; i++)
            {
                string tmppath  = wiserver.DownloadFile(wi.Attachments[i].Id);
                string filename = string.Format("D:\\temp\\vsts\\{0}-{1}", wi.Fields["ID"].Value, wi.Attachments[i].Name);
                File.Copy(tmppath, filename);
                Console.WriteLine(string.Format("{0}\n", filename));
            }
            Console.ReadLine();
        }
예제 #30
0
        private dynamic GetTestcoverage(TfsTeamProjectCollection projectCollection, Uri uri)
        {
            var watch = Stopwatch.StartNew();

            projectCollection.EnsureAuthenticated();
            var tcm = projectCollection.GetService <ITestManagementService>();
            var testManagementTeamProject = tcm.GetTeamProject(_settings.Project);
            var runs = testManagementTeamProject.TestRuns.ByBuild(uri);

            var result = new
            {
                Statistics = runs.Select(x => new
                {
                    x.Statistics.TotalTests,
                    x.Statistics.FailedTests,
                    x.Statistics.PassedTests
                }).ToList()
            };

            Trace.WriteLine("GetTestCoverage: " + watch.Elapsed);
            return(result);
        }
예제 #31
0
        public override int RunInternal(ImportPicturesOptions opts)
        {
            if (!Directory.Exists(opts.OutPath))
            {
                Directory.CreateDirectory(opts.OutPath);
            }

            if (opts.CollectionURL.ToString().Contains("visualstudio.com"))
            {
                throw new InvalidDomainException("Unable to upload pictures to VSTS due to API/Permission restrictions.");
            }

            TfsTeamProjectCollection collection = new TfsTeamProjectCollection(opts.CollectionURL);

            collection.EnsureAuthenticated();
            IIdentityManagementService2 ims2 = (IIdentityManagementService2)collection.GetService(typeof(IIdentityManagementService2));


            var files = Directory.GetFiles(opts.OutPath);
            var regex = new Regex(Regex.Escape("-"));

            foreach (string file in files)
            {
                string ident = regex.Replace(Path.GetFileNameWithoutExtension(file), @"\", 1);
                string mess;
                if (SetProfileImage(ims2, ident, file, out mess))
                {
                    Trace.WriteLine(string.Format(" [UPDATE] New Profile for : {0} ", ident));
                    File.Delete(file);
                }
                else
                {
                    Trace.WriteLine(string.Format(" [FAIL] Unable to set: {0} ", ident));
                }
            }

            return(0);
        }
예제 #32
0
        /// <summary>
        /// The connect.
        /// </summary>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        /// <returns>
        /// is connected
        /// </returns>
        public bool Connect(Uri uri, ICredentials credentials, bool anotherUser)
        {
            List <CatalogNode> catalogNodes = GetCatalogNodes(uri, credentials, anotherUser);

            if (catalogNodes != null)
            {
                nodes = new List <CatalogNode>();
                foreach (CatalogNode node in catalogNodes)
                {
                    try
                    {
                        bool _isvsservice = uri.ToString().Contains("visualstudio.com");
                        using (TfsTeamProjectCollection projCollection = new TfsTeamProjectCollection(new Uri(string.Format(@"{0}/{1}", uri, (_isvsservice)? "" : node.Resource.DisplayName)), Credential))
                        {
                            projCollection.EnsureAuthenticated();
                            projCollection.Connect(ConnectOptions.None);
                            nodes.Add(node);
                        }
                    }
                    catch (TeamFoundationServiceUnavailableException ex)
                    {
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message);
                    }
                }

                if (nodes.Count > 0)
                {
                    ChangeCollection(nodes[0].Resource.DisplayName);
                    tfsVersion = collection.GetVersion();
                    return(true);
                }
            }

            return(false);
        }
예제 #33
0
        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing && (this.components != null))
        //    {
        //        this.components.Dispose();
        //    }
        //    base.Dispose(disposing);
        //}

        private TfsTeamProjectCollection GetServer(string serverName)
        {
            //TfsTeamProjectCollection tfsProj = tpp.SelectedTeamProjectCollection;
            TfsTeamProjectCollection server = null;

            try
            {
                if (!this._servers.ContainsKey(serverName))
                {
                    server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverName));
                    //server = TeamFoundationServerFactory.GetServer(serverName, new UICredentialsProvider());
                    server.EnsureAuthenticated();
                    this._servers.Add(serverName, server);
                    return(server);
                }
                return(this._servers[serverName]);
            }
            catch (Exception exception)
            {
                MessageBox.Show(this, exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return(null);
            }
        }
예제 #34
0
 /// <summary>
 /// Connects to the Project Collection
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnConnect_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (cboServer.Text != string.Empty)
         {
             Mouse.OverrideCursor = Cursors.Wait;
             _tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(cboServer.Text),
                                                                             new UICredentialsProvider());
             _tfs.EnsureAuthenticated();
             LoadProjects();
             _wis = (WorkItemStore)_tfs.GetService(typeof(WorkItemStore));
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         Mouse.OverrideCursor = null;
     }
 }
        private VssHttpMessageHandler GetHttpHandler(string tfsUri, ILogger logger)
        {
            VssCredentials vssCreds;
            Uri            tfsCollectionUri = new Uri(tfsUri);

            using (TfsTeamProjectCollection collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsCollectionUri))
            {
                // Build agents run non-attended and most often non-interactive so make sure not to create a credential prompt
                collection.ClientCredentials.AllowInteractive = false;
                collection.EnsureAuthenticated();

                logger.LogInfo(Resources.DOWN_DIAG_ConnectedToTFS, tfsUri);

                // We need VSS credentials that encapsulate all types of credentials (NetworkCredentials for TFS, OAuth for VSO)
                TfsConnection connection = collection as TfsConnection;
                vssCreds = connection.ClientCredentials.ConvertToVssCredentials(tfsCollectionUri);
            }

            Debug.Assert(vssCreds != null, "Not expecting ConvertToVssCredentials ");
            VssHttpMessageHandler vssHttpMessageHandler = new VssHttpMessageHandler(vssCreds, new VssHttpRequestSettings());

            return(vssHttpMessageHandler);
        }
        static void Main(string[] args)
        {
            var u = new Uri("http://server:8080/tfs/DefaultCollection");
            var c = new VssClientCredentials();
            TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(u, c);

            tpc.EnsureAuthenticated();
            ITestManagementService     itms  = tpc.GetService <ITestManagementService>();
            ITestManagementTeamProject ittp  = itms.GetTeamProject("LCScrum");
            ITestSuiteBase             suite = ittp.TestSuites.Find(352);
            ITestCaseCollection        testCaseCollection = suite.AllTestCases;

            foreach (var tc in testCaseCollection)
            {
                ITestCase testcase = ittp.TestCases.Find(tc.Id);

                foreach (ITestAction action in testcase.Actions)
                {
                    Console.WriteLine(String.Format("{0} - {1}", testcase.Id, action));
                }
            }
            Console.Read();
        }
예제 #37
0
        public IEnumerable <IShelveset> GetShelvesetByOwner(string serverUrl, string actingUserName, string ownerName)
        {
            TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl));

            teamProjectCollection.EnsureAuthenticated();

            VersionControlServer vcServer             = teamProjectCollection.GetService <VersionControlServer>();
            HashSet <string>     workspaceBranchNames = new HashSet <string>();

            foreach (Workspace workspace in vcServer.QueryWorkspaces(null, actingUserName, null))
            {
                workspace.Folders.ToList().ForEach(f => workspaceBranchNames.Add(f.ServerItem));
            }

            foreach (Shelveset shelveset in vcServer.QueryShelvesets(null, ownerName))
            {
                PendingSet changeSet = vcServer.QueryShelvedChanges(shelveset).FirstOrDefault();
                if (changeSet != null)
                {
                    yield return(new AdapterShelveset(shelveset, changeSet.PendingChanges, workspaceBranchNames.ToArray()));
                }
            }
        }
        protected void Connect()
        {
            string tpcUrl = TfsUrl + "/" + TeamProjectCollection + "/";

            if (!string.IsNullOrWhiteSpace(this.Username))
            {
                Console.WriteLine("Authenticating as '{0}'", this.Username);

                // source http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx
                NetworkCredential    netCred   = new NetworkCredential(this.Username, this.Password);
                BasicAuthCredential  basicCred = new BasicAuthCredential(netCred);
                TfsClientCredentials tfsCred   = new TfsClientCredentials(basicCred);
                tfsCred.AllowInteractive = false;

                tpc = new TfsTeamProjectCollection(new Uri(tpcUrl), tfsCred);
            }
            else
            {
                tpc = new TfsTeamProjectCollection(new Uri(tpcUrl));
            }

            tpc.EnsureAuthenticated();

            gitSvc = tpc.GetService <GitRepositoryService>();

            if (!string.IsNullOrWhiteSpace(this.Username))
            {
                NetworkCredential netCred = new NetworkCredential(this.Username, this.Password);
                var cred = new VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(netCred));
                gitWebApiClient = new GitHttpClient(new Uri(tpcUrl), cred);
            }
            else
            {
                var cred = new VssCredentials(true);
                gitWebApiClient = new GitHttpClient(new Uri(tpcUrl), cred);
            }
        }
예제 #39
0
        /// <summary>
        /// Initializes the tool.
        /// </summary>
        /// <param name="uriAddress"> The URI Address. </param>
        /// <param name="forWeb">True if this is called from a web client.</param>
        public static void Initialize(string uriAddress, bool forWeb = false)
        {
            tfsAddress    = new Uri(uriAddress);
            TfsWebAddress = string.IsNullOrEmpty(ConfigurationManager.AppSettings.Get("teamWebAccessUrl")) ? string.Format("{0}/web", uriAddress) : ConfigurationManager.AppSettings.Get("teamWebAccessUrl");

            // gets the project id
            projectCollection = new TfsTeamProjectCollection(tfsAddress, new UICredentialsProvider());
            projectCollection.EnsureAuthenticated();

            versionControlcServer = projectCollection.GetService <VersionControlServer>();
            var catalogNodes = projectCollection.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None);

            foreach (var node in catalogNodes)
            {
                string projectId;
                node.Resource.Properties.TryGetValue("ProjectId", out projectId);
                ProjectId = projectId;
            }

            if (forWeb)
            {
                // create new cache folder for Tfs (used for workItems).
                Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");
                var           settings = connectionConfiguration.AppSettings.Settings;
                if (settings["WorkItemTrackingCacheRoot"] == null)
                {
                    settings.Add("WorkItemTrackingCacheRoot", System.IO.Path.GetTempPath() + "TFSClientCache");
                    connectionConfiguration.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }
            }

            // gets the owner name from the environment
            CurrentUser   = versionControlcServer.AuthorizedIdentity.UniqueName;
            Users         = GetUsers();
            isInitialized = true;
        }
        /// <summary>
        /// To run this preparation steps successfully a Windows File Share must be created at "fileShareFolder" (no content necessary).
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="tfsPath"></param>
        /// <param name="workspaceName"></param>
        /// <param name="tfsProject"></param>
        /// <param name="localWorkspaceFolder"></param>
        /// <param name="fileShareFolder"></param>
        internal static void PrepareFileShareTestEnvironment(string username, string password, string tfsPath, string workspaceName, string tfsProject, string localWorkspaceFolder, string fileShareFolder)
        {
            try
            {
                NetworkCredential cred = new NetworkCredential(username, password);
                using (TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(tfsPath), cred))
                {
                    tfs.EnsureAuthenticated();

                    VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

                    var workspace = WorkspaceHelper.WorkspaceCreate(vcs, tfsProject, workspaceName, localWorkspaceFolder);
                    workspace.Get();

                    var targetContent = $"<?xml version='1.0'?><Component xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://schemas.aitgmbh.de/DependencyManager/2011/11'><Dependencies><Dependency Type='BinaryDependency'><Provider Type='FileShare'><Settings Type='FileShareSettings'><Setting Name='FileShareRootPath' Value='{fileShareFolder}' /><Setting Name='ComponentName' Value='comp1' /><Setting Name='VersionNumber' Value='V1.0' /></Settings></Provider></Dependency></Dependencies></Component>";
                    FileHelper.CheckInFolderWithFile(workspace, "FileShareTarget", "component.targets", targetContent);

                    var subPath     = Path.Combine(fileShareFolder, "comp1");
                    var subSubPath  = Path.Combine(subPath, "V1.0");
                    var subSubPath2 = Path.Combine(subPath, "V2.0");

                    Directory.CreateDirectory(subSubPath);
                    Directory.CreateDirectory(subSubPath2);

                    var emptyTarget = "<?xml version='1.0'?><Component xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://schemas.aitgmbh.de/DependencyManager/2011/11'><Dependencies /></Component>";
                    FileHelper.AddFileInLocal(subSubPath, "component.targets", emptyTarget);
                    FileHelper.AddFileInLocal(subSubPath2, "component.targets", emptyTarget);
                    FileHelper.AddFileInLocal(subSubPath, "Example1.dll", "dummy content");
                    FileHelper.AddFileInLocal(subSubPath2, "Example2.dll", "dummy content");
                }
            }
            catch
            {
                throw;
            }
        }
예제 #41
0
        private VersionControlServer GetVersionControl(ISourceControlConnectionSettingsSource settings)
        {
            VersionControlServer versionControl = null;

            TfsConnectionParameters parameters = TfsConnectionHelper.GetTfsConnectionParameters(settings);

            switch (parameters.SegmentsCount)
            {
            case UriTfsProjectCollection:
            {
                _teamProjectCollection = new TfsTeamProjectCollection(parameters.TfsCollectionUri, parameters.Credential);
                _teamProjectCollection.EnsureAuthenticated();

                versionControl = _teamProjectCollection.GetService <VersionControlServer>();
                _teamProjects  = versionControl.GetAllTeamProjects(false);

                break;
            }

            case UriTfsTeamProject:
            {
                _teamProjectCollection = new TfsTeamProjectCollection(parameters.TfsCollectionUri, parameters.Credential);
                _teamProjectCollection.EnsureAuthenticated();

                versionControl = _teamProjectCollection.GetService <VersionControlServer>();
                _teamProjects  = new TeamProject[] { versionControl.GetTeamProject(parameters.TeamProjectName) };

                break;
            }

            default:
                throw new Exception("Wrong URI format.");
            }

            return(versionControl);
        }
        internal static void PrepareSourceControlTestEnvironment(string username, string password, string tfsPath, string tfsProject, string workspaceName, string localWorkspaceFolder, bool sourceControlMapping = false)
        {
            try
            {
                NetworkCredential cred = new NetworkCredential(username, password);
                using (TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(tfsPath), cred))
                {
                    tfs.EnsureAuthenticated();

                    VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

                    var workspace = WorkspaceHelper.WorkspaceCreate(vcs, tfsProject, workspaceName, localWorkspaceFolder);
                    workspace.Get();

                    string targetContent;
                    if (!sourceControlMapping)
                    {
                        targetContent = $"<?xml version='1.0'?><Component xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://schemas.aitgmbh.de/DependencyManager/2011/11'><Dependencies><Dependency Type='BinaryDependency'><Provider Type='SourceControlCopy'><Settings Type='SourceControlSettings'><Setting Name='ServerRootPath' Value='$/{Values.TeamProjectName}/DependencySource' /><Setting Name='VersionSpec' Value='T' /></Settings></Provider></Dependency></Dependencies></Component>";
                    }
                    else
                    {
                        targetContent = $"<?xml version='1.0'?><Component xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://schemas.aitgmbh.de/DependencyManager/2011/11'><Dependencies><Dependency Type='SourceDependency'><Provider Type='SourceControl'><Settings Type='SourceControlSettings'><Setting Name='ServerRootPath' Value='$/{Values.TeamProjectName}/DependencySource' /><Setting Name='VersionSpec' Value='T' /></Settings></Provider></Dependency></Dependencies></Component>";
                    }
                    FileHelper.CheckInFolderWithFile(workspace, "SourceControlTarget", "component.targets", targetContent);

                    FileHelper.CheckInFolderWithFile(workspace, "DependencySource", "helloWorld.dll", "dummy content");

                    var emptyTargetContent = "<?xml version='1.0'?><Component xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://schemas.aitgmbh.de/DependencyManager/2011/11'><Dependencies /></Component>";
                    FileHelper.CheckInFolderWithFile(workspace, "DependencySource", "component.targets", emptyTargetContent);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #43
0
        internal static void PrepareSubVersionTestEnvironment(string username, string password, string tfsPath, string workspaceName, string tfsProject, string localWorkspaceFolder, string subversionPath)
        {
            try
            {
                NetworkCredential cred = new NetworkCredential(username, password);
                using (TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(tfsPath), cred))
                {
                    tfs.EnsureAuthenticated();

                    VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));

                    var workspace = WorkspaceHelper.WorkspaceCreate(vcs, tfsProject, workspaceName, localWorkspaceFolder);
                    workspace.Get();

                    var targetContent = "<?xml version='1.0'?><Component xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://schemas.aitgmbh.de/DependencyManager/2011/11'><Dependencies><Dependency Type='BinaryDependency'><Provider Type='Subversion'><Settings Type='SubversionSettings'><Setting Name='SubversionRootPath' Value='file:///{0}/trunk/lib/ComponentA/1.0' /><Setting Name='VersionSpec' Value='H' /></Settings></Provider></Dependency></Dependencies></Component>";
                    targetContent = string.Format(targetContent, subversionPath);
                    FileHelper.CheckInFolderWithFile(workspace, "Subversion", "component.targets", targetContent);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #44
0
        private TfsTeamProjectCollection GetDependantTfsCollection(NetworkCredential credentials)
        {
            var startTime = DateTime.UtcNow;
            var timer     = System.Diagnostics.Stopwatch.StartNew();
            TfsTeamProjectCollection y;

            try
            {
                Log.Information("TfsMigrationClient::GetDependantTfsCollection:AuthenticationMode({0})", _config.AuthenticationMode.ToString());
                switch (_config.AuthenticationMode)
                {
                case AuthenticationMode.AccessToken:
                    Log.Information("TfsMigrationClient::GetDependantTfsCollection: Connecting with AccessToken ");
                    _vssCredentials = new VssBasicCredential(string.Empty, TfsConfig.PersonalAccessToken);
                    y = new TfsTeamProjectCollection(TfsConfig.Collection, _vssCredentials);
                    break;

                case AuthenticationMode.Windows:
                    Log.Information("TfsMigrationClient::GetDependantTfsCollection: Connecting with NetworkCredential passes on CommandLine ");
                    if (credentials is null)
                    {
                        throw new InvalidOperationException("If AuthenticationMode = Windows then you must pass credentails on the command line.");
                    }
                    _vssCredentials = new VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(credentials));
                    y = new TfsTeamProjectCollection(TfsConfig.Collection, _vssCredentials);
                    break;

                case AuthenticationMode.Prompt:
                    Log.Information("TfsMigrationClient::GetDependantTfsCollection: Prompting for credentials ");
                    y = new TfsTeamProjectCollection(TfsConfig.Collection);
                    break;

                default:
                    Log.Information("TfsMigrationClient::GetDependantTfsCollection: Setting _vssCredentials to Null ");
                    y = new TfsTeamProjectCollection(TfsConfig.Collection);
                    break;
                }
                Log.Information("MigrationClient: Connecting to {CollectionUrl} ", TfsConfig.Collection);
                Log.Information("MigrationClient: validating security for {@AuthorizedIdentity} ", y.AuthorizedIdentity);
                y.EnsureAuthenticated();
                timer.Stop();
                Log.Information("MigrationClient: Access granted to {CollectionUrl} for {Name} ({Account})", TfsConfig.Collection, y.AuthorizedIdentity.DisplayName, y.AuthorizedIdentity.UniqueName);
                _Telemetry.TrackDependency(new DependencyTelemetry("TfsObjectModel", TfsConfig.Collection.ToString(), "GetWorkItem", null, startTime, timer.Elapsed, "200", true));
            }
            catch (Exception ex)
            {
                timer.Stop();
                _Telemetry.TrackDependency(new DependencyTelemetry("TfsObjectModel", TfsConfig.Collection.ToString(), "GetWorkItem", null, startTime, timer.Elapsed, "500", false));
                _Telemetry.TrackException(ex,
                                          new Dictionary <string, string> {
                    { "CollectionUrl", TfsConfig.Collection.ToString() },
                    { "TeamProjectName", TfsConfig.Project }
                },
                                          new Dictionary <string, double> {
                    { "Time", timer.ElapsedMilliseconds }
                });
                Log.Error(ex, "Unable to configure store");
                throw;
            }
            return(y);
        }
예제 #45
0
        private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                NetworkCredential        credential = new NetworkCredential(UserNameBox.Text, PasswordBox.Text);
                TfsTeamProjectCollection tpc        = new TfsTeamProjectCollection(new Uri(TfsURIBox.Text), credential);

                var versionControl = tpc.GetService <Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer>();

                var name = versionControl.AuthenticatedUser;

                tpc.EnsureAuthenticated();

                setProgress(10);

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

                setProgress(20);

                if (changedByRd.Checked)
                {
                    queryResults = workItemStore.Query(changedDateQuery);
                }
                else
                {
                    queryResults = workItemStore.Query(defectQuery);
                }

                addCSVPre();

                int loopItr = 1;

                //Put All items
                foreach (WorkItem item in queryResults)
                {
                    if (progressPercentage <= 70)
                    {
                        setProgress((loopItr / queryResults.Count) * 40, true);
                    }

                    if (changedByRd.Checked)
                    {
                        if (checkRevisions(item, name) == null)
                        {
                            continue;
                        }
                        else
                        {
                            date = checkRevisions(item, name) ?? DateTime.MinValue;
                        }
                    }
                    else
                    {
                        date = Convert.ToDateTime(item["Resolved Date"]);
                    }

                    day = date.DayOfWeek.ToString();

                    int   intDayWeek = (int)date.DayOfWeek;
                    float estimated  = 0;

                    if (item["Development Estimate"] != null)
                    {
                        estimated = (float)Convert.ToDecimal(item["Development Estimate"]);
                    }

                    if (dayDefectTemplate.ContainsKey(date.DayOfWeek.ToString()) && dayDefectTemplate[day] != null)
                    {
                        defectHour = dayDefectTemplate[day];
                        defectHour.Add(item.Id.ToString(), estimated);

                        dayDefectTemplate[day] = defectHour;
                    }
                    else
                    {
                        defectHour = new Dictionary <string, float>();
                        defectHour.Add(item.Id.ToString(), estimated);
                        dayDefectTemplate[day] = defectHour;
                    }

                    loopItr++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please makesure URL/Username/Password is correct", "Fox TimeSheet Exception Handling", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                MessageBox.Show(ex.ToString(), "Fox TimeSheet Exception Handling for Dev", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int loopItr2 = 1;

            //Add hours
            foreach (KeyValuePair <String, Dictionary <string, float> > resItem in dayDefectTemplate)
            {
                defectHour = resItem.Value;

                if (defectHour != null)
                {
                    foreach (KeyValuePair <String, float> defectHourList in defectHour)
                    {
                        if (progressPercentage <= 90)
                        {
                            setProgress((loopItr2 / queryResults.Count) * 20, true);
                        }

                        csvExport.Append(projectNumBox.Text.Trim() + "," + taskBox.Text.Trim() + "," + typeBox.Text.Trim() + ",");

                        String defectNumber = defectHourList.Key.ToString();
                        float  hour         = 8;

                        if (developerEstimateRd.Checked)
                        {
                            if (defectHourList.Value == 0)
                            {
                                hour = hour / defectHour.Count;

                                addPrefix((int)Enum.Parse(typeof(DayOfWeek), resItem.Key, true));
                                csvExport.Append(hour.ToString() + "," + defectNumber + ",");
                                addSuffix((int)Enum.Parse(typeof(DayOfWeek), resItem.Key, true));
                                csvExport.Append(Environment.NewLine);
                            }
                            else
                            {
                                hour = (float)defectHourList.Value;

                                int daysDivide = (int)(hour / 8);

                                hour = hour / daysDivide;

                                addPrefix((int)Enum.Parse(typeof(DayOfWeek), resItem.Key, true));

                                for (int i = 0; i < daysDivide; i++)
                                {
                                    csvExport.Append(hour.ToString() + "," + defectNumber + ",");
                                }

                                addSuffix((int)Enum.Parse(typeof(DayOfWeek), resItem.Key, true));
                                csvExport.Append(Environment.NewLine);
                            }
                        }
                        else
                        {
                            hour = hour / defectHour.Count;

                            addPrefix((int)Enum.Parse(typeof(DayOfWeek), resItem.Key, true));
                            csvExport.Append(hour.ToString() + "," + defectNumber + ",");
                            addSuffix((int)Enum.Parse(typeof(DayOfWeek), resItem.Key, true));
                            csvExport.Append(Environment.NewLine);
                        }

                        loopItr2++;
                    }
                }
            }

            addCSVPost();
            exportFile();
        }
예제 #46
0
        public static object Run(ExportADGroupsOptions opts, string logPath)
        {
            Telemetry.Current.TrackEvent("Run-ExportADGroupsCommand");
            string exportPath = CreateExportPath(logPath, "ExportADGroups");

            Trace.Listeners.Add(new TextWriterTraceListener(Path.Combine(exportPath, "ExportADGroups.log"), "ExportADGroupsCommand"));
            Stopwatch stopwatch = Stopwatch.StartNew();
            //////////////////////////////////////////////////

            StreamWriter sw = File.CreateText(Path.Combine(exportPath, "AzureADGroups.csv"));

            sw.AutoFlush = true;
            using (var csv = new CsvWriter(sw))
            {
                csv.WriteHeader <AzureAdGroupItem>();

                TfsTeamProjectCollection sourceCollection = new TfsTeamProjectCollection(opts.CollectionURL);
                sourceCollection.EnsureAuthenticated();
                IIdentityManagementService2 sourceIMS2         = (IIdentityManagementService2)sourceCollection.GetService(typeof(IIdentityManagementService2));
                List <CatalogNode>          sourceTeamProjects = sourceCollection.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.TeamProject }, false, CatalogQueryOptions.None).ToList();
                if (opts.TeamProject != null)
                {
                    sourceTeamProjects = sourceTeamProjects.Where(x => x.Resource.DisplayName == opts.TeamProject).ToList();
                }
                int current = sourceTeamProjects.Count();
                foreach (CatalogNode sourceTeamProject in sourceTeamProjects)
                {
                    Trace.WriteLine(string.Format("---------------{0}\\{1}", current, sourceTeamProjects.Count()));
                    Trace.WriteLine(string.Format("{0}, {1}", sourceTeamProject.Resource.DisplayName, sourceTeamProject.Resource.Identifier));
                    string projectUri = sourceTeamProject.Resource.Properties["ProjectUri"];
                    TeamFoundationIdentity[] appGroups = sourceIMS2.ListApplicationGroups(projectUri, ReadIdentityOptions.None);
                    foreach (TeamFoundationIdentity appGroup in appGroups.Where(x => !x.DisplayName.EndsWith("\\Project Valid Users")))
                    {
                        Trace.WriteLine(string.Format("    {0}", appGroup.DisplayName));
                        TeamFoundationIdentity sourceAppGroup = sourceIMS2.ReadIdentity(appGroup.Descriptor, MembershipQuery.Expanded, ReadIdentityOptions.None);
                        foreach (IdentityDescriptor child in sourceAppGroup.Members.Where(x => x.IdentityType == "Microsoft.TeamFoundation.Identity"))
                        {
                            TeamFoundationIdentity sourceChildIdentity = sourceIMS2.ReadIdentity(IdentitySearchFactor.Identifier, child.Identifier, MembershipQuery.None, ReadIdentityOptions.ExtendedProperties);

                            if ((string)sourceChildIdentity.GetProperty("SpecialType") == "AzureActiveDirectoryApplicationGroup")
                            {
                                Trace.WriteLine(string.Format("     Suspected AD Group {0}", sourceChildIdentity.DisplayName));
                                csv.WriteRecord <AzureAdGroupItem>(new AzureAdGroupItem
                                {
                                    TeamProject      = sourceTeamProject.Resource.DisplayName,
                                    ApplciationGroup = sourceTeamProject.Resource.DisplayName,
                                    Account          = (string)sourceChildIdentity.GetProperty("Account"),
                                    Mail             = (string)sourceChildIdentity.GetProperty("Mail"),
                                    DirectoryAlias   = (string)sourceChildIdentity.GetProperty("DirectoryAlias")
                                });
                            }
                        }
                    }
                    current--;
                    sw.Flush();
                }
            }
            sw.Close();
            //    current--;
            //}



            //////////////////////////////////////////////////
            stopwatch.Stop();
            Trace.WriteLine(string.Format(@"DONE in {0:%h} hours {0:%m} minutes {0:s\:fff} seconds", stopwatch.Elapsed));
            Trace.Listeners.Remove("ExportADGroupsCommand");
            return(0);
        }
 protected virtual TfsTeamProjectCollection GetTeamProjectCollection()
 {
     if (this.UseSystemCredentials)
     {
         var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(this.BaseUri);
         projectCollection.EnsureAuthenticated();
         return projectCollection;
     }
     else
     {
         var projectColleciton = new TfsTeamProjectCollection(this.BaseUri, new TfsClientCredentials(new WindowsCredential(new NetworkCredential(this.UserName, this.Password, this.Domain))));
         projectColleciton.EnsureAuthenticated();
         return projectColleciton;
     }
 }
예제 #48
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter TFS Server Url: ");
            var serverUrl = Console.ReadLine();

            TfsTeamProjectCollection tfsCollection = new TfsTeamProjectCollection(new Uri(serverUrl));

            tfsCollection.EnsureAuthenticated();

            WorkItemStore store = (WorkItemStore)tfsCollection.GetService(typeof(WorkItemStore));

            Console.WriteLine("Enter TFS Project Name: ");
            var projectName = Console.ReadLine();

            Project project = store.Projects[projectName];

            Console.WriteLine("How many Feature do you want to create?: ");
            var featureCount = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("How many PBIs do you want to create for every feature Item?: ");
            var pbiCount = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("How many Tasks do you want to create for every PBI Item?: ");
            var taskCount = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("How many Bugs do you want to create for every PBI Item?: ");
            var bugCount = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("How many TestCases do you want to create for every PBI Item?: ");
            var testCount = Convert.ToInt32(Console.ReadLine());

            try
            {
                for (int i = 0; i < featureCount; i++)
                {
                    Console.WriteLine("Creating new Feature Work Item ... ");
                    WorkItem workItem = CreateWorkItem(project, "Feature");
                    workItem.Save();

                    for (int j = 0; j < pbiCount; j++)
                    {
                        Console.WriteLine("Creating new Product Backlog Item ... ");
                        WorkItem subItem = CreateWorkItem(project, "Product Backlog Item");
                        SetWorkItemState(subItem, j);
                        WorkItemLinkType hierarchyLinkType = CreateParentChildRelation(store, subItem, workItem.Id);
                        subItem.Save();

                        Console.WriteLine("Creating new Tasks ... ");
                        for (int k = 0; k < taskCount; k++)
                        {
                            WorkItem subsubItem = CreateWorkItem(project, "Task");
                            SetWorkItemState(subsubItem, j);
                            WorkItemLinkType hierarchyLinkType2 = CreateParentChildRelation(store, subsubItem, subItem.Id);
                            subsubItem.Save();
                        }

                        Console.WriteLine("Creating new Bugs ... ");
                        for (int l = 0; l < bugCount; l++)
                        {
                            WorkItem subBugItem = CreateWorkItem(project, "Bug");
                            SetWorkItemState(subBugItem, j);
                            WorkItemLinkType hierarchyLinkType3 = CreateParentChildRelation(store, subBugItem, workItem.Id);
                            CreateSimpleRelation(store, subBugItem, subItem.Id);
                            subBugItem.Save();
                        }

                        Console.WriteLine("Creating new Test Cases ... ");
                        for (int k = 0; k < testCount; k++)
                        {
                            WorkItem subTestItem = CreateWorkItem(project, "Test Case");
                            SetWorkItemState(subTestItem, j);
                            CreateTestRelation(store, subTestItem, subItem.Id);
                            subTestItem.Save();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("********Cannot Save Work Item Relation*********");
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Es wurden {0} Work Items erstellt.", Count.ToString());
            Console.WriteLine("Beenden Sie das Programm mit einer beliebigen Taste ...");
            Console.ReadLine();
        }
예제 #49
0
        Project GetProject()
        {
            if (this.project == null)
            {
                string tfsUrl = ConfigurationManager.AppSettings[tfsUrlKey];
                string projectName = ConfigurationManager.AppSettings[projectNameKey];

                var tfs = new TfsTeamProjectCollection(new Uri(tfsUrl));
                tfs.EnsureAuthenticated();

                workItemStore = tfs.GetService<WorkItemStore>();

                this.project = workItemStore.Projects[projectName];
            }

            return project;
        }
예제 #50
0
        static void Main(string[] args)
        {
            var outFile = ConfigurationManager.AppSettings["OutFile"];
            var usingStdOut = String.IsNullOrWhiteSpace(outFile);
            var outStream = usingStdOut
                                ? Console.OpenStandardOutput()
                                : new FileStream(outFile, FileMode.Create);

            if (!usingStdOut) Console.WriteLine("========================================================================================================================");
            if (!usingStdOut) Console.Write("Creating git-clone of TFS repository:");

            var tfsProjectCollection = ConfigurationManager.AppSettings["TfsTeamProjectCollection"];
            if (String.IsNullOrWhiteSpace(tfsProjectCollection))
                throw new ConfigurationErrorsException(
                    "Error: Missing required setting for TfsTeamProjectCollection in the .exe.config file.");

            var tfsRoot = ConfigurationManager.AppSettings["TfsRoot"];
            if (String.IsNullOrWhiteSpace(tfsRoot))
                throw new ConfigurationErrorsException(
                    "Error: Missing required setting for TfsRoot in the .exe.config file.");

            var skipCommitsSetting = ConfigurationManager.AppSettings["SkipCommits"];
            if (!String.IsNullOrWhiteSpace(skipCommitsSetting))
            {
                skipCommitsSetting.Split(new[] {' ', ',', ';'}, StringSplitOptions.RemoveEmptyEntries)
                                  .ToList()
                                  .ForEach(i => SkipCommits.Add(Int32.Parse(i)));
            }

            if (!usingStdOut) Console.WriteLine("{0}/{1}", tfsProjectCollection, tfsRoot);
            if (!usingStdOut) Console.WriteLine("Fetching list of changesets from TFS...");

            var collection = new TfsTeamProjectCollection(new Uri(tfsProjectCollection));
            collection.EnsureAuthenticated();
            var versionControl = collection.GetService<VersionControlServer>();

            var allChanges = versionControl
                .QueryHistory(
                    tfsRoot,
                    VersionSpec.Latest,
                    0,
                    RecursionType.Full,
                    null,
                    new ChangesetVersionSpec(1),
                    VersionSpec.Latest,
                    int.MaxValue,
                    true,
                    false)
                .OfType<Changeset>()
                .OrderBy(x => x.ChangesetId)
                .ToList();

            var processed = 0;
            var lastChangesetId = allChanges.Last().ChangesetId;
            var sumChanges = allChanges.Sum(x => x.Changes.Count());

            if (!usingStdOut)
            {
                Console.WriteLine("\tFirst changeset-id..: {0:######}", allChanges.First().ChangesetId);
                Console.WriteLine("\tLast  changeset-id..: {0:######}", lastChangesetId);
                Console.WriteLine("\tNo of changesets....: {0:######}", allChanges.Count);
                Console.WriteLine("\tNo of actual changes: {0:######}", sumChanges);
                Console.WriteLine("------------------------------------------------------------------------------------------------------------------------");
            }

            CreateMapDomainList();
            CreateMapMailDomainList();
            InactiveEmailUsernameExtension = ConfigurationManager.AppSettings["InactiveEmailUsernameExtension"];

            foreach (var changeSet in allChanges)
            {
                var beforeProcessing = processed;
                processed += changeSet.Changes.Count();

                if (SkipCommits.Contains(changeSet.ChangesetId))
                {
                    if (!usingStdOut) Console.WriteLine("Skipping configuratively excluded changeset: {0}", changeSet.ChangesetId);
                    continue;
                }

                if (!usingStdOut) Console.Write("Progress: {1,6:##0.00%} Changeset: {0,6} > ", changeSet.ChangesetId, ((float)beforeProcessing) / sumChanges);

                if (BreakCommits.Contains(changeSet.ChangesetId))
                {
                    System.Diagnostics.Debugger.Break();
                }

                var commit = new TfsChangeSet(changeSet).ProcessChangeSet(usingStdOut);
                if (commit == null)
                {
                    if (!usingStdOut) Console.WriteLine(" Ops! Skipping 'null-commit' changeset.");
                    continue;
                }

                if (!usingStdOut) Console.WriteLine(".");
                outStream.RenderCommand(commit);
                outStream.WriteLine(string.Format("progress {0}/{1}", changeSet.ChangesetId, lastChangesetId));
            }
            outStream.WriteLine("done");
            outStream.Close();
            if (!usingStdOut) Console.WriteLine("========================================================================================================================");
        }
예제 #51
0
        public async Task GetTopChangedFiles()
        {
            //Criteria used to limit results
            var maxChangesToConsider = 1000;
            var maxResults           = 10;
            var fromDate             = DateTime.Now.AddDays(-10);
            var toDate            = DateTime.Now;
            var maxResultsPerPath = 100;

            var fileExtensionToInclude = new List <string> {
                ".cs", ".js"
            };
            var extensionExclusions = new List <string> {
                ".csproj", ".json", ".css"
            };
            var fileExclusions = new List <string> {
                "AssemblyInfo.cs", "jquery-1.12.3.min.js", "config.js"
            };

            //var pathExclusions = new List<string> {
            //    "/subdirToForceExclude1/",
            //    "/subdirToForceExclude2/",
            //    "/subdirToForceExclude3/",
            //};

            using (var collection = new TfsTeamProjectCollection(new Uri(tfsConfig.TfsUrl),
                                                                 new NetworkCredential(userName: tfsConfig.UserName, password: tfsConfig.Password
                                                                                       , domain: tfsConfig.Domain
                                                                                       )))
            {
                collection.EnsureAuthenticated();


                //Set up date-range criteria for query
                var criteria = new TfvcChangesetSearchCriteria
                {
                    FromDate = fromDate.ToShortDateString(),
                    ToDate   = toDate.ToShortDateString(),
                    //FromId = 48503,
                    //ToId = 66416,
                    //IncludeLinks = true,
                    //ItemPath = @"$/GSP6.1/Dev/"
                    ItemPath = @"$/GSP6/Dev/"
                };

                var tfvc = collection.GetService(typeof(VersionControlServer)) as VersionControlServer;

                //Get changesets
                //Note: maxcount set to maxvalue since impact to server is minimized by linq query below
                var changeSets = tfvc.QueryHistory(path: criteria.ItemPath, version: VersionSpec.Latest,
                                                   deletionId: 0, recursion: RecursionType.Full, user: null,
                                                   versionFrom: new DateVersionSpec(fromDate), versionTo: new DateVersionSpec(toDate),
                                                   maxCount: int.MaxValue, includeChanges: true,
                                                   includeDownloadInfo: false, slotMode: true)
                                 as IEnumerable <Changeset>;

                Console.WriteLine("from{0} to {1} changeset count{2} from id:{3}to id:{4}", fromDate.ToShortDateString(),
                                  toDate.ToShortDateString(), changeSets.Count(), changeSets.First().ChangesetId, changeSets.Last().ChangesetId);
                //Filter changes contained in changesets
                var changes = changeSets.SelectMany(a => a.Changes)
                              .Where(a => a.ChangeType != ChangeType.Lock || a.ChangeType != ChangeType.Delete || a.ChangeType != ChangeType.Property)
                              //.Where(e => !e.Item.ServerItem.ContainsAny(pathExclusionspathExclusions))
                              .Where(e => e.Item.ServerItem.LastIndexOf('.') >= 0)
                              .Where(e => !e.Item.ServerItem.Substring(e.Item.ServerItem.LastIndexOf('/') + 1).ContainsAny(fileExclusions))

                              .Where(e => !e.Item.ServerItem.Substring(e.Item.ServerItem.LastIndexOf('.')).ContainsAny(extensionExclusions))
                              .Where(e => e.Item.ServerItem.Substring(e.Item.ServerItem.LastIndexOf('.')).ContainsAny(fileExtensionToInclude))
                              .GroupBy(g => g.Item.ServerItem)
                              .Select(d => new { File = d.Key, Count = d.Count() })
                              .OrderByDescending(o => o.Count)
                              .Take(maxResultsPerPath)
                ;


                //Write top items for each path to the console
                Console.WriteLine(criteria.ItemPath); Console.WriteLine("->");
                foreach (var change in changes)
                {
                    Console.WriteLine("ChangeCount: {0} : File: {1}", change.Count, change.File);
                }
                Console.WriteLine(Environment.NewLine);
            }
        }
		private VersionControlServer GetVersionControl(ISourceControlConnectionSettingsSource settings)
		{
			VersionControlServer versionControl;

			TfsConnectionParameters parameters = TfsConnectionHelper.GetTfsConnectionParameters(settings);

			switch (parameters.SegmentsCount)
			{
				case UriTfsProjectCollection:
					{
						_teamProjectCollection = new TfsTeamProjectCollection(parameters.TfsCollectionUri, parameters.Credential);
						_teamProjectCollection.EnsureAuthenticated();

						versionControl = _teamProjectCollection.GetService<VersionControlServer>();
						_teamProjects = versionControl.GetAllTeamProjects(false);

						break;
					}
				case UriTfsTeamProject:
					{
						_teamProjectCollection = new TfsTeamProjectCollection(parameters.TfsCollectionUri, parameters.Credential);
						_teamProjectCollection.EnsureAuthenticated();

						try
						{
							versionControl = _teamProjectCollection.GetService<VersionControlServer>();
							_teamProjects = new[] { versionControl.GetTeamProject(parameters.TeamProjectName) };
						}
						catch (Microsoft.TeamFoundation.VersionControl.Client.VersionControlException)
						{
							var gitRepositoryService = _teamProjectCollection.GetService<GitRepositoryService>();
							var gitRepositories = gitRepositoryService.QueryRepositories(parameters.TeamProjectName);
							var gitRepository = gitRepositories.Single(gr => gr.Name.Equals(parameters.TeamProjectName));
							if (gitRepository != null)
							{
								throw new VersionControlException($"Git team project is not supported, use Git plugin with '{gitRepository.RemoteUrl}' instead.");
							}
							throw;
						}
						break;
					}
				default:
					throw new Exception("Wrong URI format.");
			}

			return versionControl;
		}
예제 #53
0
        private TfsTeamProjectCollection m_server = null;   // Team foundation server
        // private TeamFoundationServer m_server = null;


        public PostBeta2TeamFoundationServiceProvider(string serverUrl)
        {
            m_server = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverUrl));
            // m_server = new TeamFoundationServer(serverUrl);
            m_server.EnsureAuthenticated();
        }
예제 #54
0
        //private readonly TfsTeamService teamService;
        //private readonly ProjectInfo projectInfo;
        public override int RunInternal(ExportPicturesOptions opts)
        {
            if (!Directory.Exists(opts.OutPath))
            {
                Directory.CreateDirectory(opts.OutPath);
            }

            TfsTeamProjectCollection collection = new TfsTeamProjectCollection(opts.CollectionURL);

            collection.EnsureAuthenticated();
            IIdentityManagementService2 ims2 = (IIdentityManagementService2)collection.GetService(typeof(IIdentityManagementService2));
            TeamFoundationIdentity      SIDS = ims2.ReadIdentity(IdentitySearchFactor.AccountName, "Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);

            Trace.WriteLine(string.Format("Found {0}", SIDS.Members.Count()));
            var itypes = (from IdentityDescriptor id in SIDS.Members select id.IdentityType).Distinct();

            foreach (string item in itypes)
            {
                var infolks = (from IdentityDescriptor id in SIDS.Members where id.IdentityType == item select id);
                Trace.WriteLine(string.Format("Found {0} of {1}", infolks.Count(), item));
            }
            var folks = (from IdentityDescriptor id in SIDS.Members where id.IdentityType == "System.Security.Principal.WindowsIdentity" || id.IdentityType == "Microsoft.IdentityModel.Claims.ClaimsIdentity" select id);

            DirectoryContext objContext = new DirectoryContext(DirectoryContextType.Domain, opts.Domain, opts.Username, opts.Password);
            Domain           objDomain  = Domain.GetDomain(objContext);
            string           ldapName   = string.Format("LDAP://{0}", objDomain.Name);

            int current = folks.Count();

            foreach (IdentityDescriptor id in folks)
            {
                try
                {
                    TeamFoundationIdentity i = ims2.ReadIdentity(IdentitySearchFactor.Identifier, id.Identifier, MembershipQuery.Direct, ReadIdentityOptions.None);
                    Trace.WriteLine(i.DisplayName);
                    if (!(i == null) && (i.IsContainer == false))
                    {
                        if ((!i.DisplayName.StartsWith("Microsoft.") && (!i.DisplayName.StartsWith("OssManagement"))))
                        {
                            DirectoryEntry    d        = new DirectoryEntry(ldapName, opts.Username, opts.Password);
                            DirectorySearcher dssearch = new DirectorySearcher(d);
                            if (i.UniqueName.Contains("@"))
                            {
                                dssearch.Filter = string.Format("(sAMAccountName={0})", i.UniqueName.Split(char.Parse(@"@"))[0]);
                            }
                            else
                            {
                                dssearch.Filter = string.Format("(sAMAccountName={0})", i.UniqueName.Split(char.Parse(@"\"))[1]);
                            }

                            SearchResult sresult   = dssearch.FindOne();
                            WebClient    webClient = new WebClient();
                            webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                            if (sresult != null)
                            {
                                string newImage = Path.Combine(opts.OutPath, string.Format("{0}.jpg", i.UniqueName.Replace(@"\", "-")));
                                if (!File.Exists(newImage))
                                {
                                    DirectoryEntry deUser = new DirectoryEntry(sresult.Path, opts.Username, opts.Password);
                                    Trace.WriteLine(string.Format("{0} [PROCESS] {1}: {2}", current, deUser.Name, newImage));
                                    string empPic = string.Format(opts.CorporatePictureMask, deUser.Properties[opts.ADPropertyName].Value);
                                    try
                                    {
                                        webClient.DownloadFile(empPic, newImage);
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.WriteLine(string.Format("      [ERROR] {0}", ex.ToString()));
                                    }
                                }
                                else
                                {
                                    Trace.WriteLine(string.Format("{0} [SKIP] Exists {1}", current, newImage));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("      [ERROR] {0}", ex.ToString()));
                }

                current--;
            }
            return(0);
        }
예제 #55
0
        public void Connect(string url, string project, string workItemQuery, string ignoreRemainingArea, string activeState, string closedState)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentNullException("url");
            }
            if (string.IsNullOrWhiteSpace(project))
            {
                throw new ArgumentNullException("project");
            }
            if (string.IsNullOrWhiteSpace(workItemQuery))
            {
                throw new ArgumentNullException("workItemQuery");
            }
            if (string.IsNullOrWhiteSpace(ignoreRemainingArea))
            {
                throw new ArgumentNullException("ignoreRemainingArea");
            }
            if (string.IsNullOrWhiteSpace(activeState))
            {
                throw new ArgumentNullException("activeState");
            }
            if (string.IsNullOrWhiteSpace(closedState))
            {
                throw new ArgumentNullException("closedState");
            }

            _url = url;
            _project = project;
            _ignoreRemainingArea = ignoreRemainingArea;
            _activeState = activeState;
            _closedState = closedState;

            _tfs = new TfsTeamProjectCollection(new Uri(url));
            _tfs.EnsureAuthenticated();

            _workItemStore = _tfs.GetService<WorkItemStore>();
            _commonStructureService = _tfs.GetService<ICommonStructureService4>();

            _workitemQueryText = GetWorkitemQueryText(workItemQuery);
        }
예제 #56
0
        private VersionControlServer GetTfsVersionControlServer(string tfsCollectionUri)
        {
            /*NetworkCredential netCred = new NetworkCredential("**", "**", "**");
            BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
            TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
            tfsCred.AllowInteractive = false;
            */

            var collection = new TfsTeamProjectCollection(new Uri(tfsCollectionUri));

            //collection.Authenticate();

            collection.EnsureAuthenticated();
            return collection.GetService<VersionControlServer>();
        }
 public void Connect()
 {
     m_tpc.EnsureAuthenticated();
     m_vcs = m_tpc.GetService <VersionControlServer>();
 }
예제 #58
0
 private void GetWorkItemStore(string projectName)
 {
     string uri = ConfigurationManager.AppSettings["TFSServer"];
     string userName = ConfigurationManager.AppSettings["UserName"];
     string password = ConfigurationManager.AppSettings["UserPw"];
     string domain = ConfigurationManager.AppSettings["Domain"];
     tfs = new TfsTeamProjectCollection(new Uri(uri), new NetworkCredential(userName, password, domain));
     try
     {
         tfs.EnsureAuthenticated();
     }
     catch (Exception ex)
     {
         log.Error("Connection TFS Server Error", ex);
         return;
     }
     if (tfs.HasAuthenticated)
     {
         try
         {
             WorkItemStore Store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore));
             if (Store.Projects.Contains(projectName))
             {
                 project = Store.Projects[projectName];
             }
             else
             {
                 log.Error("Get project Error. may be the project not exist");
             }
         }
         catch (Exception ex)
         {
             log.Error("Get Project Error", ex);
         }
     }
 }
예제 #59
0
        public async Task GetTopChangedFiles()
        {
            //Criteria used to limit results
            var maxChangesToConsider = 1000;
            var maxResults = 10;
            var fromDate = DateTime.Now.AddDays(-182);
            var toDate = DateTime.Now;
            var maxResultsPerPath = 100;

            var fileExtensionToInclude = new List<string> { ".cs", ".js" };
            var extensionExclusions = new List<string> { ".csproj", ".json", ".css" };
            var fileExclusions = new List<string> { "AssemblyInfo.cs", "jquery-1.12.3.min.js", "config.js" };
            //var pathExclusions = new List<string> {
            //    "/subdirToForceExclude1/",
            //    "/subdirToForceExclude2/",
            //    "/subdirToForceExclude3/",
            //};

            using (var collection = new TfsTeamProjectCollection(new Uri(tfsConfig.TfsUrl),
                new NetworkCredential(userName: tfsConfig.UserName, password: tfsConfig.Password
                    , domain: tfsConfig.Domain
                    )))
            {
                collection.EnsureAuthenticated();


                //Set up date-range criteria for query
                var criteria = new TfvcChangesetSearchCriteria
                {
                    FromDate = fromDate.ToShortDateString(),
                    ToDate = toDate.ToShortDateString(),
                    //FromId = 48503,
                    //ToId = 66416,
                    //IncludeLinks = true,
                    //ItemPath = @"$/GSP6.1/Dev/"
                    ItemPath = @"$/GSP6/Dev/"
                };

                var tfvc = collection.GetService(typeof(VersionControlServer)) as VersionControlServer;

                //Get changesets
                //Note: maxcount set to maxvalue since impact to server is minimized by linq query below
                var changeSets = tfvc.QueryHistory(path: criteria.ItemPath, version: VersionSpec.Latest,
                    deletionId: 0, recursion: RecursionType.Full, user: null,
                    versionFrom: new DateVersionSpec(fromDate), versionTo: new DateVersionSpec(toDate),
                    maxCount: int.MaxValue, includeChanges: true,
                    includeDownloadInfo: false, slotMode: true)
                    as IEnumerable<Changeset>;

                Console.WriteLine("from{0} to {1} changeset count{2} from id:{3}to id:{4}", fromDate.ToShortDateString(),
                    toDate.ToShortDateString(), changeSets.Count(), changeSets.First().ChangesetId, changeSets.Last().ChangesetId);
                //Filter changes contained in changesets
                var changes = changeSets.SelectMany(a => a.Changes)
                .Where(a => a.ChangeType != ChangeType.Lock || a.ChangeType != ChangeType.Delete || a.ChangeType != ChangeType.Property)
                //.Where(e => !e.Item.ServerItem.ContainsAny(pathExclusionspathExclusions))
                .Where(e => e.Item.ServerItem.LastIndexOf('.') >= 0)
                .Where(e => !e.Item.ServerItem.Substring(e.Item.ServerItem.LastIndexOf('/') + 1).ContainsAny(fileExclusions))

                .Where(e => !e.Item.ServerItem.Substring(e.Item.ServerItem.LastIndexOf('.')).ContainsAny(extensionExclusions))
                .Where(e => e.Item.ServerItem.Substring(e.Item.ServerItem.LastIndexOf('.')).ContainsAny(fileExtensionToInclude))
                .GroupBy(g => g.Item.ServerItem)
                .Select(d => new { File = d.Key, Count = d.Count() })
                .OrderByDescending(o => o.Count)
                .Take(maxResultsPerPath)
                ;


                //Write top items for each path to the console
                Console.WriteLine(criteria.ItemPath); Console.WriteLine("->");
                foreach (var change in changes)
                {
                    Console.WriteLine("ChangeCount: {0} : File: {1}", change.Count, change.File);
                }
                Console.WriteLine(Environment.NewLine);

            }
        }
 /// <summary>
 /// Connects to the Project Collection
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnConnect_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (cboServer.Text != string.Empty)
         {
             Mouse.OverrideCursor = Cursors.Wait;
             _tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(cboServer.Text),
                 new UICredentialsProvider());
             _tfs.EnsureAuthenticated();
             LoadProjects();
             _wis = (WorkItemStore)_tfs.GetService(typeof(WorkItemStore));
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         Mouse.OverrideCursor = null;
     }
 }