示例#1
0
        /// <summary>
        ///     Deletes all files from a package
        /// </summary>
        /// <param name="installed">Insyalled package</param>
        /// <param name="repositories">Repositories where to find the package</param>
        private static void DeleteFiles(PackageInfo installed, ICollection <string> repositories, ILogger logger)
        {
            logger.Log("Deleting installed files... ");

            var factory = new PackageRepositoryFactory();

            IPackage package;

            var globalRepo = new AggregateRepository(factory, repositories, true);

            package = globalRepo.FindPackage(installed.Name, SemanticVersion.Parse(installed.Version), true, true);

            if (package == null)
            {
                throw new InexistentPackageException(string.Format("Unable to find package {0} version {1}", installed.Name, installed.Version));
            }

            var fylesystem = new PhysicalFileSystem(installed.InstallationDirectory);

            fylesystem.DeleteFiles(package.GetFiles(), installed.InstallationDirectory);

            File.Delete(Path.Combine(installed.InstallationDirectory, installed.Name + "." + installed.Version + ".nupkg"));

            foreach (var config in Directory.GetFiles(installed.InstallationDirectory, "*.config"))
            {
                File.Delete(config);
            }

            logger.Log("Installed files deleted");
        }
示例#2
0
        internal async Task DownloadAndOpenDataServicePackage(string packageUrl, string id = null, NuGetVersion version = null)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                UIServices.Show(
                    StringResources.NoNetworkConnection,
                    MessageLevel.Warning);
                return;
            }

            if (id != null && version != null && Uri.TryCreate(packageUrl, UriKind.Absolute, out var downloadUrl))
            {
                var repository      = PackageRepositoryFactory.CreateRepository(packageUrl);
                var packageIdentity = new NuGet.Packaging.Core.PackageIdentity(id, version);

                var downloadedPackage = await PackageDownloader.Download(repository, packageIdentity);

                if (downloadedPackage != null)
                {
                    LoadPackage(downloadedPackage, packageUrl, PackageType.RemotePackage);
                }
            }
            else
            {
                UIServices.Show(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        StringResources.Dialog_InvalidPackageUrl,
                        packageUrl),
                    MessageLevel.Error
                    );
            }
        }
示例#3
0
        /// <summary>
        ///     Downloads the specified package and installs it in the configured folder
        /// </summary>
        /// <param name="info">Pacakge informations</param>
        private static void DownloadPackage(PackageInfo info, ICollection <string> repositories, ILogger logger)
        {
            logger.Log(String.Format("Downloading package for {0} version {1} ... ", info.Name, info.Version));

            var factory = new PackageRepositoryFactory();

            IPackage package;

            var globalRepo = new AggregateRepository(factory, repositories, true);

            package = globalRepo.FindPackage(info.Name, SemanticVersion.Parse(info.Version), true, true);

            if (package == null)
            {
                throw new InexistentPackageException(string.Format("Unable to find package {0} version {1}", info.Name, info.Version));
            }

            var manager = new PackageManager(
                globalRepo,
                new CustomPathResolver()
            {
                BasePath = info.InstallationDirectory
            },
                new OverWritingPhysicalFilesystem(info.InstallationDirectory));

            manager.InstallPackage(package, false, true);

            logger.Log(String.Format("Package for {0} version {1} downloaded ... ", info.Name, info.Version));
        }
