public static PackageSourceProvider GetSourceProvider(ISettings settings)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            var sourceProvider = new PackageSourceProvider(settings, enablePackageSourcesChangedEvent: false);
#pragma warning restore CS0618 // Type or member is obsolete
            return(sourceProvider);
        }
Exemplo n.º 2
0
        public void EnableCommandEnableDisabledSourcesCorrectly()
        {
            // Arrange
            var settings = new MockUserSettingsManager();
            settings.SetValues(PackageSourceProvider.PackageSourcesSectionName,
               new[] {
                    new KeyValuePair<string, string>("one", "onesource"),       // enabled
                    new KeyValuePair<string, string>("two", "twosource"),       // disabled
                    new KeyValuePair<string, string>("three", "threesource")    // enabled
                });
            settings.SetValues(PackageSourceProvider.DisabledPackageSourcesSectionName,
                new[] {
                    new KeyValuePair<string, string>("two", "true")
                });

            var packageSourceProvider = new PackageSourceProvider(settings);
            var command = new SourcesCommand(packageSourceProvider);
            command.Arguments.Add("Enable");
            command.Name = "two";
            command.Console = new Mock<IConsole>().Object;

            // Act
            command.ExecuteCommand();

            // Assert
            var packageSources = packageSourceProvider.LoadPackageSources().ToList();
            Assert.Equal(3, packageSources.Count);
            Assert.True(packageSources[0].IsEnabled);
            Assert.True(packageSources[1].IsEnabled);
            Assert.True(packageSources[2].IsEnabled);
        }
Exemplo n.º 3
0
        static SettingsCredentialProvider CreateSettingsCredentialProvider(ICredentialProvider credentialProvider)
        {
            ISettings settings = Settings.LoadDefaultSettings(null, null, null);
            var       packageSourceProvider = new PackageSourceProvider(settings);

            return(new SettingsCredentialProvider(credentialProvider, packageSourceProvider));
        }
Exemplo n.º 4
0
        public virtual async Task <IEnumerable <IPackageSearchMetadata> > QueryPackagesAsync(string packageId, string version = null, bool includePreRelease = false)
        {
            var matches = new List <IPackageSearchMetadata>();

            Logger.LogInformation("Searching repository for package: " + packageId);

            var packageSourceProvider    = new PackageSourceProvider(m_NugetSettings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, m_Providers);

            var sourceRepositories = sourceRepositoryProvider.GetRepositories();

            foreach (var sourceRepository in sourceRepositories)
            {
                var searchResource = await sourceRepository.GetResourceAsync <PackageSearchResource>();

                var searchFilter = new SearchFilter(includePreRelease)
                {
                    IncludeDelisted     = false,
                    SupportedFrameworks = new[] { m_CurrentFramework.DotNetFrameworkName }
                };

                IEnumerable <IPackageSearchMetadata> searchResult;
                try
                {
                    searchResult = (await searchResource.SearchAsync(packageId, searchFilter, 0, 10, Logger, CancellationToken.None)).ToList();
                }
                catch (Exception ex)
                {
                    Logger.LogDebug("Could not find package: ");
                    Logger.LogDebug(ex.ToString());
                    continue;
                }

                if (version == null)
                {
                    Logger.LogDebug("version == null, adding searchResult: " + searchResult.Count());
                    matches.AddRange(searchResult);
                    continue;
                }

                foreach (var packageMeta in searchResult)
                {
                    var versions = (await packageMeta.GetVersionsAsync()).ToList();
                    if (!versions.Any(d
                                      => d.Version.OriginalVersion.Equals(version, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    Logger.LogDebug("adding packageMeta: "
                                    + packageMeta.Identity.Id
                                    + ":"
                                    + packageMeta.Identity.Version);
                    matches.Add(packageMeta);
                }
            }

            return(matches);
        }
        public SourceRepositoryProvider(ISettings settings)
        {
            _repositoryCache      = new ConcurrentDictionary <PackageSource, SourceRepository>();
            PackageSourceProvider = new PackageSourceProvider(settings);

            _resourceProviders = new List <Lazy <INuGetResourceProvider> >();
            _resourceProviders.AddRange(Repository.Provider.GetCoreV3());
        }
        static void InitializeCredentialProvider()
        {
            ISettings settings = Settings.LoadDefaultSettings(null, null, null);
            var       packageSourceProvider = new PackageSourceProvider(settings);
            var       credentialProvider    = new SettingsCredentialProvider(new SharpDevelopCredentialProvider(), packageSourceProvider);

            HttpClient.DefaultCredentialProvider = credentialProvider;
        }
 public PropertyComparisonTest(PackageSourceProvider packageSourceProvider, PackageReader packageReader, TestData testData, Client client, Mapper mapper)
 {
     _packageSourceProvider = packageSourceProvider;
     _packageReader         = packageReader;
     _testData = testData;
     _client   = client;
     _mapper   = mapper;
 }
Exemplo n.º 8
0
        public Bootstrapper(string path)
        {
            var machineWideSettings = new BonsaiMachineWideSettings();
            var settings            = Settings.LoadDefaultSettings(AppDomain.CurrentDomain.BaseDirectory, null, machineWideSettings);
            var sourceProvider      = new PackageSourceProvider(settings);

            packageManager = new RestorePackageManager(sourceProvider, path);
        }
 public NuGetFeedSourceStore(IPreferences preferences)
     : base(preferences)
 {
     _packageSourceProvider = new PackageSourceProvider(
         // Do not load user settings or machine wide settings for WebMatrix 'nuget.org' feed
         // In other words, pass all null to LoadDefaultSettings
         Settings.LoadDefaultSettings(null, null, null),
         defaultSources: new[] { new PackageSource("https://www.nuget.org/api/v2", Resources.NuGet_PackageSourceName) });
 }
Exemplo n.º 10
0
        public SourceRepositoryProvider(ISettings settings)
        {
            // Create the package source provider (needed primarily to get default sources)
            PackageSourceProvider = new PackageSourceProvider(settings);

            // Add the v3 provider as default
            _resourceProviders = new List <Lazy <INuGetResourceProvider> >();
            _resourceProviders.AddRange(Repository.Provider.GetCoreV3());
        }
        public SourceSettings GetSourceSettings(string rootDirectory, string?source)
        {
            var defaultSettings       = Settings.LoadDefaultSettings(rootDirectory);
            var packageSourceProvider = new PackageSourceProvider(defaultSettings);
            var sourcesSettings       = FindSourcesSettings(source, defaultSettings);

            source = sourcesSettings.Source ?? packageSourceProvider.DefaultPushSource ?? throw new InvalidOperationException($"A source for: {source} was not found.");
            return(new SourceSettings(source, sourcesSettings.PackageSourcesSection));
        }
        public void SetFixture(PowerShellCmdletsTestContext data)
        {
            _testContext = data;
            ISettings settings = Settings.LoadDefaultSettings(Environment.ExpandEnvironmentVariables("%systemdrive%"), null, null);
            var       packageSourceProvider = new PackageSourceProvider(settings);
            var       packageSources        = packageSourceProvider.LoadPackageSources();

            _provider = new SourceRepositoryProvider(packageSourceProvider, _testContext.ResourceProviders);
        }
Exemplo n.º 13
0
        static void ConfigureCredentialProvider()
        {
            ISettings settings = Settings.LoadDefaultSettings(null, null, null);
            var       packageSourceProvider = new PackageSourceProvider(settings);

            var credentialProvider = new SettingsCredentialProvider(NullCredentialProvider.Instance, packageSourceProvider);

            HttpClient.DefaultCredentialProvider = credentialProvider;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            AddMenuCommandHandlers();

            // IMPORTANT: Do NOT do anything that can lead to a call to ServiceLocator.GetGlobalService().
            // Doing so is illegal and may cause VS to hang.

            _dte = (DTE)GetService(typeof(SDTE));
            Debug.Assert(_dte != null);

            _dteEvents = _dte.Events.DTEEvents;
            _dteEvents.OnBeginShutdown += OnBeginShutDown;

            // set default credential provider for the HttpClient
            var webProxy = (IVsWebProxy)GetService(typeof(SVsWebProxy));

            Debug.Assert(webProxy != null);

            var settings = Settings.LoadDefaultSettings(
                _solutionManager == null ? null : _solutionManager.SolutionFileSystem,
                configFileName: null,
                machineWideSettings: MachineWideSettings);
            var packageSourceProvider = new PackageSourceProvider(settings);

            HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new VSRequestCredentialProvider(webProxy), packageSourceProvider);

            // when NuGet loads, if the current solution has package
            // restore mode enabled, we make sure every thing is set up correctly.
            // For example, projects which were added outside of VS need to have
            // the <Import> element added.
            if (PackageRestoreManager.IsCurrentSolutionEnabledForRestore)
            {
                if (VsVersionHelper.IsVisualStudio2013)
                {
                    // Run on a background thread in VS2013 to avoid CPS hangs. The modal loading dialog will block
                    // until this completes.
                    ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
                                                                  PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false)));
                }
                else
                {
                    PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
                }
            }

            // when NuGet loads, if the current solution has some package
            // folders marked for deletion (because a previous uninstalltion didn't succeed),
            // delete them now.
            if (SolutionManager.IsSolutionOpen)
            {
                DeleteOnRestart.DeleteMarkedPackageDirectories();
            }
        }
