コード例 #1
0
        /// <summary>
        /// connect to a TFS Server.
        /// </summary>
        /// <param name="tfsUri">Possible URI of the TFS Server</param>
        /// <returns>The correct Tfs Uri</returns>
        public Uri ConnectToTfsServer(Uri tfsUri)
        {
            bool tfsIsConnected = false;

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

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

            if (tfsIsConnected)
            {
                FetchProjects();
            }

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

            tfsCred.AllowInteractive = false;

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

            configurationServer.Authenticate();
            return(configurationServer);

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

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

            return(tfs);
        }
コード例 #3
0
        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
ファイル: TfsManager.cs プロジェクト: mguerrer/Salma
        /// <summary>
        /// The get catalog nodes.
        /// </summary>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <returns>
        /// The <see cref="List"/>.
        /// </returns>
        private List <CatalogNode> GetCatalogNodes(Uri uri, ICredentials cred, bool anotherUser)
        {
            List <CatalogNode> catalogNodes = null;

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

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

            return(catalogNodes);
        }
コード例 #5
0
ファイル: MyTfsServer.cs プロジェクト: pmiossec/SirenOfShame
 public MyTfsServer(CiEntryPointSetting ciEntryPointSetting)
 {
     try {
         _tfsConfigurationServer = GetTfsConfigurationServer(ciEntryPointSetting.Url, ciEntryPointSetting.UserName, ciEntryPointSetting.GetPassword());
         _tfsConfigurationServer.EnsureAuthenticated();
     } catch (TeamFoundationServiceUnavailableException ex) {
         _log.Debug(ex);
         throw new ServerUnavailableException(ex.Message, ex);
     }
 }
コード例 #6
0
 public MyTfsServer(CiEntryPointSetting ciEntryPointSetting)
 {
     try {
         _tfsConfigurationServer = GetTfsConfigurationServer(ciEntryPointSetting.Url, ciEntryPointSetting.UserName, ciEntryPointSetting.GetPassword());
         _tfsConfigurationServer.EnsureAuthenticated();
     } catch (TeamFoundationServiceUnavailableException ex) {
         _log.Debug(ex);
         throw new ServerUnavailableException(ex.Message, ex);
     }
 }
コード例 #7
0
ファイル: TFHelper.cs プロジェクト: apetrovskiy/STUPS
        public static void ConnectTFServer(TFSCmdletBase cmdlet, string url, ICredentials credentials)
        {
            try
            {
                Uri uri =
                    new Uri(url);
                
                TfsConfigurationServer tfsServer =
                    new TfsConfigurationServer(
                        uri,
                        credentials);
                
                cmdlet.WriteVerbose(
                    cmdlet,
                    "Connected, checking the connection");
                
                try {
                    tfsServer.EnsureAuthenticated();
                }
                catch (Exception eTfsServerConnected) {
                    
                    cmdlet.WriteError(
                        cmdlet,
                        "Failed to connect to server '" +
                        url +
                        "'." +
                        eTfsServerConnected.Message,
                        "FailedToConnect",
                        ErrorCategory.InvalidResult,
                        true);
                }
                
                CurrentData.CurrentServer = tfsServer;
                
                cmdlet.WriteVerbose(cmdlet,
                                    "Connected to: '" +
                                    url + 
                                    "'");
                
                cmdlet.WriteObject(cmdlet, tfsServer);
            }
//            catch (TeamFoundationServerUnauthorizedException ex)
//            {
//                // handle access denied
//            }
//            catch (TeamFoundationServiceUnavailableException ex)
//            {
//                // handle service unavailable
//            }
            catch (WebException ex)
            {
                // handle other web exception
            }
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: kulcsar/alm-syncusers
        private static TfsConfigurationServer Connect(string tfsServerUrl)
        {
            // Set the URI of the Team Foundation Server
            Uri tfsServerUri = new Uri(tfsServerUrl);

            // Get a TfsConfigurationServer instance
            TfsConfigurationServer configServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsServerUri);

            configServer.EnsureAuthenticated();

            return(configServer);
        }