示例#4
0
        public static IPackageRepository GetV2SourceRepository(Configuration.PackageSource source)
        {
            IPackageRepository     repo    = new PackageRepositoryFactory().CreateRepository(source.Source);
            LocalPackageRepository _lprepo = repo as LocalPackageRepository;

            if (_lprepo != null)
            {
                return(_lprepo);
            }
            string _userAgent = UserAgentUtil.GetUserAgent("NuGet.Client.Interop", "host");
            var    events     = repo as IHttpClientEvents;

            if (events != null)
            {
                events.SendingRequest += (sender, args) =>
                {
                    var httpReq = args.Request as HttpWebRequest;
                    if (httpReq != null)
                    {
                        httpReq.UserAgent = _userAgent;
                    }
                };
            }
            return(repo);
        }
        protected override void ExecuteTask()
        {
            string dir = SolutionDir.FullName;

            _fileSystem = new PhysicalFileSystem(dir);

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

            UpdateAllPackages(dir);
        }
        public void CreateRepositoryReturnsLocalRepositoryIfSourceIsPhysicalPath(string path)
        {
            // Arrange
            var factory = new PackageRepositoryFactory();

            // Act
            var repository = factory.CreateRepository(path);

            // Assert
            Assert.IsType <LazyLocalPackageRepository>(repository);
        }
示例#7
0
        /// <summary>
        ///     Searches all available versions of a package in a list of repostiories
        /// </summary>
        /// <param name="repositories">Repositories to search</param>
        /// <param name="packageName">Pacakge identifier</param>
        /// <returns>List of available versions</returns>
        public static ICollection <string> Search(ICollection <string> repositories, string packageName)
        {
            var factory    = new PackageRepositoryFactory();
            var globalRepo = new AggregateRepository(factory, repositories.Distinct(), true);
            var packages   = globalRepo.FindPackagesById(packageName);

            return(packages.Select(x => x.Version)
                   .OrderByDescending(x => x)
                   .Select(x => x.ToString())
                   .ToList()
                   .Distinct().ToList());
        }
示例#8
0
        /// <summary>
        ///     Deletes a package from a repository
        /// </summary>
        /// <param name="package">Pacakge to delte</param>
        /// <param name="version">Version to delete</param>
        /// <param name="gallery">Origin gallery</param>
        public static void Delete(string package, string version, string gallery)
        {
            var factory    = new PackageRepositoryFactory();
            var globalRepo = new AggregateRepository(factory, new List <string>()
            {
                gallery
            }, true);

            var p = globalRepo.FindPackage(package, new SemanticVersion(version));

            globalRepo.RemovePackage(p);
        }
示例#9
0
        private static IEnumerable <string> FindPackage(string package, bool isreleaseversion = true)
        {
            //Get the list of all NuGet packages with ID 'SFA.DAS.Providers.Api.Client'
            var repo     = new PackageRepositoryFactory().CreateRepository("https://packages.nuget.org/api/v2");
            var packages = repo.FindPackagesById(package).ToList();

            //Filter the list of packages that are not Release (Stable) versions
            packages = packages.Where(x => x.IsReleaseVersion() == isreleaseversion && x.IsListed() == true).OrderByDescending(y => y.Version).ToList();

            //Iterate through the list and print the full name of the pre-release packages to console
            return(packages.Where(p => p.Version.ToFullString() != "0.9.161").Select(q => q.Version.ToFullString()));
        }
        public void CreateRepositoryReturnsLocalRepositoryIfSourceIsPhysicalPath()
        {
            // Arrange
            var paths = new[] { @"C:\packages\", 
                                 @"\\folder\sub-folder",
                                 "file://some-folder/some-dir"};
            var factory = new PackageRepositoryFactory();

            // Act and Assert
            Assert.True(paths.Select(factory.CreateRepository)
                               .All(p => p is LocalPackageRepository));
        }
        public void CreateRepositoryReturnsLocalRepositoryIfSourceIsPhysicalPath()
        {
            // Arrange
            var paths = new[] { @"C:\packages\",
                                @"\\folder\sub-folder",
                                "file://some-folder/some-dir" };
            var factory = new PackageRepositoryFactory();

            // Act and Assert
            Assert.True(paths.Select(factory.CreateRepository)
                        .All(p => p is LocalPackageRepository));
        }