Exemplo n.º 15
0
        public void Sources_WarnWhenUpdatingHttpSource(string updateSource, bool shouldWarn)
        {
            using (TestDirectory configFileDirectory = _fixture.CreateTestDirectory())
            {
                string configFileName = "nuget.config";
                string configFilePath = Path.Combine(configFileDirectory, configFileName);

                var nugetConfig =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageSources>
    <add key=""test_source"" value=""http://source.test.initial"" />
  </packageSources>
</configuration>";
                CreateXmlFile(configFilePath, nugetConfig);

                ISettings settings = Settings.LoadDefaultSettings(
                    configFileDirectory,
                    configFileName,
                    null);

                PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings);
                var sources = packageSourceProvider.LoadPackageSources().ToList();
                Assert.Single(sources);

                PackageSource source = sources.Single();
                Assert.Equal("test_source", source.Name);
                Assert.Equal("http://source.test.initial", source.Source);

                // Arrange
                var args = new string[]
                {
                    "nuget",
                    "update",
                    "source",
                    "test_source",
                    "--source",
                    updateSource,
                    "--configfile",
                    configFilePath
                };

                // Act
                CommandRunnerResult result = _fixture.RunDotnet(configFileDirectory, string.Join(" ", args), ignoreExitCode: true);

                // Assert
                Assert.True(result.Success, result.Output + " " + result.Errors);

                ISettings loadedSettings = Settings.LoadDefaultSettings(root: configFileDirectory, configFileName: null, machineWideSettings: null);

                SettingSection packageSourcesSection = loadedSettings.GetSection("packageSources");
                SourceItem     sourceItem            = packageSourcesSection?.GetFirstItemWithAttribute <SourceItem>("key", "test_source");
                Assert.Equal(updateSource, sourceItem.GetValueAsPath());
                Assert.Equal(shouldWarn, result.Output.Contains("warn : You are running the 'update source' operation with an 'HTTP' source"));
            }
        }
Exemplo n.º 16
0
        public async IAsyncEnumerable <(SourceRepository Repository, IPackageSearchMetadata Package)> SearchPackagesAsync(string searchTerm,
                                                                                                                          int maxResults             = 128,
                                                                                                                          bool includePrerelease     = false,
                                                                                                                          string nugetConfigFilePath = "")
        {
            var providers = GetNugetResourceProviders();

            var packageRootFolder = "";

            if (!string.IsNullOrWhiteSpace(Assembly.GetEntryAssembly()?.Location))
            {
                packageRootFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);
            }

            ISettings settings;

            if (!string.IsNullOrWhiteSpace(nugetConfigFilePath))
            {
                settings = Settings.LoadSettingsGivenConfigPaths(new List <string>()
                {
                    nugetConfigFilePath
                });
            }
            else
            {
                settings = Settings.LoadDefaultSettings(packageRootFolder ?? "", null, new MachineWideSettings());
            }

            var packageSourceProvider    = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, providers);

            var repositories = sourceRepositoryProvider.GetRepositories();

            foreach (var repository in repositories)
            {
                var packageSearchResource = await repository.GetResourceAsync <PackageSearchResource>();

                SearchFilter searchFilter;

                if (includePrerelease)
                {
                    searchFilter = new SearchFilter(includePrerelease, SearchFilterType.IsAbsoluteLatestVersion);
                }
                else
                {
                    searchFilter = new SearchFilter(includePrerelease);
                }

                var items = await packageSearchResource.SearchAsync(searchTerm, searchFilter, 0, maxResults, _logger, CancellationToken.None);

                foreach (var packageSearchMetadata in items)
                {
                    yield return(repository, packageSearchMetadata);
                }
            }
        }
Exemplo n.º 17
0
        public static void PrepareSourceRepositoriesFrom(List <SourceRepository> sourceRepositories, string configFile)
        {
            PackageSourceProvider p = new PackageSourceProvider(new Settings(Path.GetDirectoryName(configFile), Path.GetFileName(configFile), true));
            var sources             = p.LoadPackageSources();

            foreach (var source in sources)
            {
                sourceRepositories.Add(new SourceRepository(source, Repository.Provider.GetCoreV3()));
            }
        }