コード例 #9
0
        public static void ConnectTFServer(TFSCmdletBase cmdlet, string url, ICredentials credentials)
        {
            try
            {
                Uri uri =
                    new Uri(url);

                TfsConfigurationServer tfsServer =
                    new TfsConfigurationServer(
                        uri,
                        credentials);

                cmdlet.WriteVerbose(
                    cmdlet,
                    "Connected, checking the connection");

                try {
                    tfsServer.EnsureAuthenticated();
                }
                catch (Exception eTfsServerConnected) {
                    cmdlet.WriteError(
                        cmdlet,
                        "Failed to connect to server '" +
                        url +
                        "'." +
                        eTfsServerConnected.Message,
                        "FailedToConnect",
                        ErrorCategory.InvalidResult,
                        true);
                }

                CurrentData.CurrentServer = tfsServer;

                cmdlet.WriteVerbose(cmdlet,
                                    "Connected to: '" +
                                    url +
                                    "'");

                cmdlet.WriteObject(cmdlet, tfsServer);
            }
//            catch (TeamFoundationServerUnauthorizedException ex)
//            {
//                // handle access denied
//            }
//            catch (TeamFoundationServiceUnavailableException ex)
//            {
//                // handle service unavailable
//            }
            catch (WebException ex)
            {
                // handle other web exception
            }
        }
コード例 #10
0
        public Boolean Connect()
        {
            //Connect or reconnect if needed.
            if (!IsConnected || _Server == null || _Server.Uri != _Configuration.TFSUri)
            {
                Disconnect();                 //Disconnect first if needed.

                _Server = _Configuration.UseLocalAccount || _Configuration.NetworkCredential == null
                                                ? new TfsConfigurationServer(_Configuration.TFSUri)
                                                : new TfsConfigurationServer(_Configuration.TFSUri, _Configuration.NetworkCredential);

                _Server.EnsureAuthenticated();
                IsConnected = true;
            }

            return(IsConnected);
        }
コード例 #11
0
ファイル: TfsHelperClass.cs プロジェクト: iozag/Buildscreen
        public TfsConfigurationServer GetTfsServer()
        {
            TfsConfigurationServer server = null;
            try
            {
                var tfsUri = new Uri(_configurationTfsService.Uri);
                var credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(_configurationTfsService.Username, _configurationTfsService.Password)));
                server = new TfsConfigurationServer(tfsUri, credentials);
                server.EnsureAuthenticated();

            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }
            return server;
        }
コード例 #12
0
ファイル: TfsHelperClass.cs プロジェクト: szelin/Buildscreen
        public TfsConfigurationServer GetTfsServer()
        {
            TfsConfigurationServer server = null;

            try
            {
                var tfsUri      = new Uri(_configurationTfsService.Uri);
                var credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(_configurationTfsService.Username, _configurationTfsService.Password)));
                server = new TfsConfigurationServer(tfsUri, credentials);
                server.EnsureAuthenticated();
            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }
            return(server);
        }
コード例 #13
0
        private static void QueueADSyncJob()
        {
            //cHANGE THE LIBRARIES UNDER THE DLL FOLDER WITH THE VERSIONS YOU COPY FROM YOUR SERVER FOLDER.
            //EG FOR 2020, C:\Program Files\Azure DevOps Server 2020\Tools
            //THEN CHANGE THE REFERENCES
            string _myUri = @"YOUR_SERVER_URL";  //REPLACE WITH YOUR SERVER URL
            Guid   adSync = new Guid("544dd581-f72a-45a9-8de0-8cd3a5f29dfe");

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

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

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

            Console.WriteLine("Job Triggered");
            Console.ReadLine();
        }
コード例 #14
0
        public static TfsConfigurationServer AuthenticateToTFSService()
        {
            Uri VSOnlineUri = new Uri(GetConfigValue("$Instance.VSOnlineUri$"));

            //If you only provide the server's uri when connecting to TFS, the caller's Windows credentials will be used
            TfsConfigurationServer tfs = TfsConfigurationServerFactory.GetConfigurationServer(VSOnlineUri);

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

            return(tfs);
        }
コード例 #15
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            bool fromCookie = false;
            var userDataPrincipal = HttpContext.Current.User as UserDataPrincipal;
            if (userDataPrincipal == null)
            {
                userDataPrincipal = UserDataPrincipal.InitFromHeaders(actionContext.Request.Headers);
            }
            if (userDataPrincipal == null)
            {
                userDataPrincipal = UserDataPrincipal.InitFromAuthCookie(actionContext.Request.Headers);
                fromCookie = true;
            }

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

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

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

                tfsConfigServer.EnsureAuthenticated();

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

            HttpContext.Current.User = userDataPrincipal;

            base.OnActionExecuting(actionContext);
        }