示例#12
0
        private async Task Initialize()
        {
            var listEndpoints = await GetListEndpointsAsync(_sourceProvider).ConfigureAwait(false);

            var repositoryFactory = new PackageRepositoryFactory();

            var repositories = listEndpoints
                               .Select(s => repositoryFactory.CreateRepository(s))
                               .ToList();

            _repository = new AggregateRepository(repositories);
        }
        public void CreateRepositoryReturnsDataServicePackageRepositoryIfSourceIsWebUrl()
        {
            // Arrange
            var httpClient = new Mock<IHttpClient>();
            httpClient.SetupAllProperties();
            var factory = new PackageRepositoryFactory();

            // Act
            IPackageRepository repository = factory.CreateRepository("http://example.com/");

            // Act and Assert
            Assert.IsType(typeof(DataServicePackageRepository), repository);
        }
        void AddNuGetPackageReference(IDotNetProject project, string packageId)
        {
            var packageRepoFactory = new PackageRepositoryFactory();
            var packageRepo        = packageRepoFactory.CreateRepository("http://www.nuget.org/api/v2/");
            var packageManagementProjectFactory = new PackageManagementProjectFactory(PackageManagementServices.PackageManagementEvents);
            var packageManagementProject        = packageManagementProjectFactory.CreateProject(packageRepo, project);
            var package = packageRepo.FindPackagesById(packageId).FirstOrDefault(x => x.IsLatestVersion);
            var packageManagerFactory = new SharpDevelopPackageManagerFactory();
            var packageManager        = packageManagerFactory.CreatePackageManager(packageRepo, project);

            packageManager.InstallPackage(package, false, false);
            packageManagementProject.AddPackageReference(package);
        }
示例#15
0
        public static Stream DownloadDacpac(string packageName, string version, string repository)
        {
            var factory = new PackageRepositoryFactory();

            IPackage package;

            var globalRepo = new AggregateRepository(factory, new string[] { repository }, true);

            package = globalRepo.FindPackage(packageName, SemanticVersion.Parse(version), true, true);

            var files = package.GetFiles();

            return(files.Single(x => x.Path.EndsWith(".dacpac")).GetStream());
        }
        public void CreateRepositoryReturnsDataServicePackageRepositoryIfSourceIsWebUrl()
        {
            // Arrange
            var httpClient = new Mock<IHttpClient>();
            httpClient.SetupAllProperties();
            httpClient.Setup(c => c.GetRedirectedUri(It.IsAny<Uri>())).Returns(new Uri("http://example.com"));
            var factory = new PackageRepositoryFactory(httpClient.Object);

            // Act
            IPackageRepository repository = factory.CreateRepository(new PackageSource("http://example.com/", "Test Source"));

            // Act and Assert
            Assert.IsInstanceOfType(repository, typeof(DataServicePackageRepository));
        }
        public void CreateRepositoryReturnsDataServicePackageRepositoryIfSourceIsWebUrl()
        {
            // Arrange
            var httpClient = new Mock <IHttpClient>();

            httpClient.SetupAllProperties();
            var factory = new PackageRepositoryFactory();

            // Act
            IPackageRepository repository = factory.CreateRepository("http://example.com/");

            // Act and Assert
            Assert.IsType(typeof(DataServicePackageRepository), repository);
        }
示例#18
0
        public void CreateRepositoryReturnsDataServicePackageRepositoryIfSourceIsWebUrl()
        {
            // Arrange
            var httpClient = new Mock <IHttpClient>();

            httpClient.SetupAllProperties();
            httpClient.Setup(c => c.GetRedirectedUri(It.IsAny <Uri>())).Returns(new Uri("http://example.com"));
            var factory = new PackageRepositoryFactory(httpClient.Object);

            // Act
            IPackageRepository repository = factory.CreateRepository(new PackageSource("http://example.com/", "Test Source"));

            // Act and Assert
            Assert.IsInstanceOfType(repository, typeof(DataServicePackageRepository));
        }
示例#19
0
        void AddNuGetPackageReference(DotNetProject project, string packageId)
        {
            var packageRepoFactory = new PackageRepositoryFactory();
            var packageRepo        = packageRepoFactory.CreateRepository("http://www.nuget.org/api/v2/");
            var package            = packageRepo.FindPackagesById(packageId).FirstOrDefault(x => x.IsLatestVersion);

            PackageManagementServices.
            ProjectOperations.
            InstallPackages("http://www.nuget.org/api/v2/",
                            project,
                            new List <PackageManagementPackageReference>()
            {
                new PackageManagementPackageReference(package.Id, package.Version.Version.ToString())
            });
        }