Exemplo n.º 18
0
        public NuGetSourceRepositoryProvider(ISettings settings, ICakeConfiguration config, PackageReference package)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            // Create the package source provider (needed primarily to get default sources)
            PackageSourceProvider = new PackageSourceProvider(settings);

            // Create the default v3 resource provider
            _resourceProviders = new List <Lazy <INuGetResourceProvider> >();
            _resourceProviders.AddRange(Repository.Provider.GetCoreV3());

            // Add repositories
            _repositories = new List <SourceRepository>();

            if (package.Address != null)
            {
                CreateRepository(package.Address.AbsoluteUri);
            }

            var nugetSources = config.GetValue(Constants.NuGet.Source);

            if (string.IsNullOrEmpty(nugetSources))
            {
                return;
            }

            foreach (var nugetSource in nugetSources.Split(';'))
            {
                if (!string.IsNullOrWhiteSpace(nugetSource))
                {
                    CreateRepository(nugetSource);
                }
            }

            foreach (var source in PackageSourceProvider.LoadPackageSources())
            {
                if (source.IsEnabled)
                {
                    CreateRepository(source);
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// NuGet.Config defines a package source with path 'nuget\' and this is returned on the
        /// Mac as part of the path.
        /// </summary>
        public static void Main(string[] args)
        {
            string rootDirectory         = Directory.GetCurrentDirectory();
            var    settings              = Settings.LoadDefaultSettings(rootDirectory);
            var    packageSourceProvider = new PackageSourceProvider(settings);

            foreach (var packageSource in packageSourceProvider.LoadPackageSources())
            {
                Console.WriteLine(packageSource.Source);
            }
        }
Exemplo n.º 20
0
        protected override void ExecuteTask()
        {
            string dir = SolutionDir.FullName;

            _fileSystem = new PhysicalFileSystem(dir);

            RepositoryFactory = new PackageRepositoryFactory();
            SourceProvider    = new PackageSourceProvider(new Settings(_fileSystem));

            UpdateAllPackages(dir);
        }
Exemplo n.º 21
0
        private static IEnumerable <PackageSource> GetEnabledSources(ISettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var provider = new PackageSourceProvider(settings);

            return(provider.LoadPackageSources().Where(e => e.IsEnabled == true).ToList());
        }
Exemplo n.º 22
0
        LicenseAwarePackageManager CreatePackageManager(PackageSourceProvider packageSourceProvider, IEnumerable <PackageManagerPlugin> plugins)
        {
            var packageManager = new LicenseAwarePackageManager(packageSourceProvider, packageManagerPath);

            packageManager.RequiringLicenseAcceptance += packageManager_RequiringLicenseAcceptance;
            packageManager.Logger = new EventLogger();
            foreach (var plugin in plugins)
            {
                packageManager.PackageManagerPlugins.Add(plugin);
            }
            return(packageManager);
        }
Exemplo n.º 23
0
        public LocalPackageHelper()
        {
            var settings = Settings.LoadDefaultSettings(Directory.GetCurrentDirectory());

            m_globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
            m_localRepository      = new NuGetv3LocalRepository(m_globalPackagesFolder);

            var psp     = new PackageSourceProvider(settings);
            var sources = psp.LoadPackageSources();

            m_repositories = sources.Select(x => Repository.Factory.GetCoreV3(x.Source));
        }
Exemplo n.º 24
0
        private static void NewMethod1()
        {
            var settings = Settings.LoadDefaultSettings(@"<RootDir>");

            var sourceProvider = new PackageSourceProvider(settings);
            var sources        = sourceProvider.LoadPackageSources();


            var retriever = new PackageInfoRetriever(sources);

            var package = retriever.GetNewest("NuGet.Client", true);
        }
        public RestoreCommand AddSourcesFromCurrentConfig()
        {
            var settings = Settings.LoadDefaultSettings(Directory.GetCurrentDirectory(), null, null, false, false);
            var packageSourceProvider = new PackageSourceProvider(settings);

            foreach (var packageSource in packageSourceProvider.LoadPackageSources())
            {
                _sources.Add(packageSource.Source);
            }

            return(this);
        }
Exemplo n.º 26
0
        public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsEmpty()
        {
            // Arrange
            var settings = new Mock <ISettings>();
            var provider = new PackageSourceProvider(settings.Object, defaultSources: new PackageSource[] { });

            // Act
            var values = provider.LoadPackageSources();

            // Assert
            Assert.False(values.Any());
        }
        public Dependency?VerifyLastestVersion(
            Dependency dependency)
        {
            var providers = new List <Lazy <INuGetResourceProvider> >();

            providers.AddRange(
                Repository.Provider.GetCoreV3()
                );

            var settings = Settings.LoadDefaultSettings(
                Directory.GetCurrentDirectory(),
                null,
                new XPlatMachineWideSetting());

            var packageSourceProvider = new PackageSourceProvider(settings);
            var packageSources        = packageSourceProvider.LoadPackageSources();

            var results = new List <IPackageSearchMetadata>();

            foreach (var packageSource in packageSources)
            {
                var sourceRepository = new SourceRepository(
                    packageSource,
                    providers
                    );

                var packageMetadataResource = sourceRepository.GetResourceAsync <PackageMetadataResource>(
                    CancellationToken.None
                    ).Result;

                var result = packageMetadataResource.GetMetadataAsync(
                    dependency.Name,
                    false,
                    true,
                    new NullSourceCacheContext(),
                    NullLogger.Instance,
                    CancellationToken.None
                    ).Result;

                results.AddRange(result);
            }

            var latest = results.OrderByDescending(x => x.Identity.Version).FirstOrDefault();

            if (latest == null)
            {
                return(null);
            }

            return(new Dependency(
                       (Name)latest.Identity.Id,
                       SemVersion.Parse(latest.Identity.Version.ToNormalizedString())));
        }
Exemplo n.º 28
0
        public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsEmpty()
        {
            // Arrange
            var settings = new Mock<ISettings>();
            var provider = new PackageSourceProvider(settings.Object, defaultSources: new PackageSource[] { });

            // Act
            var values = provider.LoadPackageSources();

            // Assert
            Assert.False(values.Any());
        }
        public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsNull()
        {
            // Arrange
            var settings = new MockUserSettingsManager();
            var provider = new PackageSourceProvider(settings, defaultSources: null);

            // Act
            var values = provider.LoadPackageSources();

            // Assert
            Assert.False(values.Any());
        }
Exemplo n.º 30
0
        private static ImmutableList <SourceRepository> GetSourceRepositories()
        {
            ISettings settings = Settings.LoadDefaultSettings(Environment.CurrentDirectory);

            PackageSourceProvider    source   = new PackageSourceProvider(settings);
            SourceRepositoryProvider provider = new SourceRepositoryProvider(source, Repository.Provider.GetCoreV3());

            IEnumerable <PackageSource>    sources      = PackageSourceProvider.LoadPackageSources(settings);
            IEnumerable <SourceRepository> repositories = sources.Select(provider.CreateRepository);

            return(repositories.ToImmutableList());
        }
            private RestoreSummaryRequest Create(
                string inputPath,
                RestoreArgs restoreContext)
            {
                var file = new FileInfo(inputPath);

                // Get settings relative to the input file
                var settings = restoreContext.GetSettings(file.DirectoryName);

                // BUGFIX
                // The null here causes an exception downstream. Instead, inline the important code.
                //var sources = restoreContext.GetEffectiveSources(settings, null);
                var packageSourceProvider = new PackageSourceProvider(settings);
                CachingSourceProvider cachingSourceProvider = new CachingSourceProvider(packageSourceProvider);
                var sources = packageSourceProvider
                              .LoadPackageSources()
                              .Select(cachingSourceProvider.CreateRepository)
                              .ToList();
                // END BUGFIX
                var FallbackPackageFolders = restoreContext.GetEffectiveFallbackPackageFolders(settings);

                var globalPath = restoreContext.GetEffectiveGlobalPackagesFolder(file.DirectoryName, settings);

                var sharedCache = _providerCache.GetOrCreate(
                    globalPath,
                    FallbackPackageFolders,
                    sources,
                    restoreContext.CacheContext,
                    restoreContext.Log);

                var project = JsonPackageSpecReader.GetPackageSpec(file.Directory.Name, file.FullName);

                // BUGFIX
                // ApplyStandardProperties tries to access RestoreMetadata with no null check. Add
                // a default value.
                project.RestoreMetadata = new ProjectRestoreMetadata();
                // END BUGFIX

                var request = new RestoreRequest(
                    project,
                    sharedCache,
                    restoreContext.CacheContext,
                    restoreContext.Log);

                restoreContext.ApplyStandardProperties(request);

                IEnumerable <string> configFiles = SettingsUtility.GetConfigFilePaths(settings);

                var summaryRequest = new RestoreSummaryRequest(request, inputPath, configFiles, sources);

                return(summaryRequest);
            }
Exemplo n.º 32
0
            public override void Context()
            {
                RemoveAndCreateDirectory(destDir1);
                RemoveAndCreateDirectory(destDir2);

                var defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl);
                var settings = Settings.LoadDefaultSettings();
                IPackageSourceProvider sourceProvider = new PackageSourceProvider(settings, new[] { defaultPackageSource });
                IPackageRepositoryFactory repositoryFactory = new CommandLineRepositoryFactory();

                command = new Copy(repositoryFactory, sourceProvider);
                command.Console = new Console();
            }
Exemplo n.º 33
0
        protected static LicenseAwarePackageManager CreatePackageManager(string path)
        {
            var logger = new EventLogger();
            var machineWideSettings = new BonsaiMachineWideSettings();
            var settings            = Settings.LoadDefaultSettings(new PhysicalFileSystem(AppDomain.CurrentDomain.BaseDirectory), null, machineWideSettings);
            var sourceProvider      = new PackageSourceProvider(settings);
            var sourceRepository    = sourceProvider.CreateAggregateRepository(PackageRepositoryFactory.Default, true);

            return(new LicenseAwarePackageManager(sourceRepository, path)
            {
                Logger = logger
            });
        }
Exemplo n.º 34
0
            public override void Context()
            {
                RemoveAndCreateDirectory(destDir1);
                RemoveAndCreateDirectory(destDir2);

                var defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl);
                var settings             = Settings.LoadDefaultSettings();
                IPackageSourceProvider    sourceProvider    = new PackageSourceProvider(settings, new[] { defaultPackageSource });
                IPackageRepositoryFactory repositoryFactory = new CommandLineRepositoryFactory();

                command         = new Copy(repositoryFactory, sourceProvider);
                command.Console = new Console();
            }
