internal HDInsightJobSubmissionPocoClient(BasicAuthCredential credentials, IAbstractionContext context, bool ignoreSslErrors, string userAgentString) { this.remoteCreds = credentials; this.context = context; this.ignoreSslErrors = ignoreSslErrors; this.userAgentString = userAgentString ?? string.Empty; }
/// <summary> /// Initializes a new instance of the HadoopRemoteJobSubmissionRestClient class. /// </summary> /// <param name="credentials"> /// The credentials to use to connect to the server. /// </param> /// <param name="context"> /// A CancellationToken that can be used to cancel events. /// </param> /// <param name="ignoreSslErrors"> /// Specifies that server side SSL error should be ignored. /// </param> /// <param name="userAgentString">UserAgent string to pass to all calls.</param> public HadoopRemoteJobSubmissionRestClient(BasicAuthCredential credentials, IAbstractionContext context, bool ignoreSslErrors, string userAgentString) { this.credentials = credentials; this.context = context; this.ignoreSslErrors = ignoreSslErrors; this.userAgentString = userAgentString ?? string.Empty; }
private TfsTeamProjectCollection TfsConnect() { try { // Determine if local TFS or VSTS if ((!AccountURL.ToLower().Contains("https")) || AccountURL.ToLower().Contains("8080")) { // Authenticate to on-premises TFS TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(AccountURL)); tpc.EnsureAuthenticated(); return(tpc); } else { // Authenticate to VSTS NetworkCredential netCred = new NetworkCredential(MicrosoftAccountAlias, MicrosoftAccountPassword); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(AccountURL), tfsCred); tpc.Authenticate(); return(tpc); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); throw; } }
public static IJobSubmissionClientCredential GetJobSubmissionClientCredentials(this IAzureHDInsightJobCommandCredentialsBase command, WindowsAzureSubscription currentSubscription, string cluster) { IJobSubmissionClientCredential clientCredential = null; if (command.Credential != null) { clientCredential = new BasicAuthCredential { Server = GatewayUriResolver.GetGatewayUri(cluster), UserName = command.Credential.UserName, Password = command.Credential.GetCleartextPassword() }; } else if (currentSubscription.IsNotNull()) { var subscriptionCredentials = GetSubscriptionCredentials(command, currentSubscription); var asCertificateCredentials = subscriptionCredentials as HDInsightCertificateCredential; var asTokenCredentials = subscriptionCredentials as HDInsightAccessTokenCredential; if (asCertificateCredentials.IsNotNull()) { clientCredential = new JobSubmissionCertificateCredential(asCertificateCredentials, cluster); } else if (asTokenCredentials.IsNotNull()) { clientCredential = new JobSubmissionAccessTokenCredential(asTokenCredentials, cluster); } } return clientCredential; }
public static IJobSubmissionClientCredential GetJobSubmissionClientCredentials(this IAzureHDInsightJobCommandCredentialsBase command, WindowsAzureSubscription currentSubscription, string cluster) { IJobSubmissionClientCredential clientCredential = null; if (command.Credential != null) { clientCredential = new BasicAuthCredential { Server = GatewayUriResolver.GetGatewayUri(cluster), UserName = command.Credential.UserName, Password = command.Credential.GetCleartextPassword() }; } else if (currentSubscription.IsNotNull()) { var subscriptionCredentials = GetSubscriptionCredentials(command, currentSubscription); var asCertificateCredentials = subscriptionCredentials as HDInsightCertificateCredential; var asTokenCredentials = subscriptionCredentials as HDInsightAccessTokenCredential; if (asCertificateCredentials.IsNotNull()) { clientCredential = new JobSubmissionCertificateCredential(asCertificateCredentials, cluster); } else if (asTokenCredentials.IsNotNull()) { clientCredential = new JobSubmissionAccessTokenCredential(asTokenCredentials, cluster); } } return(clientCredential); }
public void ICanSubmitASqoopJob() { var factory = new MockRemotePocoLayerFactory(); var pocoMock = new MockRemotePoco(); pocoMock.JobId = "54321"; factory.Mock = pocoMock; ServiceLocator.Instance.Locate <IServiceLocationIndividualTestManager>().Override <IRemoteHadoopJobSubmissionPocoClientFactory>(factory); // var creds = new JobSubmissionCertificateCredential(Guid.NewGuid(), null, "someCluster"); var creds = new BasicAuthCredential() { Password = "******", Server = new Uri("http://somewhere"), UserName = "******" }; var poco = new HDInsightJobSubmissionPocoClient(creds, GetAbstractionContext(), false, pocoMock.GetUserAgentString()); var task = poco.SubmitSqoopJob(new SqoopJobCreateParameters() { Command = "load remote;" }); task.Wait(); Assert.AreEqual("54321", task.Result.JobId); Assert.IsTrue(pocoMock.SubmitSqoopJobCalled); }
public AzureHDInsightClusterConfigurationAccessorSimulator(IJobSubmissionClientCredential credentials) { var remoteCreds = credentials as BasicAuthCredential; Assert.IsNotNull(remoteCreds); this.credentials = remoteCreds; }
public void ICanGetAJob() { var expectedJob = new JobDetails() { ExitCode = 12, Name = "some jobDetails", StatusCode = Hadoop.Client.JobStatusCode.Completed, JobId = "2345" }; var factory = new MockRemotePocoLayerFactory(); var pocoMock = new MockRemotePoco { JobId = string.Empty, JobDetails = expectedJob }; factory.Mock = pocoMock; ServiceLocator.Instance.Locate <IServiceLocationIndividualTestManager>().Override <IRemoteHadoopJobSubmissionPocoClientFactory>(factory); var creds = new BasicAuthCredential() { Password = "******", Server = new Uri("http://somewhere"), UserName = "******" }; var poco = new HDInsightJobSubmissionPocoClient(creds, GetAbstractionContext(), false, pocoMock.GetUserAgentString()); var task = poco.GetJob("2345"); task.Wait(); Assert.AreEqual("2345", task.Result.JobId); Assert.IsTrue(pocoMock.GetJobCalled); Assert.AreEqual(expectedJob, task.Result); }
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); }
// see http://msdn.microsoft.com/en-us/library/bb130306.aspx public void Connect() { if (this.Credential != null && !string.IsNullOrWhiteSpace(this.Credential.UserName)) { if (IsVSO(this.CollectionUrl)) { // source http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx BasicAuthCredential basicCred = new BasicAuthCredential(this.Credential); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; this.Collection = new TfsTeamProjectCollection(this.CollectionUrl, tfsCred); } else { this.Collection = new TfsTeamProjectCollection(this.CollectionUrl, this.Credential); }//if } else { if (IsVSO(this.CollectionUrl)) { throw new SecurityException("VSO requires user and password"); } else { this.Collection = new TfsTeamProjectCollection(this.CollectionUrl); } } this.Collection.EnsureAuthenticated(); }
/// <summary> /// Get the parameters of the test case /// </summary> /// <param name="testCaseId">Test case id (work item id#) displayed into TFS</param> /// <returns>Returns the test case parameters in datatable format. If there are no parameters then it will return null</returns> public static DataTable GetTestCaseParameters(int testCaseId) { ITestManagementService TestMgrService; ITestCase TestCase = null; DataTable TestCaseParameters = null; NetworkCredential netCred = new NetworkCredential( Constants.TFS_USER_NAME, Constants.TFS_USER_PASSWORD); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection( new Uri(Constants.TFS_URL), tfsCred); teamProjectCollection.Authenticate(); TestMgrService = teamProjectCollection.GetService<ITestManagementService>(); TestCase = TestMgrService.GetTeamProject(Constants.TFS_PROJECT_NAME).TestCases.Find(testCaseId); if (TestCase != null) { if (TestCase.Data.Tables.Count > 0) { TestCaseParameters = TestCase.Data.Tables[0]; } } return TestCaseParameters; }
static void Main(string[] args) { var credentials = new BasicAuthCredential { UserName = "******", Password = "******", Server = new Uri("https://simonellistonball.azurehdinsight.net") }; var submissionClient = JobSubmissionClientFactory.Connect(credentials); submissionClient.JobStatusEvent += (o, e) => Console.WriteLine(e.JobDetails.StatusCode); var pigJobParams = new PigJobCreateParameters { StatusFolder = "wasbs://[email protected]/status", File = "wasbs://[email protected]/lovecleanstreets.pig" }; var job = submissionClient.CreatePigJob(pigJobParams); bool complete = false; while (!complete) { var jobDetails = submissionClient.GetJob(job.JobId); Console.WriteLine(jobDetails.StatusCode); Console.WriteLine(jobDetails.ExitCode); if (jobDetails.StatusCode == JobStatusCode.Completed) { complete = true; } Thread.Sleep(2000); } Console.ReadLine(); }
internal static void ValidateClusterConfiguration(ClusterDetails testCluster, ClusterCreateParametersV2 cluster) { var remoteCreds = new BasicAuthCredential() { Server = GatewayUriResolver.GetGatewayUri(new Uri(testCluster.ConnectionUrl).Host), UserName = testCluster.HttpUserName, Password = testCluster.HttpPassword }; var configurationAccessor = ServiceLocator.Instance.Locate <IAzureHDInsightClusterConfigurationAccessorFactory>().Create(remoteCreds); var coreConfiguration = configurationAccessor.GetCoreServiceConfiguration().WaitForResult(); ValidateConfiguration(cluster.CoreConfiguration, coreConfiguration); var hdfsConfiguration = configurationAccessor.GetHdfsServiceConfiguration().WaitForResult(); ValidateConfiguration(cluster.HdfsConfiguration, hdfsConfiguration); var mapReduceConfiguration = configurationAccessor.GetMapReduceServiceConfiguration().WaitForResult(); ValidateConfiguration(cluster.MapReduceConfiguration.ConfigurationCollection, mapReduceConfiguration); var hiveConfiguration = configurationAccessor.GetHiveServiceConfiguration().WaitForResult(); ValidateConfiguration(cluster.HiveConfiguration.ConfigurationCollection, hiveConfiguration); var oozieConfiguration = configurationAccessor.GetOozieServiceConfiguration().WaitForResult(); ValidateConfiguration(cluster.OozieConfiguration.ConfigurationCollection, oozieConfiguration); }
public static ITestManagementTeamProject GetProject(Uri tfsUri, string projectName, string username, string password) { try { Trace.TraceInformation($"Connecting to VSTS {tfsUri.AbsoluteUri}, Project: {projectName}"); var networkCredential = new NetworkCredential(username, password); BasicAuthCredential basicCred = new BasicAuthCredential(networkCredential); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; TfsTeamProjectCollection projectsCollection = new TfsTeamProjectCollection(tfsUri, tfsCred); ITestManagementService service = (ITestManagementService)projectsCollection.GetService(typeof(ITestManagementService)); ITestManagementTeamProject project = service.GetTeamProject(projectName); Trace.TraceInformation($"project {projectName} found"); return(project); } catch (TestObjectNotFoundException) { Trace.TraceError($"Project {projectName} not found"); return(null); } catch (Exception ex) { Trace.TraceError(ex.Message); return(null); } }
public ConnectionResult Connect(string host, string user, string password) { string.Format("Connecting to TFS '{0}'", host).Debug(); try { _projectCollectionUri = new Uri(host); } catch (UriFormatException ex) { string.Format("Invalid project URL '{0}': {1}", host, ex.Message).Error(); return ConnectionResult.InvalidUrl; } //This is used to query TFS for new WorkItems try { if (_projectCollectionNetworkCredentials == null) { _projectCollectionNetworkCredentials = new NetworkCredential(user, password); // if this is hosted TFS then we need to authenticate a little different // see this for setup to do on visualstudio.com site: // http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx if (_projectCollectionUri.Host.ToLowerInvariant().Contains(".visualstudio.com")) { if (_basicAuthCredential == null) _basicAuthCredential = new BasicAuthCredential(_projectCollectionNetworkCredentials); if (_tfsClientCredentials == null) { _tfsClientCredentials = new TfsClientCredentials(_basicAuthCredential); _tfsClientCredentials.AllowInteractive = false; } } if (_projectCollection == null) { _projectCollection = _tfsClientCredentials != null ? new TfsTeamProjectCollection(_projectCollectionUri, _tfsClientCredentials) : new TfsTeamProjectCollection(_projectCollectionUri, _projectCollectionNetworkCredentials); } _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection); } if (_projectCollectionWorkItemStore == null) _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection); } catch (Exception e) { string.Format("Failed to connect: {0}", e.Message).Error(e); return ConnectionResult.FailedToConnect; } return ConnectionResult.Success; }
public ConnectionResult Connect(string host, string user, string password) { string.Format("Connecting to TFS '{0}'", host).Debug(); try { _projectCollectionUri = new Uri(host); } catch (UriFormatException ex) { string.Format("Invalid project URL '{0}': {1}", host, ex.Message).Error(); return(ConnectionResult.InvalidUrl); } //This is used to query TFS for new WorkItems try { if (_projectCollectionNetworkCredentials == null) { _projectCollectionNetworkCredentials = new NetworkCredential(user, password); // if this is hosted TFS then we need to authenticate a little different // see this for setup to do on visualstudio.com site: // http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx if (_projectCollectionUri.Host.ToLowerInvariant().Contains(".visualstudio.com")) { if (_basicAuthCredential == null) { _basicAuthCredential = new BasicAuthCredential(_projectCollectionNetworkCredentials); } if (_tfsClientCredentials == null) { _tfsClientCredentials = new TfsClientCredentials(_basicAuthCredential); _tfsClientCredentials.AllowInteractive = false; } } if (_projectCollection == null) { _projectCollection = _tfsClientCredentials != null ? new TfsTeamProjectCollection(_projectCollectionUri, _tfsClientCredentials) : new TfsTeamProjectCollection(_projectCollectionUri, _projectCollectionNetworkCredentials); } _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection); } if (_projectCollectionWorkItemStore == null) { _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection); } } catch (Exception e) { string.Format("Failed to connect: {0}", e.Message).Error(e); return(ConnectionResult.FailedToConnect); } return(ConnectionResult.Success); }
public void Connect() { NetworkCredential netCred = new NetworkCredential(m_username, m_password); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); m_tpc = new TfsTeamProjectCollection(new Uri(m_url), tfsCred); }
public TFS(Uri server, NetworkCredential credential) { BasicAuthCredential basicCred = new BasicAuthCredential(credential); var tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; _connection.ClientCredentials = tfsCred; Initialize(server, tfsCred); }
public HadoopJobSubmissionPocoSimulatorClient(BasicAuthCredential connectionCredentials, IAbstractionContext context, string userAgentString) { this.credentials = connectionCredentials; var server = connectionCredentials.Server.Host.Split('.')[0]; this.cluster = HDInsightManagementRestSimulatorClient.GetCloudServiceInternal(server); this.context = context; this.userAgentString = userAgentString; this.InitializeSimulator(); }
public void Initialize(BuildConfig config) { NetworkCredential credentials = new NetworkCredential(config.Username, config.Password); BasicAuthCredential basicCredentials = new BasicAuthCredential(credentials); TfsClientCredentials cred = new TfsClientCredentials(basicCredentials); cred.AllowInteractive = false; tpc = new TfsTeamProjectCollection(new Uri(config.SourceUrl + "/" + config.Collection),cred); tpc.Authenticate(); this.Server = tpc.GetService<Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer>(); }
internal BasicAuthCredential GetRemoteHadoopCredential() { var azureTestCredentials = GetCredentials("hadoop"); var credentials = new BasicAuthCredential() { Server = new Uri(azureTestCredentials.WellKnownCluster.Cluster), UserName = azureTestCredentials.AzureUserName, Password = azureTestCredentials.AzurePassword }; return(credentials); }
internal JobSubmissionClusterDetails GetJobSubmissionClusterDetails(bool ignoreCache = false) { var asCertCredentials = this.subscriptionCredentials as JobSubmissionCertificateCredential; var asTokenCredentials = this.subscriptionCredentials as JobSubmissionAccessTokenCredential; string clusterName; if (asCertCredentials.IsNotNull()) { clusterName = asCertCredentials.Cluster; } else if (asTokenCredentials.IsNotNull()) { clusterName = asTokenCredentials.Cluster; } else { throw new NotSupportedException("Credential type '" + this.subscriptionCredentials.GetType().FullName + "' is not supported."); } var credentialCache = ServiceLocator.Instance.Locate <IJobSubmissionCache>(); var retval = credentialCache.GetCredentails(this.subscriptionCredentials.SubscriptionId, clusterName); if (retval.IsNull() || ignoreCache) { var overrideHandlers = ServiceLocator.Instance.Locate <IHDInsightClusterOverrideManager>().GetHandlers(this.subscriptionCredentials, this.Context, this.IgnoreSslErrors); ServiceLocator.Instance.Locate <IHDInsightClientFactory>().Create(this.subscriptionCredentials); IHDInsightSubscriptionCredentials actualCredentials = ServiceLocator.Instance.Locate <IHDInsightSubscriptionCredentialsFactory>() .Create(this.subscriptionCredentials); var hdinsight = ServiceLocator.Instance.Locate <IHDInsightClientFactory>().Create(actualCredentials); hdinsight.IgnoreSslErrors = this.IgnoreSslErrors; var cluster = hdinsight.GetCluster(clusterName); var versionFinderClient = overrideHandlers.VersionFinder; this.AssertSupportedVersion(cluster.VersionNumber, versionFinderClient); var remoteCredentials = new BasicAuthCredential() { Server = GatewayUriResolver.GetGatewayUri(cluster.ConnectionUrl, cluster.VersionNumber), UserName = cluster.HttpUserName, Password = cluster.HttpPassword }; retval = new JobSubmissionClusterDetails() { Cluster = cluster, RemoteCredentials = remoteCredentials }; credentialCache.StoreCredentails(this.subscriptionCredentials.SubscriptionId, clusterName, retval); } return(retval); }
/// <summary> /// Prevents a default instance of the <see cref="TfsProjects"/> class from being created. /// This might change if the project name can be optional. /// </summary> public TfsProjects(string tfsUri, string username, string password, string projectName = null) { NetworkCredential netCred = new NetworkCredential(username, password); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; ProjectCollection = new TfsTeamProjectCollection(new Uri(tfsUri), tfsCred); ProjectCollection.Authenticate(); Store = new WorkItemStore(ProjectCollection); ProjectName = projectName; }
/// <summary> /// Initializes a new instance of the <see cref="TfsProjects"/> class. /// </summary> /// <param name="context">The context.</param> /// <param name="projectName">Name of the project.</param> public TfsProjects(ITfsContext context) { NetworkCredential netCred = new NetworkCredential(context.Username, context.Password); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; ProjectCollection = new TfsTeamProjectCollection(new Uri(context.Uri), tfsCred); ProjectCollection.Authenticate(); Store = new WorkItemStore(ProjectCollection); ProjectName = context.ProjectName; }
public static TfsTeamProjectCollection GetTeamProjectCollection(Uri collectionUri, out NetworkCredential credential) { string user = ConfigurationManager.AppSettings["TfsClientUser"]; string password = ConfigurationManager.AppSettings["TfsClientPassword"]; credential = new NetworkCredential(user, password); BasicAuthCredential basicCred = new BasicAuthCredential(credential); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(collectionUri, tfsCred); teamProjectCollection.Authenticate(); return(teamProjectCollection); }
protected override void OnCreateMockObjects() { base.OnCreateMockObjects(); MockCredentials = new Mock <ICredentials>(); Credentials = MockCredentials.Object; BasicAuthCredential = new BasicAuthCredential(Credentials); TfsClientCredentials = new TfsClientCredentials(BasicAuthCredential); TfsClientCredentials.AllowInteractive = false; MockProjectCollection = new Mock <TfsTeamProjectCollection>(new Uri("http://localhost"), Credentials); ProjectCollection = MockProjectCollection.Object; ProjectHyperlinkService = null; WorkItemStore = null; TFSUsers = new List <Microsoft.TeamFoundation.Server.Identity>(); }
public TfsTeamProjectCollection Authorize(IDictionary<string, string> authorizeInformation) { NetworkCredential netCred = new NetworkCredential( "*****@*****.**", "yourbasicauthpassword"); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; TfsTeamProjectCollection tpc = new TfsTeamProjectCollection( new Uri("https://YourAccountName.visualstudio.com/DefaultCollection"), tfsCred); tpc.Authenticate(); return tpc; }
protected override void OnCreateMockObjects() { base.OnCreateMockObjects(); MockCredentials = new Mock<ICredentials>(); Credentials = MockCredentials.Object; BasicAuthCredential = new BasicAuthCredential(Credentials); TfsClientCredentials = new TfsClientCredentials(BasicAuthCredential); TfsClientCredentials.AllowInteractive = false; MockProjectCollection = new Mock<TfsTeamProjectCollection>(new Uri("http://localhost"), Credentials); ProjectCollection = MockProjectCollection.Object; ProjectHyperlinkService = null; WorkItemStore = null; TFSUsers = new List<Microsoft.TeamFoundation.Server.Identity>(); }
private IEnumerable <TfsClientCredentials> GetServiceIdentityPatCredentials() { if (string.IsNullOrWhiteSpace(_config.TfsServerConfig.ServiceIdentityPatFile) && _config.TfsServerConfig.ServiceIdentityPatKeyVaultSecret == null) { return(new List <TfsClientCredentials>()); } var netCred = new NetworkCredential("", GetPatFromConfig()); var basicCred = new BasicAuthCredential(netCred); var patCred = new TfsClientCredentials(basicCred) { AllowInteractive = false }; return(new List <TfsClientCredentials> { patCred }); }
static void Main(string[] args) { NetworkCredential netCred = new NetworkCredential( "*****@*****.**", "yourbasicauthpassword"); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; TfsTeamProjectCollection tpc = new TfsTeamProjectCollection( new Uri("https://YourAccountName.visualstudio.com/DefaultCollection"), tfsCred); tpc.Authenticate(); Console.WriteLine(tpc.InstanceId); }
private void ConnectDestinationProjectButton_Click(object sender, RoutedEventArgs e) { TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false); DialogResult result = tpp.ShowDialog(); if (result.ToString() == "OK") { StatusViwer.Content = ""; MigratingLabel.Content = ""; StatusBar.Value = 0; SourceFieldGrid.ItemsSource = new List <string>(); TargetFieldGrid.ItemsSource = new List <string>(); MappedListGrid.ItemsSource = new List <object>(); FieldToCopyGrid.ItemsSource = new List <object>(); WorkFlowListGrid.ItemsSource = new List <object>(); finalFieldMap = new Hashtable(); copyingFieldSet = new Hashtable(); migrateTypeSet = new List <object>(); NetworkCredential netCred = new NetworkCredential("*****@*****.**", "px3iifegtadud3p33ma55vvf2ign7y7j6tdb4hvs43jefuwym6oa"); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri("https://apra-amcos.visualstudio.com"), tfsCred); tpc.Authenticate(); this.destinationTFS = tpc; this.destinationStore = (WorkItemStore)destinationTFS.GetService(typeof(WorkItemStore)); this.destinationProject = destinationStore.Projects["TestMigration"]; DestinationProjectText.Text = string.Format("{0}/{1}", destinationTFS.Uri.ToString(), destinationProject.Name); writeTarget = new WorkItemWrite(destinationTFS, destinationProject); if ((string)ConnectionStatusLabel.Content == "Select a Target project") { ConnectionStatusLabel.Content = ""; } } }
private void Authenticate(string user, string pass) { if (string.IsNullOrEmpty(user) && string.IsNullOrEmpty(pass)) { _credential = new TfsClientCredentials() { AllowInteractive = true }; } else { var netCred = new NetworkCredential(user, pass); var basicCred = new BasicAuthCredential(netCred); _credential = new TfsClientCredentials(basicCred) { AllowInteractive = true }; } }
protected TfsTeamProjectCollection GetClient() { var collectionUri = new Uri(GetSetting(TfsSettings.HostName)); var credential = new NetworkCredential(GetSetting(TfsSettings.UserName), GetSetting(TfsSettings.UserPassword)); var basicCred = new BasicAuthCredential(credential); var tfsCred = new TfsClientCredentials(basicCred) { AllowInteractive = false }; var teamProjectCollection = new TfsTeamProjectCollection(collectionUri, tfsCred); teamProjectCollection.EnsureAuthenticated(); return(teamProjectCollection); }
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); }
private IEnumerable <TfsClientCredentials> GetBasicAuthCredentials() { var usernameAndPassword = GetAltAuthUsernameAndPasswordFromConfig(); if (usernameAndPassword == null) { return(new List <TfsClientCredentials>()); } NetworkCredential netCred = new NetworkCredential(usernameAndPassword.Item1, usernameAndPassword.Item2); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; return(new List <TfsClientCredentials> { tfsCred }); }
public Tfs(IBoardSubscriptionManager subscriptions, IConfigurationProvider <Configuration> configurationProvider, ILocalStorage <AppSettings> localStorage, ILeanKitClientFactory leanKitClientFactory, ICredentials projectCollectionNetworkCredentials, BasicAuthCredential basicAuthCredential, TfsClientCredentials tfsClientCredentials, TfsTeamProjectCollection projectCollection, TswaClientHyperlinkService projectHyperlinkService, WorkItemStore projectCollectionWorkItemStore, List <Microsoft.TeamFoundation.Server.Identity> tfsUsers) : base(subscriptions, configurationProvider, localStorage, leanKitClientFactory) { _projectCollectionNetworkCredentials = projectCollectionNetworkCredentials; _projectCollection = projectCollection; _projectHyperlinkService = projectHyperlinkService; _projectCollectionWorkItemStore = projectCollectionWorkItemStore; _basicAuthCredential = basicAuthCredential; _tfsClientCredentials = tfsClientCredentials; _tfsUsers = tfsUsers; }
public Tfs(IBoardSubscriptionManager subscriptions, IConfigurationProvider<Configuration> configurationProvider, ILocalStorage<AppSettings> localStorage, ILeanKitClientFactory leanKitClientFactory, ICredentials projectCollectionNetworkCredentials, BasicAuthCredential basicAuthCredential, TfsClientCredentials tfsClientCredentials, TfsTeamProjectCollection projectCollection, TswaClientHyperlinkService projectHyperlinkService, WorkItemStore projectCollectionWorkItemStore, List<Microsoft.TeamFoundation.Server.Identity> tfsUsers) : base(subscriptions, configurationProvider, localStorage, leanKitClientFactory) { _projectCollectionNetworkCredentials = projectCollectionNetworkCredentials; _projectCollection = projectCollection; _projectHyperlinkService = projectHyperlinkService; _projectCollectionWorkItemStore = projectCollectionWorkItemStore; _basicAuthCredential = basicAuthCredential; _tfsClientCredentials = tfsClientCredentials; _tfsUsers = tfsUsers; }
private static BasicAuthCredential GetClusterHttpCredentials(ClusterDetails cluster) { if (string.IsNullOrEmpty(cluster.ConnectionUrl)) { throw new InvalidOperationException("Unable to connect to cluster as connection url is missing or empty."); } if (string.IsNullOrEmpty(cluster.HttpUserName) || string.IsNullOrEmpty(cluster.HttpPassword)) { throw new InvalidOperationException("Unable to connect to cluster as cluster username and/or password are missing or empty."); } BasicAuthCredential clusterCreds = new BasicAuthCredential() { Server = new Uri(cluster.ConnectionUrl), UserName = cluster.HttpUserName, Password = cluster.HttpPassword }; return(clusterCreds); }
protected override TfsTeamProjectCollection GetTfsCredential(Uri uri) { var basicAuthCredential = new BasicAuthCredential(GetCredential()); return new TfsTeamProjectCollection(uri, new TfsClientCredentials(basicAuthCredential) { AllowInteractive = !HasCredentials }); }
static void Main(string[] args) { BasicAuthCredential bAuth = new BasicAuthCredential(new NetworkCredential("nikunj", "decos@123")); var tfs = new TfsTeamProjectCollection(new Uri(URL_TO_TFS_COLLECTION), new TfsClientCredentials(bAuth)); tfs.Authenticate(); var store = tfs.GetService<WorkItemStore>(); var versionStore = tfs.GetService<Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer>(); StringBuilder swFileData = new StringBuilder(); //Handler, WorkItemId, ReviewRequestId, Comment, Author, CommentDate {NewLine} swFileData.Append(string.Format("{0}, {1}, {2}, {3}, {4}, {5}{6}", "Handler", "WorkItemId", "ReviewRequestId", "Comment", "Author", "CommentDate", Environment.NewLine)); StringBuilder swReviewResponseData = new StringBuilder(); //"Handler", "WorkItemId", "ReviewRequestId", "ReviewResponseId", "ClosedBy", "ClosedStatus", "ClosedDate" swReviewResponseData.Append(string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}{7}", "Handler", "WorkItemId", "ReviewRequestId", "ReviewResponseId", "ClosedBy", "ClosedStatus", "ClosedDate", Environment.NewLine)); StringBuilder swReviewRequestData = new StringBuilder(); //ID, Work Item Type, Title, Assigned To, State, Effort, Tags, Area Path, Changed Date, Closed Date, Created Date, Iteration Path, Remaining Work, ReviewRequestCount string sReviewRequestLine = "ID, Work Item Type, Title, Assigned To, State, Effort, Tags, Area Path, Changed Date, Closed Date, Created Date, Iteration Path, Remaining Work, ReviewRequestCount"; string sReviewRequestHeaderFormat = string.Empty; int iColumnIndex = 0; foreach (var column in sReviewRequestLine.Split(',')) { if (iColumnIndex > 0) sReviewRequestHeaderFormat += ", "; sReviewRequestHeaderFormat += "{" + iColumnIndex + "}"; iColumnIndex++; } sReviewRequestHeaderFormat += "{" + iColumnIndex + "}"; swReviewRequestData.Append(string.Format(sReviewRequestHeaderFormat, "ID" , "Work Item Type", "Title" , "Assigned To", "State", "Effort", "Tags", "Area Path", "Changed Date", "Closed Date", "Created Date" , "Iteration Path", "Remaining Work", "ReviewRequestCount", Environment.NewLine)); var queryText = "SELECT [System.Id] FROM WorkItems WHERE [System.WorkItemType] In ('Product Backlog Item','Bug') And [System.CreatedDate] >= '4/1/2015'" + "And [System.State] <> 'Removed' Order By [System.Id], [System.ChangedDate]"; var query = new Query(store, queryText); var result = query.RunQuery().OfType<WorkItem>().ToList(); //To get all sub task for Issue & Internal Support - PBI Parallel.ForEach(result, (workitem) => { AddTaskToResult(workitem, store, result); }); //Parallel.ForEach(result, (workitem) => foreach (var workitem in result) { List<WorkItem> wicReviewRequests = GetReviewRequests(store, workitem); string sWorkItemNewLine = GetWorkItemLine(sReviewRequestHeaderFormat, workitem, wicReviewRequests); swReviewRequestData.Append(sWorkItemNewLine); //Console.WriteLine(sRequestNewLine); if (wicReviewRequests != null) { foreach (var reviewrequest in wicReviewRequests) { try { #region code review comments //1. Get code review comments from review request List<CodeReviewComment> comments = GetCodeReviewComments(reviewrequest.Id); if (comments != null && comments.Count > 0) { //Create new line for each comments (CSV) foreach (var comment in comments) { try { //Handler, WorkItemId, ReviewRequestId, Comment, Author, CommentDate {NewLine} string sNewLine = string.Format("{0}, {1}, {2}, {3}, {4}, {5}{6}", reviewrequest.CreatedBy, workitem.Id, reviewrequest.Id, comment.Comment, comment.Author, comment.PublishDate, Environment.NewLine); swFileData.Append(sNewLine); //Console.WriteLine(sNewLine); } catch (Exception ex) { Console.WriteLine("Error-Comment:" + ex); } } } #endregion #region code review responses //2. Get code review responses for this code review request List<WorkItem> wicReviewResponses = GetReviewResponses(store, reviewrequest); if (wicReviewResponses != null && wicReviewResponses.Count > 0) { //Create new line for each code review response (CSV) foreach (WorkItem reviewresponse in wicReviewResponses) { if (reviewresponse.Type.Name == "Code Review Response") { try { //"Handler", "WorkItemId", "ReviewRequestId", "ReviewResponseId", "ClosedBy", "ClosedStatus", "ClosedDate" string sClosedBy = (reviewresponse.Fields["Closed By"]).Value.ToString(); string sClosedStatus = (reviewresponse.Fields["Closed Status"]).Value.ToString(); object oClosedDate = (reviewresponse.Fields["Closed Date"]).Value; string sClosedDate = string.Empty; if (oClosedDate != null) sClosedDate = oClosedDate.ToString(); string sNewLine = string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}{7}", reviewrequest.CreatedBy, workitem.Id, reviewrequest.Id, reviewresponse.Id, sClosedBy, sClosedStatus, sClosedDate, Environment.NewLine); swReviewResponseData.Append(sNewLine); //Console.WriteLine(sNewLine); } catch (Exception ex) { Console.WriteLine("Error-CRR:" + ex); } } } } #endregion } catch (Exception ex) { Console.WriteLine("Error-WI:" + ex); } } } //}); } File.WriteAllText(@"D:\Personal\Team meeting\2015\2015-Sep-All Half Yeraly Apprisal-Comments-Rev01.csv", swFileData.ToString()); File.WriteAllText(@"D:\Personal\Team meeting\2015\2015-Sep-All Half Yeraly Apprisal-ReviewResponse-Rev01.csv", swReviewResponseData.ToString()); File.WriteAllText(@"D:\Personal\Team meeting\2015\2015-Sep-All Half Yeraly Apprisal-ReviewRequests-Rev01.csv", swReviewRequestData.ToString()); }
private void cmdImport_Click(object sender, EventArgs e) { Uri collectionUri = new Uri(txtCollectionUri.Text); string teamProject = txtTeamProject.Text; OpenFileDialog dlg = new OpenFileDialog(); dlg.CheckFileExists = true; dlg.Title = "Import Area/Iteration structure"; dlg.DefaultExt = ".nodes"; dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes"; if (dlg.ShowDialog(this) == DialogResult.OK) { string filename = dlg.FileName; var networkCredential = new NetworkCredential("username", "password"); var basicAuthCredential = new BasicAuthCredential(networkCredential); var tfsCredential = new TfsClientCredentials(basicAuthCredential); using (var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential)) //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri, new UICredentialsProvider())) using (WaitState waitState = new WaitState(this)) { tfs.Authenticate(); tfs.EnsureAuthenticated(); WorkItemStore store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); Project proj = store.Projects[teamProject]; NodeInfo rootAreaNode = null; NodeInfo rootIterationNode = null; var css = (ICommonStructureService4)tfs.GetService(typeof(ICommonStructureService4)); foreach (NodeInfo info in css.ListStructures(proj.Uri.ToString())) { if (info.StructureType == "ProjectModelHierarchy") { rootAreaNode = info; } else if (info.StructureType == "ProjectLifecycle") { rootIterationNode = info; } } using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) using (StreamReader reader = new StreamReader(fs)) { string nextLine = reader.ReadLine(); if (nextLine != "NODES") { MessageBox.Show("Wrong file format!"); return; } reader.ReadLine(); reader.ReadLine(); while (!reader.EndOfStream) { nextLine = reader.ReadLine(); if (nextLine.StartsWith("A") && chkAreaStructure.Checked) { CreateNode(css, nextLine.Substring(2), rootAreaNode); } else if (nextLine.StartsWith("I") && chkIterationStructure.Checked) { CreateNode(css, nextLine.Substring(2), rootIterationNode); } else { // Ignore other lines } } reader.Close(); } MessageBox.Show("Import successful."); } } }
private void cmdExport_Click(object sender, EventArgs e) { Uri collectionUri = new Uri(txtCollectionUri.Text); string teamProject = txtTeamProject.Text; SaveFileDialog dlg = new SaveFileDialog(); dlg.CheckPathExists = true; dlg.Title = "Export Area/Iteration structure"; dlg.DefaultExt = ".nodes"; dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes"; if (dlg.ShowDialog(this) == DialogResult.OK) { string filename = dlg.FileName; var networkCredential = new NetworkCredential("username", "password"); var basicAuthCredential = new BasicAuthCredential(networkCredential); var tfsCredential = new TfsClientCredentials(basicAuthCredential); using(var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential)) //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri)) using (WaitState waitState = new WaitState(this)) { tfs.Authenticate(); tfs.EnsureAuthenticated(); // get the configuration server var svr = tfs.ConfigurationServer; // get the configuration service var svc = tfs.GetService<TeamSettingsConfigurationService>(); // get the common structure service var css = tfs.GetService<ICommonStructureService4>(); // get the spotlabs project var prj = css.GetProjectFromName(txtTeamProject.Text); // get the configurations var cfg = svc.GetTeamConfigurationsForUser(new[] { prj.Uri }).Single<TeamConfiguration>(); // get the settings var opt = cfg.TeamSettings; // get the iteration schedule var schedule = css.GetIterationDates(prj.Uri); Console.WriteLine(opt.ToString()); var store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); var proj = store.Projects[teamProject]; using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write)) using (StreamWriter writer = new StreamWriter(fs)) { writer.WriteLine("NODES"); writer.WriteLine(String.Format("{0}, Version {1}", Application.ProductName, Application.ProductVersion)); writer.WriteLine("Copyright (C) 2010 " + Application.CompanyName); if (chkAreaStructure.Checked) { WriteNodes(proj.AreaRootNodes, writer, "A"); } if (chkIterationStructure.Checked) { WriteNodes(proj.IterationRootNodes, writer, "I"); } writer.Close(); } } MessageBox.Show("Export successful."); } }
public override void Init() { if (Configuration == null) return; try { _projectCollectionUri = new Uri(Configuration.Target.Url); } catch (UriFormatException ex) { Log.Error("Error connection to TFS. Ensure the Target Host is a valid URL: {0} - {1}", ex.GetType(), ex.Message); return; } Log.Info("Connecting to TFS..."); //This is used to query TFS for new WorkItems try { if (_projectCollectionNetworkCredentials == null) { // if this is hosted TFS then we need to authenticate a little different // see this for setup to do on visualstudio.com site: // http://blogs.msdn.com/b/buckh/archive/2013/01/07/how-to-connect-to-tf-service-without-a-prompt-for-liveid-credentials.aspx if (_projectCollectionUri.Host.ToLowerInvariant().Contains(".visualstudio.com")) { _projectCollectionNetworkCredentials = new NetworkCredential(Configuration.Target.User, Configuration.Target.Password); if (_basicAuthCredential == null) _basicAuthCredential = new BasicAuthCredential(_projectCollectionNetworkCredentials); if (_tfsClientCredentials == null) { _tfsClientCredentials = new TfsClientCredentials(_basicAuthCredential); _tfsClientCredentials.AllowInteractive = false; } if (_projectCollection == null) { _projectCollection = new TfsTeamProjectCollection(_projectCollectionUri, _tfsClientCredentials); _projectHyperlinkService = _projectCollection.GetService<TswaClientHyperlinkService>(); _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection); } } else { // Check for common NTLM/Windows Auth convention // ("DOMAIN\Username") in User input and separate // domain from username: string domain = null; string username = null; if (Configuration.Target.User.Contains("\\")) { string[] domainUser = Configuration.Target.User.Split('\\'); domain = domainUser[0]; username = domainUser[1]; } if (domain != null) { Log.Debug("Logging in using NTLM auth (using domain: {0}, username: {1})", domain, username); _projectCollectionNetworkCredentials = new NetworkCredential(username, Configuration.Target.Password, domain); } else { _projectCollectionNetworkCredentials = new NetworkCredential(Configuration.Target.User, Configuration.Target.Password); } if (_projectCollection == null) { _projectCollection = new TfsTeamProjectCollection(_projectCollectionUri, _projectCollectionNetworkCredentials); _projectHyperlinkService = _projectCollection.GetService<TswaClientHyperlinkService>(); _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection); } } } if (_projectCollectionWorkItemStore == null) _projectCollectionWorkItemStore = new WorkItemStore(_projectCollection); if (_projectCollection != null && _tfsUsers == null) LoadTfsUsers(); } catch (Exception e) { Log.Error("Error connecting to TFS: {0} - {1}", e.GetType(), e.Message); } // per project, if exclusions are defined, build type filter to exclude them foreach (var mapping in Configuration.Mappings) { mapping.ExcludedTypeQuery = ""; if (mapping.Excludes == null) continue; var excludedTypes = mapping.Excludes.Split(','); Log.Debug("Excluded WorkItemTypes for [{0}]:", mapping.Identity.Target); foreach (var type in excludedTypes) { var trimmedType = type.Trim(); Log.Debug(">> [{0}]", trimmedType); mapping.ExcludedTypeQuery += String.Format(" AND [System.WorkItemType] <> '{0}'", trimmedType); } } }
private IBuildServer GetBuildServer() { BasicAuthCredential basicCredentials = new BasicAuthCredential(credentialsProvider); TfsClientCredentials tfsCredentials = new TfsClientCredentials(basicCredentials); tfsCredentials.AllowInteractive = false; var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsServerAddress)); tfs.ClientCredentials = tfsCredentials; tfs.Authenticate(); IBuildServer buildServer = tfs.GetService<IBuildServer>(); return buildServer; }
private IEnumerable<TfsClientCredentials> GetBasicAuthCredentials() { var usernameAndPassword = GetAltAuthUsernameAndPasswordFromConfig(); if (usernameAndPassword == null) { return new List<TfsClientCredentials>(); } NetworkCredential netCred = new NetworkCredential(usernameAndPassword.Item1, usernameAndPassword.Item2); BasicAuthCredential basicCred = new BasicAuthCredential(netCred); TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred); tfsCred.AllowInteractive = false; return new List<TfsClientCredentials> { tfsCred }; }
public IJobSubmissionClient Create(BasicAuthCredential credential) { return Create(credential, string.Empty); }
public IJobSubmissionClient Create(BasicAuthCredential credential, string customUserAgent) { return Help.SafeCreate(() => new RemoteHadoopClient(credential, customUserAgent)); }
public IHadoopApplicationHistoryClient CreateHadoopApplicationHistoryClient(BasicAuthCredential credential) { return Help.SafeCreate(() => new RemoteHadoopClient(credential, string.Empty)); }
private IEnumerable<TfsClientCredentials> GetServiceIdentityPatCredentials() { if (string.IsNullOrWhiteSpace(_config.TfsServerConfig.ServiceIdentityPatFile)) { return new List<TfsClientCredentials>(); } var netCred = new NetworkCredential("", GetPatFromConfig()); var basicCred = new BasicAuthCredential(netCred); var patCred = new TfsClientCredentials(basicCred) {AllowInteractive = false}; return new List<TfsClientCredentials> {patCred}; }