示例#20
0
        public int Count(string url, NetworkCredential credential)
        {
            var uri = new Uri(url);

            TestCredentialProvider.Instance.Credentials.Add(uri, credential);
            try
            {
                var repository = new PackageRepositoryFactory().CreateRepository(url);
                return(repository.GetPackages().Count());
            }
            finally
            {
                TestCredentialProvider.Instance.Credentials.Remove(uri);
            }
        }
示例#21
0
        public NugetStore(string rootDirectory, string configFile = DefaultConfig)
        {
            if (rootDirectory == null)
            {
                throw new ArgumentNullException("rootDirectory");
            }
            if (configFile == null)
            {
                throw new ArgumentNullException("configFile");
            }

            var configFilePath = Path.Combine(rootDirectory, configFile);

            if (!File.Exists(configFilePath))
            {
                throw new ArgumentException(String.Format("Invalid installation. Configuration file [{0}] not found", configFile), "configFile");
            }

            rootFileSystem = new PhysicalFileSystem(rootDirectory);
            settings       = NuGet.Settings.LoadDefaultSettings(rootFileSystem, configFile, null);

            string installPath = settings.GetRepositoryPath();

            packagesFileSystem    = new PhysicalFileSystem(installPath);
            packageSourceProvider = new PackageSourceProvider(settings);

            repositoryFactory   = new PackageRepositoryFactory();
            aggregateRepository = packageSourceProvider.CreateAggregateRepository(repositoryFactory, true);

            pathResolver = new DefaultPackagePathResolver(packagesFileSystem);

            manager = new PackageManager(aggregateRepository, pathResolver, packagesFileSystem);

            MainPackageId = Settings.GetConfigValue(MainPackageKey);
            if (string.IsNullOrWhiteSpace(MainPackageId))
            {
                throw new InvalidOperationException(string.Format("Invalid configuration. Expecting [{0}] in config", MainPackageKey));
            }

            RepositoryPath = Settings.GetConfigValue(RepositoryPathKey);
            if (string.IsNullOrWhiteSpace(RepositoryPath))
            {
                RepositoryPath = DefaultGamePackagesDirectory;
            }

            // Setup NugetCachePath in the cache folder
            Environment.SetEnvironmentVariable("NuGetCachePath", Path.Combine(rootDirectory, "Cache", RepositoryPath));
        }
示例#22
0
 public static IPackageRepository GetV2SourceRepository(PackageSource source, string host)
 {           
     IPackageRepository repo = new PackageRepositoryFactory().CreateRepository(source.Url);
     LocalPackageRepository _lprepo = repo as LocalPackageRepository;
     if (_lprepo != null)
         return _lprepo;
     string _userAgent = UserAgentUtil.GetUserAgent("NuGet.Client.Interop", host);
     var events = repo as IHttpClientEvents;
     if (events != null)
     {
         events.SendingRequest += (sender, args) =>
         {
             var httpReq = args.Request as HttpWebRequest;
             if (httpReq != null)
             {
                 httpReq.UserAgent = _userAgent;
             }
         };               
     }
     return repo;
 }
示例#23
0
        public AddInRepository(params AddInSource[] sources)
        {
            List <PackageSource> packageSources = new List <PackageSource>();

            foreach (AddInSource source in sources)
            {
                PackageSource packageSource = new PackageSource(source.Source,
                                                                source.Name,
                                                                isEnabled: true,
                                                                isOfficial: source.IsOfficial);

                packageSources.Add(packageSource);
            }

            PackageSourceProvider     packageSourceProvider    = new PackageSourceProvider(new NullSettings(), packageSources);
            IPackageRepositoryFactory packageRepositoryFactory = new PackageRepositoryFactory();

            // TODO probably turn this off and report proper errors
            this._repository = packageSourceProvider.GetAggregate(packageRepositoryFactory,
                                                                  ignoreFailingRepositories: true);
        }