Exemplo n.º 35
0
        public void LoadPackageSourcesReturnsDefaultSourcesIfSpecified()
        {
            // Arrange
            var settings = new Mock<ISettings>().Object;
            var provider = new PackageSourceProvider(settings, defaultSources: new[] { new PackageSource("A"), new PackageSource("B") });

            // Act
            var values = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(2, values.Count);
            Assert.Equal("A", values.First().Source);
            Assert.Equal("B", values.Last().Source);
        }
        public void GetCredentialQueriesUnderlyingProviderIfProxyCredentialsAreRequested()
        {
            // Arrange
            var underlyingProvider = new Mock<ICredentialProvider>(MockBehavior.Strict);
            underlyingProvider.Setup(p => p.GetCredentials(It.IsAny<Uri>(), It.IsAny<IWebProxy>(), CredentialType.ProxyCredentials, false))
                              .Returns<ICredentials>(null).Verifiable();

            var packageSourceProvider = new PackageSourceProvider(NullSettings.Instance);
            var settingsCredentialProvider = new SettingsCredentialProvider(underlyingProvider.Object, packageSourceProvider);

            // Act
            var value = settingsCredentialProvider.GetCredentials(new Uri("http://nuget.org"), new Mock<IWebProxy>().Object, CredentialType.ProxyCredentials, false);

            // Assert
            Assert.Null(value);
            underlyingProvider.Verify();
        }
Exemplo n.º 37
0
        public void PrimaryAndSecondaryAreAddedWhenNotPresent()
        {
            // Act
            NullSettings settings = new NullSettings();
            List<PackageSource> primary = new List<PackageSource>();
            PackageSource item = new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName);
            primary.Add(item);

            List<PackageSource> secondary = new List<PackageSource>();
            PackageSource item2 = new PackageSource(NuGetConstants.V2FeedUrl, NuGetConstants.V2FeedName, false);
            secondary.Add(item2);

            PackageSourceProvider psp = new PackageSourceProvider(settings, primary, secondary);

            // Assert
            //Primary IsEnabled = true, IsOfficial = true (Added for the first time)
            //Secondary IsEnabled = false, IsOfficial = true  (Added for the first time)
            VerifyPackageSource(psp, 2, new string[] { NuGetConstants.V3FeedName, NuGetConstants.V2FeedName },
                new string[] { NuGetConstants.V3FeedUrl, NuGetConstants.V2FeedUrl },
                new bool[] { true, false }, new bool[] { true, true });
        }
Exemplo n.º 38
0
        public void SecondaryIsAddedWhenNotPresentButDisabled()
        {
            // Act
            //Create nuget.config that has Primary defined and Secondary missing
            string nugetConfigFileFolder = TestFilesystemUtility.CreateRandomTestFolder();
            var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.config");
            File.Create(nugetConfigFilePath).Close();

            var enabledReplacement = @"<add key='" + NuGetConstants.V3FeedName + "' value='" + NuGetConstants.V3FeedUrl + "' />";
            var disabledReplacement = string.Empty;
            File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement));

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            VerifyPackageSource(before, 1, new string[] { NuGetConstants.V3FeedName },
                new string[] { NuGetConstants.V3FeedUrl },
                new bool[] { true }, new bool[] { false });

            List<PackageSource> primary = new List<PackageSource>();
            PackageSource item = new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName);
            primary.Add(item);

            List<PackageSource> secondary = new List<PackageSource>();
            PackageSource item2 = new PackageSource(NuGetConstants.V2FeedUrl, NuGetConstants.V2FeedName, false);
            secondary.Add(item2);

            PackageSourceProvider after = new PackageSourceProvider(settings, primary, secondary);

            // Assert
            //Primary already exists in nuget.config as Enabled. So IsEnabled = true. IsOfficial is also set to true when loading package sources
            //Primary IsEnabled = true, IsOfficial = true
            //Secondary is added, marked as official but added as disabled
            //Secondary IsEnabled = false, IsOfficial = true
            VerifyPackageSource(after, 2, new string[] { NuGetConstants.V3FeedName, NuGetConstants.V2FeedName },
                new string[] { NuGetConstants.V3FeedUrl, NuGetConstants.V2FeedUrl },
                new bool[] { true, false }, new bool[] { true, true });

            //Clean up
            TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