コード例 #16
0
        public void AnalyzeRepository(string repository, bool verbose)
        {
            ConsolePrinter.Log("Analyzing TFS Source Control on server '{0}'", repository);
            if (String.IsNullOrWhiteSpace(repository))
            {
                throw new CommandLineException(AnalyzeCommandResources.AnalyzeCommandRepositoryRequired);
            }

            Uri tfsUri = new Uri(repository);
            TfsConfigurationServer tfs = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri, new UICredentialsProvider());

            tfs.EnsureAuthenticated();

            IDictionary <TfsTeamProjectCollection, ReadOnlyCollection <CatalogNode> > teamProjectCollectionInfo
                = GetTeamProjectCollectionsWithTeamProjectCatalogNodes(tfs);

            foreach (KeyValuePair <TfsTeamProjectCollection, ReadOnlyCollection <CatalogNode> > teamProjectCollectionKvp in teamProjectCollectionInfo)
            {
                AnalyzeTfsTeamProjectCollection(teamProjectCollectionKvp, verbose);
            }
        }
コード例 #17
0
        public bool CanConnect(Uri tfsUri, NetworkCredential credentials)
        {
            Guard.NotNull(tfsUri, credentials);

            bool canConnect;

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

            return(canConnect);
        }
コード例 #18
0
        public ActionResult Search(string id, string search)
        {
            try
            {
                ItemWidgetArguments args = new ItemWidgetArguments(UserContext, GeminiContext, Cache, System.Web.HttpContext.Current.Request, CurrentIssue);

                TFSPicker tfsPicker = new TFSPicker();

                tfsPicker.AuthenticateUser(args);

                UserWidgetDataDetails loginDetails = tfsPicker.getLoginDetails();

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

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

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

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

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

                configurationServer.Credentials = iCred;

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

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

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

                CatalogNode catalogNode = configurationServer.CatalogNode;

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

                string url = string.Empty;

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

                TfsTeamProjectCollection tpc = null;

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

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

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

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

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

                    var result = workItemStore.Query(query);

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

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

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

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

                            queryResults.Add(item);
                        }
                    }
                }

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

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

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

                        data.AppId = Constants.AppId;

                        data.ControlId = Constants.ControlId;

                        data.IssueId = id.ToInt();

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

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

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

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

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

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

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

                successView = false;

                messageView = ex.Message;

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

            return(JsonSuccess(new { success = successView, data = dataView, message = messageView }));
        }
コード例 #19
0
ファイル: TfsManager.cs プロジェクト: nkravch/SALMA-2.0
        /// <summary>
        /// The get catalog nodes.
        /// </summary>
        /// <param name="uri">
        /// The uri.
        /// </param>
        /// <returns>
        /// The <see cref="List"/>.
        /// </returns>
        private List<CatalogNode> GetCatalogNodes(Uri uri, ICredentials cred, bool anotherUser)
        {
            List<CatalogNode> catalogNodes = null;
            try
            {

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

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

            return catalogNodes;
        }
コード例 #20
0
        private static async Task<bool> CanLogIn(string username, string password, string uri, string configType)
        {
            bool response = false;

            HttpClientHandler httpClientHandler = null;
            // VSO check
            if (configType == "VSO")
            {
                using (var client = CreateAuthenticationClient(uri, username, password))
                {
                    client.BaseAddress = new Uri(uri);
                    
                    Debug.WriteLine("Code: " + client.GetAsync("").Result.StatusCode);
                    response = client.GetAsync("").Result.StatusCode == HttpStatusCode.OK;
                }
            }
            // TFS check
            else if (configType == "TFS")
            {
                var credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(username, password)));
                var server = new TfsConfigurationServer(new Uri(uri), credentials);
                try
                {
                    server.EnsureAuthenticated();
                }
                catch (TeamFoundationServerUnauthorizedException e)
                {
                    return false;
                }
                response = server.HasAuthenticated;
            }
            return response;
        }