示例#24
0
        protected override void ExecuteTask()
        {
            if (ProjectFile == null && ProjectDir == null)
            {
                throw new ValidationException("Either project or project-dir must be set on <nuget-get-dependencies />.");
            }

            string dir = SolutionDir.FullName;

            _fileSystem = new PhysicalFileSystem(dir);

            string projectDir = ProjectFile == null ? ProjectDir.FullName : ProjectFile.Directory.FullName;

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

            var packagesConfigFiles = Directory.GetFiles(projectDir, Constants.PackageReferenceFile, SearchOption.AllDirectories);
            var project             = packagesConfigFiles.Select(GetProject)
                                      .Where(p => p.Project != null)
                                      .SingleOrDefault();

            if (project == null)
            {
                throw new BuildException("No project found", Location);
            }

            string             repositoryPath   = GetRepositoryPathFromSolution(dir);
            IPackageRepository sourceRepository = AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, Source);

            var references = GetReferences(project.PackagesConfigPath, project.Project, repositoryPath, sourceRepository);
            var deps       = new NuGetDependencies
            {
                Dependencies = references.Select(GetDependency).ToArray()
            };

            Project.DataTypeReferences.Add(ReferenceId, deps);
            Log(Level.Info, "Found {0} dependencies", deps.Dependencies.Length);
        }
示例#25
0
 public static IPackageRepository GetV2SourceRepository(Configuration.PackageSource source)
 {
     var repo = new PackageRepositoryFactory().CreateRepository(source.Source);
     var _lprepo = repo as LocalPackageRepository;
     if (_lprepo != null)
     {
         return _lprepo;
     }
     var _userAgent = UserAgentUtil.GetUserAgent("NuGet.Client.Interop", "host");
     var events = repo as IHttpClientEvents;
     if (events != null)
     {
         events.SendingRequest += (sender, args) =>
             {
                 var httpReq = args.Request as HttpWebRequest;
                 if (httpReq != null)
                 {
                     httpReq.UserAgent = _userAgent;
                 }
             };
     }
     return repo;
 }
示例#26
0
        public NugetStore(string rootDirectory, string configFile = DefaultConfig, string overrideFile = OverrideConfig)
        {
            if (rootDirectory == null)
            {
                throw new ArgumentNullException(nameof(rootDirectory));
            }
            if (configFile == null)
            {
                throw new ArgumentNullException(nameof(configFile));
            }
            if (overrideFile == null)
            {
                throw new ArgumentNullException(nameof(overrideFile));
            }

            // First try the override file with custom settings
            var configFileName = overrideFile;
            var configFilePath = Path.Combine(rootDirectory, configFileName);

            if (!File.Exists(configFilePath))
            {
                // Override file does not exist, fallback to default config file
                configFileName = configFile;
                configFilePath = Path.Combine(rootDirectory, configFileName);

                if (!File.Exists(configFilePath))
                {
                    throw new ArgumentException($"Invalid installation. Configuration file [{configFile}] not found", nameof(configFile));
                }
            }

            rootFileSystem = new PhysicalFileSystem(rootDirectory);
            Settings       = NuGet.Settings.LoadDefaultSettings(rootFileSystem, configFileName, null);

            string installPath = Settings.GetRepositoryPath();

            packagesFileSystem    = new PhysicalFileSystem(installPath);
            packageSourceProvider = new PackageSourceProvider(Settings);

            repositoryFactory = new PackageRepositoryFactory();
            SourceRepository  = packageSourceProvider.CreateAggregateRepository(repositoryFactory, true);

            pathResolver = new DefaultPackagePathResolver(packagesFileSystem);

            Manager = new PackageManager(SourceRepository, pathResolver, packagesFileSystem);

            var mainPackageList = Settings.GetConfigValue(MainPackagesKey);

            if (string.IsNullOrWhiteSpace(mainPackageList))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{MainPackagesKey}] in config");
            }
            MainPackageIds = mainPackageList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            VSIXPluginId = Settings.GetConfigValue(VsixPluginKey);
            if (string.IsNullOrWhiteSpace(VSIXPluginId))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{VsixPluginKey}] in config");
            }

            RepositoryPath = Settings.GetConfigValue(RepositoryPathKey);
            if (string.IsNullOrWhiteSpace(RepositoryPath))
            {
                RepositoryPath = DefaultGamePackagesDirectory;
            }

            // Setup NugetCachePath in the cache folder
            Environment.SetEnvironmentVariable("NuGetCachePath", Path.Combine(rootDirectory, "Cache", RepositoryPath));
        }