Exemplo n.º 39
0
        public void PrimaryURLIsForcedWhenPrimaryNameHasAnotherFeed()
        {
            // Act
            //Create nuget.config that has Primary name used for a different feed
            string nugetConfigFileFolder = TestFilesystemUtility.CreateRandomTestFolder();
            var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.config");
            File.Create(nugetConfigFilePath).Close();

            var randomURL = "https://www.somerandomURL.com/";
            var enabledReplacement = @"<add key='" + NuGetConstants.V3FeedName + "' value='" + randomURL + "' />";
            var disabledReplacement = string.Empty;
            File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement));

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            VerifyPackageSource(before, 1, new string[] { NuGetConstants.V3FeedName },
                new string[] { randomURL },
                new bool[] { true }, new bool[] { false });

            List<PackageSource> primary = new List<PackageSource>();
            PackageSource item = new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName);
            primary.Add(item);

            PackageSourceProvider after = new PackageSourceProvider(settings, primary, null);

            // Assert
            //Primary Name already exists in nuget.config but with different URL
            //It gets overwritten by primary package source (which is enabled above while creating it)
            //IsEnabled = true, IsOfficial = true
            VerifyPackageSource(after, 1, new string[] { NuGetConstants.V3FeedName },
                new string[] { NuGetConstants.V3FeedUrl },
                new bool[] { false }, new bool[] { true });

            //Clean up
            TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
        public void ActivePackageSourceReturnsNullIfNotSetInNuGetConfig()
        {
            // Act
            //Create nuget.config that has active package source defined
            string nugetConfigFileFolder = NuGet.Configuration.Test.TestFilesystemUtility.CreateRandomTestFolder();
            string nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.Config");
            File.Create(nugetConfigFilePath).Close();

            string enabledReplacement = @"<add key='" + NuGetConstants.V2FeedName + "' value='" + NuGetConstants.V2FeedUrl + "' />";
            File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement));

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            Assert.Null(before.ActivePackageSourceName);

            before.SaveActivePackageSource(new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName));
            Assert.Equal(NuGetConstants.V3FeedName, before.ActivePackageSourceName);

            //Clean up
            NuGet.Configuration.Test.TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
        public void SavePackageSourcesWillNotSaveTheWindows8ExpressFeedWhenRunningWindows8Express()
        {
            // Arrange
            var mockFileSystem = new MockFileSystem();            
            var settings = Settings.LoadDefaultSettings(
                mockFileSystem,
                configFileName: null,
                machineWideSettings: null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(settings, packageSourceProvider, vsShellInfo.Object);
            var packageSources = provider.LoadPackageSources().ToList();

            Assert.Equal(1, packageSources.Count);
            Assert.Equal(NuGetConstants.VSExpressForWindows8FeedUrl, packageSources[0].Source);
            Assert.True(packageSources[0].IsEnabled);

            // Act
            provider.SavePackageSources(packageSources);

            // Assert
            // the Win8ExpressFeed is saved as active source, but not saved
            // in <packageSources>.
            Assert.Equal(1, mockFileSystem.Paths.Count);
            var configFile = mockFileSystem.Paths.First().Key;
            var configFileContent = mockFileSystem.ReadAllText(configFile);

            Assert.Equal(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <activePackageSource>
    <add key=""Windows 8 Packages"" value=""https://www.nuget.org/api/v2/curated-feeds/windows8-packages/"" />
  </activePackageSource>
</configuration>".Replace("\r", ""),
                  configFileContent.Replace("\r", ""));
        }
        public void LoadPackageSourcesWillAddTheWindows8SourceAtTheFrontWhenRunningWindows8Express()
        {
            // Arrange
            var mockFileSystem = new MockFileSystem();
            mockFileSystem.AddFile("nuget.config",
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageSources>
    <add key=""a"" value=""http://a"" />
  </packageSources>
</configuration>");

            var settings = Settings.LoadDefaultSettings(
                mockFileSystem,
                configFileName: null,
                machineWideSettings: null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(settings, packageSourceProvider, vsShellInfo.Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(2, sources.Count);
            AssertPackageSource(sources[0], "Windows 8 Packages", NuGetConstants.VSExpressForWindows8FeedUrl);
            AssertPackageSource(sources[1], "a", "http://a");
        }
Exemplo n.º 43
0
        public void LoadPackageSourcesPerformMigrationIfSpecified()
        {
            // Arrange
            var settings = new Mock<ISettings>();
            settings.Setup(s => s.GetValues("packageSources")).Returns(
                new[] { 
                    new KeyValuePair<string, string>("one", "onesource"),
                    new KeyValuePair<string, string>("two", "twosource"),
                    new KeyValuePair<string, string>("three", "threesource"),
                }
            );

            // disable package "three"
            settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("three", "true" ) });

            IList<KeyValuePair<string, string>> savedSettingValues = null;
            settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>()))
                    .Callback<string, IList<KeyValuePair<string, string>>>((_, savedVals) => { savedSettingValues = savedVals; })
                    .Verifiable();

            var provider = new PackageSourceProvider(settings.Object,
                null,
                new Dictionary<PackageSource, PackageSource> {
                    { new PackageSource("onesource", "one"), new PackageSource("goodsource", "good") },
                    { new PackageSource("foo", "bar"), new PackageSource("foo", "bar") },
                    { new PackageSource("threesource", "three"), new PackageSource("awesomesource", "awesome") }
                }
            );

            // Act
            var values = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(3, values.Count);
            AssertPackageSource(values[0], "good", "goodsource", true);
            AssertPackageSource(values[1], "two", "twosource", true);
            AssertPackageSource(values[2], "awesome", "awesomesource", false);

            Assert.Equal(3, savedSettingValues.Count);
            Assert.Equal("good", savedSettingValues[0].Key);
            Assert.Equal("goodsource", savedSettingValues[0].Value);
            Assert.Equal("two", savedSettingValues[1].Key);
            Assert.Equal("twosource", savedSettingValues[1].Value);
            Assert.Equal("awesome", savedSettingValues[2].Key);
            Assert.Equal("awesomesource", savedSettingValues[2].Value);
        }
        public void LoadPackageSourcesPerformMigrationIfSpecified()
        {
            // Arrange
            var settings = new MockUserSettingsManager();
            settings.SetValues(
                PackageSourceProvider.PackageSourcesSectionName,
                new KeyValuePair<string, string>[] { 
                    new KeyValuePair<string, string>("one", "onesource"),
                    new KeyValuePair<string, string>("two", "twosource"),
                    new KeyValuePair<string, string>("three", "threesource"),
                }
            );

            // disable package "three"
            settings.SetValue(
                PackageSourceProvider.DisabledPackageSourcesSectionName,
                "three",
                "threesource");

            var provider = new PackageSourceProvider(
                settings,
                null,
                new Dictionary<PackageSource, PackageSource> {
                    { new PackageSource("onesource", "one"), new PackageSource("goodsource", "good") },
                    { new PackageSource("foo", "bar"), new PackageSource("foo", "bar") },
                    { new PackageSource("threesource", "three"), new PackageSource("awesomesource", "awesome") }
                }
            );

            // Act
            var values = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(3, values.Count);
            AssertPackageSource(values[0], "good", "goodsource", true);
            AssertPackageSource(values[1], "two", "twosource", true);
            AssertPackageSource(values[2], "awesome", "awesomesource", false);

            var savedSettingValues = settings.GetValues(PackageSourceProvider.PackageSourcesSectionName);
            Assert.Equal(3, savedSettingValues.Count);
            Assert.Equal("good", savedSettingValues[0].Key);
            Assert.Equal("goodsource", savedSettingValues[0].Value);
            Assert.Equal("two", savedSettingValues[1].Key);
            Assert.Equal("twosource", savedSettingValues[1].Value);
            Assert.Equal("awesome", savedSettingValues[2].Key);
            Assert.Equal("awesomesource", savedSettingValues[2].Value);
        }
Exemplo n.º 45
0
        private void VerifyPackageSource(PackageSourceProvider psp, int count, string[] names, string[] feeds, bool[] isEnabled, bool[] isOfficial)
        {
            List<PackageSource> toVerifyList = new List<PackageSource>();
            toVerifyList = psp.LoadPackageSources().ToList();

            Assert.Equal(toVerifyList.Count, count);
            var index = 0;
            foreach (PackageSource ps in toVerifyList)
            {
                Assert.Equal(ps.Name, names[index]);
                Assert.Equal(ps.Source, feeds[index]);
                Assert.Equal(ps.IsEnabled, isEnabled[index]);
                Assert.Equal(ps.IsOfficial, isOfficial[index]);
                index++;
            }
        }