コード例 #21
0
 private static async Task<bool> CanLogIn(string username, string password, string uri, string configType)
 {
     bool response = false;
     try
     {
         // VSO check
         if (configType == "VSO")
         {
             using (var client = new HttpClient())
             {
                 client.BaseAddress = new Uri(uri);
                 client.DefaultRequestHeaders.Accept.Clear();
                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                     Convert.ToBase64String(
                         Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))));
                 Debug.WriteLine("Code: " + client.GetAsync("").Result.StatusCode);
                 response = client.GetAsync("").Result.StatusCode == HttpStatusCode.OK;
             }
         }
         // TFS check
         else if (configType == "TFS")
         {
             var credentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential(username, password)));
             var server = new TfsConfigurationServer(new Uri(uri), credentials);
             server.EnsureAuthenticated();
             response = server.HasAuthenticated;
         }
     }
     catch (Exception e)
     { 
         LogService.WriteError(e);
         throw;
     }
     return response;
 }
コード例 #22
0
        public WorkItem GetItem(string id, out string url)
        {
            url = null;

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

            ICredentials iCred = new NetworkCredential(Username, Password);

            connect.setLoginDetails(Username, Password, RepositoryUrl);

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

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


            configurationServer.Credentials = iCred;

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

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

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

            CatalogNode catalogNode = configurationServer.CatalogNode;

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

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

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

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

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

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

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

                    return(item);
                }
            }

            return(null);
        }