示例#27
0
        private Task <string?> DownloadWithProgress(SourceRepository sourceRepository, PackageIdentity packageIdentity)
        {
            var progressDialogText = Resources.Dialog_DownloadingPackage;

            if (packageIdentity.HasVersion)
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, packageIdentity.Version);
            }
            else
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, string.Empty);
            }

            string?description = null;
            int?   percent     = null;
            var    updated     = 0;

            var progressDialogLock = new object();

#pragma warning disable CA2000 // Dispose objects before losing scope (handled in finally below)
            var progressDialog = new ProgressDialog
            {
                Text              = progressDialogText,
                WindowTitle       = Resources.Dialog_Title,
                ShowTimeRemaining = true,
                CancellationText  = "Canceling download..."
            };

            // polling for Cancel button being clicked
            var cts   = new CancellationTokenSource();
            var timer = new System.Timers.Timer(100);
#pragma warning restore CA2000 // Dispose objects before losing scope

            timer.Elapsed += (o, e) =>
            {
                lock (progressDialogLock)
                {
                    if (progressDialog.CancellationPending)
                    {
                        timer.Stop();
                        cts.Cancel();
                    }
                    else if (Interlocked.CompareExchange(ref updated, 0, 1) == 1)
                    {
                        progressDialog.ReportProgress(percent.GetValueOrDefault(), null, description);
                    }
                }
            };


            var tcs = new TaskCompletionSource <string?>();
            progressDialog.DoWork += (object?sender, DoWorkEventArgs args) =>
            {
                var t = DoWorkAsync();
                t.Wait(cts.Token);
                tcs.TrySetResult(t.Result);
            };
            progressDialog.RunWorkerCompleted += (object?sender, RunWorkerCompletedEventArgs args) =>
            {
                MainWindow.Value.Activate();
            };

            progressDialog.ShowDialog(MainWindow.Value);
            timer.Start();

            async Task <string?> DoWorkAsync()
            {
                try
                {
                    var httpProgressProvider = new ProgressHttpHandlerResourceV3Provider(OnProgress);
                    var repository           = PackageRepositoryFactory.CreateRepository(sourceRepository.PackageSource, new[] { new Lazy <INuGetResourceProvider>(() => httpProgressProvider) });
                    var downloadResource     = await repository.GetResourceAsync <DownloadResource>(cts !.Token).ConfigureAwait(false);

                    using var sourceCacheContext = new SourceCacheContext()
                          {
                              NoCache = true
                          };
                    var context = new PackageDownloadContext(sourceCacheContext, Path.GetTempPath(), true);

                    using var result = await downloadResource.GetDownloadResourceResultAsync(packageIdentity, context, string.Empty, NullLogger.Instance, cts.Token).ConfigureAwait(false);

                    if (result.Status == DownloadResourceResultStatus.Cancelled)
                    {
                        throw new OperationCanceledException();
                    }

                    if (result.Status == DownloadResourceResultStatus.NotFound)
                    {
                        throw new Exception($"Package '{packageIdentity.Id} {packageIdentity.Version}' not found");
                    }

                    var tempFilePath = Path.GetTempFileName();
                    using (var fileStream = File.OpenWrite(tempFilePath))
                    {
                        await result.PackageStream.CopyToAsync(fileStream).ConfigureAwait(false);
                    }

                    return(tempFilePath);
                }
                catch (OperationCanceledException)
                {
                    return(null);
                }
                catch (Exception exception)
                {
                    OnError(exception);
                    return(null);
                }
                finally
                {
                    timer !.Stop();
                    timer.Dispose();
                    cts !.Dispose();
                    // close progress dialog when done
                    lock (progressDialogLock !)
                    {
                        progressDialog !.Dispose();
                    }
                }
            }

            void OnProgress(long bytesReceived, long?totalBytes)
            {
                if (totalBytes.HasValue)
                {
                    // TODO: remove ! once https://github.com/dotnet/roslyn/issues/33330 is fixed
                    percent     = (int)((bytesReceived * 100L) / totalBytes) !;
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0} of {1}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture),
                        FileSizeConverter.Convert(totalBytes.Value, typeof(string), null, CultureInfo.CurrentCulture));
                }
                else
                {
                    percent     = null;
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture));
                }
                Interlocked.Exchange(ref updated, 1);
            }

            return(tcs.Task);
        }
        private async Task <string> DownloadWithProgress(SourceRepository sourceRepository, PackageIdentity packageIdentity)
        {
            var progressDialogText = Resources.Dialog_DownloadingPackage;

            if (packageIdentity.HasVersion)
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, packageIdentity.Version);
            }
            else
            {
                progressDialogText = string.Format(CultureInfo.CurrentCulture, progressDialogText, packageIdentity.Id, string.Empty);
            }

            string description = null;
            int?   percent     = null;
            var    updated     = false;

            var progressDialogLock = new object();
            var progressDialog     = new ProgressDialog
            {
                Text              = progressDialogText,
                WindowTitle       = Resources.Dialog_Title,
                ShowTimeRemaining = true,
                CancellationText  = "Canceling download..."
            };

            // polling for Cancel button being clicked
            var cts   = new CancellationTokenSource();
            var timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(200)
            };

            timer.Tick += (o, e) =>
            {
                lock (progressDialogLock)
                {
                    if (progressDialog.CancellationPending)
                    {
                        timer.Stop();
                        cts.Cancel();
                    }
                    else if (updated)
                    {
                        if (!progressDialog.IsOpen)
                        {
                            progressDialog.ProgressBarStyle = percent.HasValue ? ProgressBarStyle.ProgressBar : ProgressBarStyle.MarqueeProgressBar;
                            progressDialog.ShowDialog(MainWindow.Value);
                        }
                        progressDialog.ReportProgress(percent.GetValueOrDefault(), null, description);
                        updated = false;
                    }
                }
            };
            timer.Start();

            try
            {
                var httpProgressProvider = new ProgressHttpHandlerResourceV3Provider(OnProgress);
                var additionalProviders  = new[] { new Lazy <INuGetResourceProvider>(() => httpProgressProvider) };

                var repository       = PackageRepositoryFactory.CreateRepository(sourceRepository.PackageSource, additionalProviders);
                var downloadResource = await repository.GetResourceAsync <DownloadResource>(cts.Token);

                using (var sourceCacheContext = new SourceCacheContext()
                {
                    NoCache = true
                })
                {
                    var context = new PackageDownloadContext(sourceCacheContext, Path.GetTempPath(), true);

                    using (var result = await downloadResource.GetDownloadResourceResultAsync(packageIdentity, context, string.Empty, NullLogger.Instance, cts.Token))
                    {
                        if (result.Status == DownloadResourceResultStatus.Cancelled)
                        {
                            throw new OperationCanceledException();
                        }
                        if (result.Status == DownloadResourceResultStatus.NotFound)
                        {
                            throw new Exception(string.Format("Package '{0} {1}' not found", packageIdentity.Id, packageIdentity.Version));
                        }

                        var tempFilePath = Path.GetTempFileName();

                        using (var fileStream = File.OpenWrite(tempFilePath))
                        {
                            await result.PackageStream.CopyToAsync(fileStream);
                        }

                        return(tempFilePath);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                return(null);
            }
            catch (Exception exception)
            {
                OnError(exception);
                return(null);
            }
            finally
            {
                timer.Stop();

                // close progress dialog when done
                lock (progressDialogLock)
                {
                    progressDialog.Close();
                    progressDialog = null;
                }

                MainWindow.Value.Activate();
            }

            void OnProgress(long bytesReceived, long?totalBytes)
            {
                if (totalBytes.HasValue)
                {
                    percent     = (int)((bytesReceived * 100L) / totalBytes);
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0} of {1}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture),
                        FileSizeConverter.Convert(totalBytes.Value, typeof(string), null, CultureInfo.CurrentCulture));
                }
                else
                {
                    percent     = null;
                    description = string.Format(
                        CultureInfo.CurrentCulture,
                        "Downloaded {0}...",
                        FileSizeConverter.Convert(bytesReceived, typeof(string), null, CultureInfo.CurrentCulture));
                }
                updated = true;
            }
        }
        protected override void ExecuteTask()
        {
            string dir            = SolutionDir.FullName;
            string repositoryPath = GetRepositoryPathFromSolution(dir);

            _fileSystem       = new PhysicalFileSystem(dir);
            RepositoryFactory = new PackageRepositoryFactory();
            SourceProvider    = new PackageSourceProvider(new Settings(_fileSystem));
            var repo = RepositoryFactory.CreateRepository(repositoryPath);

            Log(Level.Debug, "Repo: {0}, Count: {1}", repo.Source, repo.GetPackages().Count());

            var           fw = VersionUtility.ParseFrameworkName(Framework);
            List <string> files = new List <string>(), references = new List <string>();

            foreach (var deps in Dependencies)
            {
                foreach (var dep in deps.Dependencies)
                {
                    var package = repo.FindPackage(dep.Id, dep.VersionSpec, !String.IsNullOrWhiteSpace(dep.VersionSpec.MinVersion.SpecialVersion), false);
                    if (package == null)
                    {
                        package = repo.FindPackage(dep.Id, dep.VersionSpec, true, false);
                    }
                    if (package == null)
                    {
                        package = repo.FindPackage(dep.Id, dep.VersionSpec, true, true);
                    }
                    if (package == null)
                    {
                        throw new BuildException(String.Format("Can't find package {0} with min version {1}", dep.Id, dep.MinVersion), Location);
                    }

                    string pkgPath = Path.Combine(repositoryPath, package.Id + "." + package.Version);

                    var package_files = package.GetLibFiles().ToList();
                    IEnumerable <IPackageFile> compatible_files;
                    Log(Level.Debug, "Found package {0} with {1} file(s) - {2}", package.Id, package_files.Count, package.GetType());
                    if (!VersionUtility.TryGetCompatibleItems(fw, package_files, out compatible_files))
                    {
                        throw new BuildException("Couldn't get compatible files.");
                    }

                    foreach (var f in compatible_files)
                    {
                        var extension = Path.GetExtension(f.Path);

                        var path = Path.Combine(pkgPath, f.Path);
                        Log(Level.Debug, "  - Found compatible file {1} ({0}) - {2}", f.Path, f.EffectivePath, path);
                        if (extension == ".dll" || extension == ".exe")
                        {
                            references.Add(path);
                        }
                        files.Add(path);
                    }
                }
            }

            if (FilesId != null)
            {
                PatternSet ps = new PatternSet();
                ps.Include.AddRange(files.Select(MakePattern).ToArray());
                Project.DataTypeReferences.Add(FilesId, ps);
            }
            if (ReferencesId != null)
            {
                PatternSet ps = new PatternSet();
                ps.Include.AddRange(references.Select(MakePattern).ToArray());
                Project.DataTypeReferences.Add(ReferencesId, ps);
            }

            Log(Level.Info, "Found {0} file(s) and {1} reference(s)", files.Count, references.Count);
        }