Exemplo n.º 46
0
        public void SavePackageSources_AddsOrderingForCollapsedFeeds()
        {
            using (var mockBaseDirectory = TestFilesystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var configContents =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <packageSources>
        <add key=""nuget.org"" value=""https://nuget.org"" />
        <add key=""test.org"" value=""https://test.org"" />
        <add key=""test.org"" value=""https://new.test.org"" protocolVersion=""3"" />
        <add key=""test2"" value=""https://test2.net"" />
    </packageSources>
</configuration>
";
                File.WriteAllText(Path.Combine(mockBaseDirectory.Path, "NuGet.config"), configContents);

                var rootPath = Path.Combine(mockBaseDirectory.Path, Path.GetRandomFileName());

                var settings = Settings.LoadDefaultSettings(rootPath,
                    configFileName: null,
                    machineWideSettings: null,
                    loadAppDataSettings: false);
                var packageSourceProvider = new PackageSourceProvider(settings);

                // Act - 1
                var sources = packageSourceProvider.LoadPackageSources().ToList();

                // Assert - 2
                Assert.Collection(sources,
                    source =>
                        {
                            Assert.Equal("nuget.org", source.Name);
                            Assert.Equal("https://nuget.org", source.Source);
                            Assert.True(source.IsEnabled);
                        },
                    source =>
                        {
                            Assert.Equal("test.org", source.Name);
                            Assert.Equal("https://new.test.org", source.Source);
                            Assert.True(source.IsEnabled);
                            Assert.Equal(3, source.ProtocolVersion);
                        },
                    source =>
                        {
                            Assert.Equal("test2", source.Name);
                            Assert.Equal("https://test2.net", source.Source);
                            Assert.True(source.IsEnabled);
                        });

                // Act - 2
                sources[1].Source = "https://new2.test.org";
                var sourcesToSave = new[]
                    {
                        sources[1], sources[2], sources[0]
                    };
                packageSourceProvider.SavePackageSources(sourcesToSave);

                // Assert - 2
                Assert.Equal(
                    TestFilesystemUtility.RemovedLineEndings(
                        @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageSources>
    <add key=""test.org"" value=""https://test.org"" />
    <add key=""test.org"" value=""https://new2.test.org"" protocolVersion=""3"" />
    <add key=""test2"" value=""https://test2.net"" />
    <add key=""nuget.org"" value=""https://nuget.org"" />
  </packageSources>
</configuration>
"),
                    TestFilesystemUtility.RemovedLineEndings(File.ReadAllText(Path.Combine(mockBaseDirectory.Path, "NuGet.config"))));
            }
        }
Exemplo n.º 47
0
        public void SavePackageSources_AddsNewSourcesToTheSettingWithLowestPriority()
        {
            using (var mockBaseDirectory = TestFilesystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var config1Contents =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>  <packageSources>    <add key=""test.org"" value=""https://test.org"" />  </packageSources>
</configuration>
";
                var config2Contents =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<packageSources>
    <add key='NuGet.org' value='https://NuGet.org' />
</packageSources>
</configuration>
";
                File.WriteAllText(Path.Combine(mockBaseDirectory.Path, "NuGet.config"), config1Contents);

                var rootPath = Path.Combine(mockBaseDirectory.Path, Path.GetRandomFileName());
                Directory.CreateDirectory(rootPath);
                File.WriteAllText(Path.Combine(rootPath, "NuGet.config"), config2Contents);

                var settings = Settings.LoadDefaultSettings(rootPath,
                    configFileName: null,
                    machineWideSettings: null,
                    loadAppDataSettings: false);
                var packageSourceProvider = new PackageSourceProvider(settings);

                // Act - 1
                var sources = packageSourceProvider.LoadPackageSources().ToList();

                // Assert - 1
                Assert.Collection(sources,
                    source =>
                        {
                            Assert.Equal("NuGet.org", source.Name);
                            Assert.Equal("https://NuGet.org", source.Source);
                            Assert.True(source.IsEnabled);
                        },
                    source =>
                        {
                            Assert.Equal("test.org", source.Name);
                            Assert.Equal("https://test.org", source.Source);
                            Assert.True(source.IsEnabled);
                        });

                // Act - 2
                sources[1].IsEnabled = false;
                sources.Insert(1, new PackageSource("http://newsource", "NewSourceName"));

                packageSourceProvider.SavePackageSources(sources);

                // Assert - 2
                Assert.Equal(
                    TestFilesystemUtility.RemovedLineEndings(
                        @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>  <packageSources>    <add key=""NewSourceName"" value=""http://newsource"" />    <add key=""test.org"" value=""https://test.org"" />  </packageSources>
  <disabledPackageSources>
    <add key=""test.org"" value=""true"" />
  </disabledPackageSources>
</configuration>
"),
                    TestFilesystemUtility.RemovedLineEndings(File.ReadAllText(Path.Combine(mockBaseDirectory.Path, "NuGet.config"))));

                Assert.Equal(
                    TestFilesystemUtility.RemovedLineEndings(
                        @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>  <packageSources>    <add key=""NuGet.org"" value=""https://NuGet.org"" />  </packageSources>
</configuration>
"),
                    TestFilesystemUtility.RemovedLineEndings(File.ReadAllText(Path.Combine(rootPath, "NuGet.config"))));
            }
        }
Exemplo n.º 48
0
        public void SavePackageSources_AddDisabledSourceToTheConfigContainingSource()
        {
            using (var mockBaseDirectory = TestFilesystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var config1Contents =
                    @"<?xml version=""1.0""?>
<configuration>
<packageSources>
    <add key='NuGet.org' value='https://NuGet.org' />
</packageSources>
</configuration>
";
                File.WriteAllText(Path.Combine(mockBaseDirectory.Path, "NuGet.config"), config1Contents);

                var config2Contents =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>\r\n<configuration></configuration";
                var rootPath = Path.Combine(mockBaseDirectory.Path, Path.GetRandomFileName());
                Directory.CreateDirectory(rootPath);
                File.WriteAllText(Path.Combine(rootPath, "NuGet.config"), config2Contents);

                var settings = Settings.LoadDefaultSettings(rootPath,
                    configFileName: null,
                    machineWideSettings: null,
                    loadAppDataSettings: false);
                var packageSourceProvider = new PackageSourceProvider(settings);

                // Act - 1
                var sources = packageSourceProvider.LoadPackageSources();

                // Assert - 2
                var source = Assert.Single(sources);
                Assert.Equal("NuGet.org", source.Name);
                Assert.Equal("https://NuGet.org", source.Source);
                Assert.True(source.IsEnabled);

                // Act - 2
                source.IsEnabled = false;
                packageSourceProvider.SavePackageSources(sources);

                // Assert - 3
                Assert.Equal(TestFilesystemUtility.RemovedLineEndings(config2Contents),
                    TestFilesystemUtility.RemovedLineEndings(File.ReadAllText(Path.Combine(rootPath, "NuGet.config"))));
                Assert.Equal(
                    TestFilesystemUtility.RemovedLineEndings(
                        @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>  <packageSources>    <add key=""NuGet.org"" value=""https://NuGet.org"" />  </packageSources>
  <disabledPackageSources>
    <add key=""NuGet.org"" value=""true"" />
  </disabledPackageSources>
</configuration>
"),
                    TestFilesystemUtility.RemovedLineEndings(File.ReadAllText(Path.Combine(mockBaseDirectory.Path, "NuGet.config"))));
            }
        }
        public void SecondaryURLIsForcedWhenSecondaryNameHasAnotherFeed()
        {
            // Act
            //Create nuget.config that has Secondary name used for a different feed
            string nugetConfigFileFolder = NuGet.Configuration.Test.TestFilesystemUtility.CreateRandomTestFolder();
            string nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.config");
            File.Create(nugetConfigFilePath).Close();
            

            string randomURL = "https://www.somerandomURL.com/";
            string enabledReplacement = @"<add key='" + NuGetConstants.V3FeedName + "' value='" + NuGetConstants.V3FeedUrl + "' />";
            enabledReplacement = enabledReplacement + @"<add key='" + NuGetConstants.V2FeedName + "' value='" + randomURL + "' />";
            string disabledReplacement = string.Empty;
            File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement));

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            VerifyPackageSource(before, 2, new string[] { NuGetConstants.V3FeedName, NuGetConstants.V2FeedName },
                            new string[] { NuGetConstants.V3FeedUrl, randomURL },
                            new bool[] { true, true }, new bool[] { false, false });

            List<PackageSource> primary = new List<PackageSource>();
            PackageSource item = new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName);
            primary.Add(item);

            List<PackageSource> secondary = new List<PackageSource>();
            PackageSource item2 = new PackageSource(NuGetConstants.V2FeedUrl, NuGetConstants.V2FeedName, false);
            secondary.Add(item2);

            PackageSourceProvider after = new PackageSourceProvider(settings, primary, secondary);

            // Assert
            //Seconday name already exists in nuget.config but with different URL
            //It gets overwritten by secondary scource which is disabled (while getting created above)
            //IsOfficial is set to true
            VerifyPackageSource(after, 2, new string[] { NuGetConstants.V3FeedName, NuGetConstants.V2FeedName },
                                new string[] { NuGetConstants.V3FeedUrl, NuGetConstants.V2FeedUrl },
                                new bool[] { true, false }, new bool[] { true, true });

            //Clean up
            NuGet.Configuration.Test.TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
Exemplo n.º 50
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            AddMenuCommandHandlers();

            // IMPORTANT: Do NOT do anything that can lead to a call to ServiceLocator.GetGlobalService(). 
            // Doing so is illegal and may cause VS to hang.

            _dte = (DTE)GetService(typeof(SDTE));
            Debug.Assert(_dte != null);

            _dteEvents = _dte.Events.DTEEvents;
            _dteEvents.OnBeginShutdown += OnBeginShutDown;

            // set default credential provider for the HttpClient
            var webProxy = (IVsWebProxy)GetService(typeof(SVsWebProxy));
            Debug.Assert(webProxy != null);

            var settings = Settings.LoadDefaultSettings(
                _solutionManager == null ? null : _solutionManager.SolutionFileSystem,
                configFileName: null,
                machineWideSettings: MachineWideSettings);
            var packageSourceProvider = new PackageSourceProvider(settings);
            HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new VSRequestCredentialProvider(webProxy), packageSourceProvider);
            
            // when NuGet loads, if the current solution has package 
            // restore mode enabled, we make sure every thing is set up correctly.
            // For example, projects which were added outside of VS need to have
            // the <Import> element added.
            if (PackageRestoreManager.IsCurrentSolutionEnabledForRestore)
            {
                PackageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
            }

            // when NuGet loads, if the current solution has some package 
            // folders marked for deletion (because a previous uninstalltion didn't succeed),
            // delete them now.
            if (SolutionManager.IsSolutionOpen)
            {
                DeleteOnRestart.DeleteMarkedPackageDirectories();
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            AddMenuCommandHandlers();

            // IMPORTANT: Do NOT do anything that can lead to a call to ServiceLocator.GetGlobalService(). 
            // Doing so is illegal and may cause VS to hang.

            _dte = (DTE)GetService(typeof(SDTE));
            Debug.Assert(_dte != null);

            // set default credential provider for the HttpClient
            var webProxy = (IVsWebProxy)GetService(typeof(SVsWebProxy));
            Debug.Assert(webProxy != null);

            var settings = Settings.LoadDefaultSettings();
            var packageSourceProvider = new PackageSourceProvider(settings);
            HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new VSRequestCredentialProvider(webProxy), packageSourceProvider);

            // when NuGet loads, if the current solution has package 
            // restore mode enabled, we make sure every thing is set up correctly.
            // For example, projects which were added outside of VS need to have
            // the <Import> element added.
            if (PackageRestoreManager.IsCurrentSolutionEnabledForRestore)
            {
                _packageRestoreManager.EnableCurrentSolutionForRestore(fromActivation: false);
            }
        }