コード例 #23
0
        public ActionResult Authenticate(int issueId)
        {
            //Authentication
            string username = Request["username"] ?? string.Empty;

            string password = Request["password"] ?? string.Empty;

            string repositoryUrl = Request["repositoryurl"] ?? string.Empty;

            string message = string.Empty;

            bool success = true;

            string dataView = string.Empty;

            if (username.IsEmpty() || password.IsEmpty() || repositoryUrl.IsEmpty())
            {
                message = "Please make sure Username, Password and Url are not empty";
                success = false;
            }

            if (success)
            {
                UserWidgetDataDetails userData = new UserWidgetDataDetails();

                userData.Username = username.Trim();

                userData.Password = SecretsHelper.Encrypt(password.Trim(), SecretsHelper.EncryptionKey);

                userData.RepositoryUrl = repositoryUrl.Trim();

                SaveLoginDetails(CurrentUser, userData, GeminiContext);

                TFSPicker tfsPicker = new TFSPicker();

                try
                {
                    ItemWidgetArguments args = new ItemWidgetArguments(UserContext, GeminiContext, Cache, System.Web.HttpContext.Current.Request, CurrentIssue);

                    tfsPicker.AuthenticateUser(args);

                    UserWidgetDataDetails loginDetails = tfsPicker.getLoginDetails();

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

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

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

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

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


                    configurationServer.Credentials = iCred;

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

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

                        if (TFSPicker.IsBasicAuth)
                        {
                            configurationServer.ClientCredentials = new TfsClientCredentials(new BasicAuthCredential(iCred));
                        }
                        else
                        {
                            configurationServer.ClientCredentials = new TfsClientCredentials(new WindowsCredential(iCred));
                        }
                        configurationServer.EnsureAuthenticated();
                    }
                }
                catch (Exception ex)
                {
                    var logindetails = GeminiContext.UserWidgetStore.Get <UserWidgetDataDetails>(CurrentUser.Entity.Id, Constants.AppId, Constants.ControlId);

                    if (logindetails != null)
                    {
                        GeminiContext.UserWidgetStore.Delete(logindetails.Id);
                    }

                    success = false;

                    message = ex.Message;

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

                    return(JsonSuccess(new { success = success, message = message }));
                }

                tfsPicker.setLoginDetails(userData.Username, password.Trim(), userData.RepositoryUrl);

                WidgetResult result = new WidgetResult();

                List <string> tfsDetails = new List <string>();

                IssueWidgetData <List <string> > data = GeminiContext.IssueWidgetStore.Get <List <string> >(issueId, Constants.AppId, Constants.ControlId);

                if (data != null && data.Value != null && data.Value.Count > 0)
                {
                    tfsDetails = data.Value;
                }

                List <WorkItem> details = new List <WorkItem>();

                foreach (var tfs in tfsDetails)
                {
                    try
                    {
                        string url;

                        UserWidgetDataDetails loginDetails = tfsPicker.getLoginDetails();

                        if (Username.IsEmpty())
                        {
                            Username = loginDetails.Username;
                        }

                        if (Password.IsEmpty())
                        {
                            Password = loginDetails.Password;
                        }

                        if (RepositoryUrl.IsEmpty())
                        {
                            RepositoryUrl = loginDetails.RepositoryUrl;
                        }

                        var item = GetItem(tfs, out url);

                        if (item != null)
                        {
                            details.Add(item);
                        }
                    }
                    catch (Exception ex)
                    {
                        success = false;

                        message = ex.Message;

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

            return(JsonSuccess(new { success = success, message = message }));
        }
コード例 #24
0
        public string GetFileContent(GeminiContext gemini, int issueid, string filename, string fullfilename, string workspace, string changesetid, string fileid, string repositoryUrl, bool getPreviousRevision = false)
        {
            ConnectByImplementingCredentialsProvider connect = new ConnectByImplementingCredentialsProvider();

            ICredentials iCred = new NetworkCredential(Username, Password);

            connect.setLoginDetails(Username, Password, workspace);

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

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

            configurationServer.Credentials = iCred;


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

            configurationServer.EnsureAuthenticated();

            CatalogNode catalogNode = configurationServer.CatalogNode;

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

            foreach (CatalogNode tpcNode in tpcNodes)
            {
                Guid tpcId = new Guid(tpcNode.Resource.Properties["InstanceId"]);

                TfsTeamProjectCollection tpc = configurationServer.GetTeamProjectCollection(tpcId);

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

                VersionControlServer versionControl = (VersionControlServer)tpc.GetService(typeof(VersionControlServer));

                Item file = null;

                try
                {
                    //IF file was just added in tfs
                    if (fileid.ToInt() == 0)
                    {
                        Item tmpFile = null;
                        //Need to catch error if file was deleted, we'll get an error and call the file with parameters as below.
                        //This would only happen to newly added file, which will not have a itemid as we wouldn't know what it is on first commit of a file
                        try
                        {
                            tmpFile = versionControl.GetItem(string.Concat(fullfilename, "/", filename));
                        }
                        catch (VersionControlException ex)
                        {
                            tmpFile = versionControl.GetItem(fullfilename + "/" + filename, VersionSpec.Latest, DeletedState.Deleted);
                        }

                        if (tmpFile != null)
                        {
                            fileid = tmpFile.ItemId.ToString();
                        }
                    }

                    if (fileid.ToInt() > 0)
                    {
                        if (getPreviousRevision)
                        {
                            if (changesetid.ToInt() > 1)
                            {
                                file = versionControl.GetItem(fileid.ToInt(), changesetid.ToInt() - 1, true);
                            }
                        }
                        else
                        {
                            file = versionControl.GetItem(fileid.ToInt(), changesetid.ToInt());
                        }

                        if (file != null)
                        {
                            if (file.DeletionId > 0)
                            {
                                return(string.Empty);
                            }
                            else
                            {
                                using (Stream stream = file.DownloadFile())
                                {
                                    StreamReader rdr = new StreamReader(stream);

                                    return(rdr.ReadToEnd());
                                }
                            }
                        }
                    }
                }
                catch (VersionControlException ex)
                {
                    GeminiApp.LogException(ex, false);

                    return(string.Empty);
                }
                catch (Exception ex)
                {
                    GeminiApp.LogException(ex, false);

                    return(string.Empty);
                }
            }

            return(string.Empty);
        }
コード例 #25
0
        static int Main(string[] args)
        {
            _initializer.Configure(ConfigurableTypes);

            var result = 0;

            try
            {
                Logger.LogInfo($"Connecting to TFS server: {_tfsConfiguration.TeamFoundationServerUrl}");
                var tfsServer = new TfsConfigurationServer(_tfsConfiguration.TeamFoundationServerUri);

                Logger.LogInfo("Ensuring is authenticated...");
                tfsServer.EnsureAuthenticated();

                Logger.LogInfo("Discovering TFS Project Collections");
                var tfsTeamCollections = _tfsCollectionsGetter.UseTfsConfigurationServer(tfsServer)
                                         .TeamFoundationServerCollections;

                var i = 0;
                foreach (var teamCollection in tfsTeamCollections)
                {
                    i++;
                    Logger.LogDebug($"{i}. Project Collection discovered: {teamCollection.Key}");
                }

                i = int.Parse(Console.ReadLine());
                i--;

                TfsTeamProjectCollection tfsCollection = null;
                if (useExplicitCollectionId)
                {
                    tfsCollection = tfsServer.GetTeamProjectCollection(_tfsConfiguration.CollectionId);
                }
                else
                {
                    var collectionId = tfsTeamCollections[i].Value;
                    Logger.LogInfo($"Selected TFS Team Collection: {tfsTeamCollections[i].Key}");

                    tfsCollection = tfsServer.GetTeamProjectCollection(collectionId);
                }

                Logger.LogInfo($"Initializing TFS Identities provider");
                _tfsIdentitiesProvider.Initialize(tfsCollection);

                Logger.LogInfo($"Initializing TFS Identities Management provider");
                _tfsIdentityManagementServiceProvider.Initialize(tfsCollection);

                Logger.LogInfo($"Discovering TFS identities");
                var tfsIdentities = _tfsIdentitiesProvider.GetTfsIdentities();

                Logger.LogInfo($"Discovered TFS Identities: {tfsIdentities.Count}");

                _profilePhotoChecker.Initialize(_tfsProperties);

                foreach (TeamFoundationIdentity tfsIdentity in tfsIdentities)
                {
                    Logger.LogDebug("\r\n");
                    Logger.LogDebug($"{"".PadLeft(30, '-')}STARTING{ "".PadLeft(30, '-')}");

                    var identityKey = tfsIdentity.UniqueName;
                    Logger.LogInfo($"Processing TFS Identity: {identityKey}");
                    Logger.LogInfo($"Reading Extended Properties for Identity: {identityKey}");
                    var tfsIdentityExtended = _tfsIdentityManagementServiceProvider.ReadExtendedProperties(tfsIdentity);

                    Logger.LogInfo($"Initializing TFS Profile Photo Validator");

                    _profilePhotoChecker.Initialize(tfsIdentityExtended);
                    if (_profilePhotoChecker.HasProfilePhoto())
                    {
                        IdentityFinnishLog(identityKey);
                        continue;
                    }

                    Logger.LogInfo($"Initializing Photo provider");
                    _photoProvider.Initialize(_photoProviderSettings);

                    Logger.LogInfo($"Getting Photo data for identity: {identityKey}");
                    var photoBytes = _photoProvider.GetPhotoBytes(identityKey);

                    if (photoBytes != null && photoBytes.Length > 0)
                    {
                        var contentType = _photoProvider.GetContentType(photoBytes);
                        Logger.LogInfo($"Discovereng ContentType of photo: {contentType}");

                        Logger.LogInfo($"Creating Personalized Extended Properties");
                        var extendedProperties = _tfsProperties.CreateExtendedProperties(photoBytes, contentType, Guid.NewGuid().ToByteArray());

                        foreach (var extendedProperty in extendedProperties)
                        {
                            Logger.LogInfo($"Configurring extended property: {extendedProperty.Key}");
                            tfsIdentity.SetProperty(extendedProperty.Key, extendedProperty.Value);
                        }

                        _tfsIdentityManagementServiceProvider.UpdateExtendedProperties(tfsIdentity);
                        Logger.LogDebug($"Photo uploaded successfully for: {identityKey}");
                    }
                    else
                    {
                        Logger.LogWarning($"Photo data for identity was not discovered: {identityKey}");
                    }

                    IdentityFinnishLog(identityKey);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                result = -1;
            }

            return(result);
        }
コード例 #26
0
ファイル: TfsGateway.cs プロジェクト: StevenThuriot/Fusion
        public bool CanConnect(Uri tfsUri, NetworkCredential credentials)
        {
            Guard.NotNull(tfsUri, credentials);

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

            return canConnect;
        }
コード例 #27
0
ファイル: TfsGateway.cs プロジェクト: StevenThuriot/Fusion
        public Boolean Connect()
        {
            //Connect or reconnect if needed.
            if (!IsConnected || _Server == null || _Server.Uri != _Configuration.TFSUri)
            {
                Disconnect(); //Disconnect first if needed.

                _Server = _Configuration.UseLocalAccount || _Configuration.NetworkCredential == null
                          	? new TfsConfigurationServer(_Configuration.TFSUri)
                          	: new TfsConfigurationServer(_Configuration.TFSUri, _Configuration.NetworkCredential);

                _Server.EnsureAuthenticated();
                IsConnected = true;
            }

            return IsConnected;
        }