Exemplo n.º 52
0
        public void PrimaryIsEnabledAndSecondaryIsDisabledWhenPrimaryIsAddedForTheFirstTimeAndSecondaryAlreadyExists()
        {
            // Act
            //Create nuget.config that has Secondary defined
            string nugetConfigFileFolder = TestFilesystemUtility.CreateRandomTestFolder();
            var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.Config");
            File.Create(nugetConfigFilePath).Close();

            var enabledReplacement = @"<add key='" + NuGetConstants.V2FeedName + "' value='" + NuGetConstants.V2FeedUrl + "' />";
            var disabledReplacement = string.Empty;
            File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement));

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            VerifyPackageSource(before, 1, new string[] { NuGetConstants.V2FeedName },
                new string[] { NuGetConstants.V2FeedUrl },
                new bool[] { true }, new bool[] { false });

            List<PackageSource> primary = new List<PackageSource>();
            PackageSource item = new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName);
            primary.Add(item);

            List<PackageSource> secondary = new List<PackageSource>();
            PackageSource item2 = new PackageSource(NuGetConstants.V2FeedUrl, NuGetConstants.V2FeedName, false);
            secondary.Add(item2);

            PackageSourceProvider after = new PackageSourceProvider(settings, primary, secondary);

            // Assert
            //First time Primary is getting added so it is set to Enabled
            //Secondary is demoted to disabled even though it is already enabled through nuget.config
            VerifyPackageSource(after, 2, new string[] { NuGetConstants.V2FeedName, NuGetConstants.V3FeedName },
                new string[] { NuGetConstants.V2FeedUrl, NuGetConstants.V3FeedUrl },
                new bool[] { false, true }, new bool[] { true, true });

            //Clean up
            TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
Exemplo n.º 53
0
        public void ActivePackageSourceCanBeReadAndWrittenInNuGetConfig()
        {
            // Act
            //Create nuget.config that has active package source defined
            string nugetConfigFileFolder = TestFilesystemUtility.CreateRandomTestFolder();
            var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.Config");
            File.Create(nugetConfigFilePath).Close();

            var enabledReplacement = @"<add key='" + NuGetConstants.V2FeedName + "' value='" + NuGetConstants.V2FeedUrl + "' />";
            var disabledReplacement = string.Empty;
            var activeReplacement = @"<add key='" + NuGetConstants.V2FeedName + "' value='" + NuGetConstants.V2FeedUrl + "' />";
            File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement, activeReplacement));

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            Assert.Equal(NuGetConstants.V2FeedName, before.ActivePackageSourceName);

            before.SaveActivePackageSource(new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName));
            Assert.Equal(NuGetConstants.V3FeedName, before.ActivePackageSourceName);

            //Clean up
            TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
        public void TheDisabledStateOfWindows8FeedIsPersistedWhenRunningOnWindows8Express()
        {
            // Arrange
            var mockFileSystem = new MockFileSystem();
            var settings = Settings.LoadDefaultSettings(
                mockFileSystem,
                configFileName: null,
                machineWideSettings: null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(true);
            var provider = new VsPackageSourceProvider(settings, packageSourceProvider, vsShellInfo.Object);
            var packageSources = provider.LoadPackageSources().ToList();

            Assert.Equal(1, packageSources.Count);
            Assert.Equal(NuGetConstants.VSExpressForWindows8FeedUrl, packageSources[0].Source);
            Assert.True(packageSources[0].IsEnabled);

            // Act
            packageSources[0].IsEnabled = false;
            provider.SavePackageSources(packageSources);

            // Assert
            // the Win8ExpressFeed is not saved in <disabledPackageSources>.
            Assert.Equal(1, mockFileSystem.Paths.Count);
            var configFile = mockFileSystem.Paths.First().Key;
            var configFileContent = mockFileSystem.ReadAllText(configFile);

            Assert.Equal(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <packageSources />
  <disabledPackageSources>
    <add key=""Windows 8 Packages"" value=""true"" />
  </disabledPackageSources>
</configuration>".Replace("\r", ""),
                  configFileContent.Replace("\r", ""));
        }
Exemplo n.º 55
0
        public void ActivePackageSourceReturnsNullIfNotPresentInNuGetConfig()
        {
            // Act
            //Create nuget.config that has active package source defined
            string nugetConfigFileFolder = TestFilesystemUtility.CreateRandomTestFolder();
            var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.Config");
            File.Create(nugetConfigFilePath).Close();

            var enabledReplacement = @"<add key='" + NuGetConstants.V2FeedName + "' value='" + NuGetConstants.V2FeedUrl + "' />";
            var fileContents = CreateNuGetConfigContent(enabledReplacement);
            fileContents = fileContents.Replace("<activePackageSource>", string.Empty);
            fileContents = fileContents.Replace("</activePackageSource>", string.Empty);
            File.WriteAllText(nugetConfigFilePath, fileContents);

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            Assert.Null(before.ActivePackageSourceName);

            SettingValue newActiveValue = new SettingValue(NuGetConstants.V3FeedName, NuGetConstants.V3FeedUrl, false);
            before.SaveActivePackageSource(new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName));
            Assert.Equal(NuGetConstants.V3FeedName, before.ActivePackageSourceName);

            //Clean up
            TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
        public void LoadPackageSourcesWillNotAddTheWindows8SourceWhenNotRunningWindows8Express()
        {
            // Arrange
            var mockFileSystem = new MockFileSystem();
            var settings = Settings.LoadDefaultSettings(
                mockFileSystem,
                configFileName: null,
                machineWideSettings: null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var vsShellInfo = new Mock<IVsShellInfo>();
            vsShellInfo.Setup(_ => _.IsVisualStudioExpressForWindows8).Returns(false);
            var provider = new VsPackageSourceProvider(settings, packageSourceProvider, vsShellInfo.Object);

            // Act
            var sources = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(0, sources.Count);
        }
Exemplo n.º 57
0
        public async Task LoadPackageSourcesWithCredentials()
        {
            // Arrange
            //Create nuget.config that has active package source defined
            string nugetConfigFileFolder = TestFilesystemUtility.CreateRandomTestFolder();
            var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.Config");

            var configContent = @"<?xml version='1.0' encoding='utf-8'?>
<configuration>
  <apikeys>
    <add key='https://www.nuget.org' value='removed' />
    <add key='https://www.myget.org/F/somecompanyfeed-unstable/' value='removed' />
    <add key='https://www.myget.org/F/somecompanyfeed/' value='removed' />
    <add key='https://www.myget.org/F/somecompanyfeed-unstable/api/v2/package' value='removed' />
    <add key='https://www.myget.org/F/somecompanyfeed/api/v2/package' value='removed' />
    <add key='https://www.myget.org/F/somecompanyfeed-unstable/api/v2/' value='removed' />
    <add key='http://nuget.gw.symbolsource.org/Public/NuGet' value='removed' />
  </apikeys>
  <packageRestore>
    <add key='enabled' value='True' />
    <add key='automatic' value='True' />
  </packageRestore>
  <activePackageSource>
    <add key='NuGet.org' value='https://nuget.org/api/v2/' />
  </activePackageSource>
  <packageSources>
    <add key='CodeCrackerUnstable' value='https://www.myget.org/F/codecrackerbuild/api/v2' />
    <add key='CompanyFeedUnstable' value='https://www.myget.org/F/somecompanyfeed-unstable/api/v2/' />
    <add key='NuGet.org' value='https://nuget.org/api/v2/' />
    <add key='AspNetVNextStable' value='https://www.myget.org/F/aspnetmaster/api/v2' />
    <add key='AspNetVNextUnstable' value='https://www.myget.org/F/aspnetvnext/api/v2' />
    <add key='CompanyFeed' value='https://www.myget.org/F/somecompanyfeed/api/v2/' />
  </packageSources>
  <packageSourceCredentials>
    <CodeCrackerUnstable>
      <add key='Username' value='myusername' />
    </CodeCrackerUnstable>
    <AspNetVNextUnstable>
      <add key='Username' value='myusername' />
    </AspNetVNextUnstable>
    <AspNetVNextStable>
      <add key='Username' value='myusername' />
    </AspNetVNextStable>
    <NuGet.org>
      <add key='Username' value='myusername' />
    </NuGet.org>
    <CompanyFeedUnstable>
      <add key='Username' value='myusername' />
      <add key='ClearTextPassword' value='removed' />
    </CompanyFeedUnstable>
    <CompanyFeed>
      <add key='Username' value='myusername' />
      <add key='ClearTextPassword' value='removed' />
    </CompanyFeed>
  </packageSourceCredentials>
</configuration>";

            using (var stream = File.Create(nugetConfigFilePath))
            {
                var bytes = Encoding.UTF8.GetBytes(configContent);
                await stream.WriteAsync(bytes, 0, configContent.Length);
            }

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider psp = new PackageSourceProvider(settings);

            var sources = psp.LoadPackageSources().ToList();

            Assert.Equal(6, sources.Count);
            Assert.NotNull(sources[1].Password);
            Assert.True(String.Equals(sources[1].Password, "removed", StringComparison.OrdinalIgnoreCase));
            Assert.NotNull(sources[5].Password);
            Assert.True(String.Equals(sources[5].Password, "removed", StringComparison.OrdinalIgnoreCase));
        }
Exemplo n.º 58
0
        public void SecondaryNameNotChangedWhenTheFeedHasAnotherName()
        {
            // Act
            //Create nuget.config that has Primary defined and Secondary missing
            string nugetConfigFileFolder = TestFilesystemUtility.CreateRandomTestFolder();
            var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, "nuget.config");
            File.Create(nugetConfigFilePath).Close();

            var enabledReplacement = @"<add key='" + NuGetConstants.V3FeedName + "' value='" + NuGetConstants.V3FeedUrl + "' />";
            enabledReplacement = enabledReplacement + @"<add key='anotherName' value='" + NuGetConstants.V2FeedUrl + "' />";
            var disabledReplacement = string.Empty;
            File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement));

            Settings settings = new Settings(nugetConfigFileFolder, "nuget.config");
            PackageSourceProvider before = new PackageSourceProvider(settings);
            VerifyPackageSource(before, 2, new string[] { NuGetConstants.V3FeedName, "anotherName" },
                new string[] { NuGetConstants.V3FeedUrl, NuGetConstants.V2FeedUrl },
                new bool[] { true, true }, new bool[] { false, false });

            List<PackageSource> primary = new List<PackageSource>();
            PackageSource item = new PackageSource(NuGetConstants.V3FeedUrl, NuGetConstants.V3FeedName);
            primary.Add(item);

            List<PackageSource> secondary = new List<PackageSource>();
            PackageSource item2 = new PackageSource(NuGetConstants.V2FeedUrl, NuGetConstants.V2FeedName, false);
            secondary.Add(item2);

            PackageSourceProvider after = new PackageSourceProvider(settings, primary, secondary);

            // Assert
            //Secondary feed is present in nuget.config but with a different name
            //In this case, we don't set IsOfficial = true
            //Primary matches both name and URL so primary's IsOfficial is set to true
            //Since this is not the first time primary is getting added, we aren't aggressive in demoting secondary from enabled to disabled
            VerifyPackageSource(after, 2, new string[] { NuGetConstants.V3FeedName, "anotherName" },
                new string[] { NuGetConstants.V3FeedUrl, NuGetConstants.V2FeedUrl },
                new bool[] { true, true }, new bool[] { true, false });

            //Clean up
            TestFilesystemUtility.DeleteRandomTestFolders(nugetConfigFileFolder);
        }
Exemplo n.º 59
0
 private SourcesCommand CreateCommand(ISettings settings = null)
 {
     settings = settings ?? new MockUserSettingsManager();
     var packageSourceProvider = new PackageSourceProvider(settings);
     return new SourcesCommand(packageSourceProvider);
 }