Ejemplo n.º 1
0
        /// <summary>
        /// Sets the package to be displayed in the detail control.
        /// </summary>
        /// <param name="searchResultPackage">The package to be displayed.</param>
        /// <param name="filter">The current filter. This will used to select the default action.</param>
        public async virtual Task SetCurrentPackage(
            PackageItemListViewModel searchResultPackage,
            ItemFilter filter)
        {
            _searchResultPackage = searchResultPackage;
            _filter = filter;
            OnPropertyChanged(nameof(Id));
            OnPropertyChanged(nameof(IconUrl));

            var versions = await searchResultPackage.GetVersionsAsync();

            _allPackageVersions = versions.Select(v => v.Version).ToList();

            _projectVersionRangeDict = new Dictionary <string, VersionRange>(StringComparer.OrdinalIgnoreCase);

            // filter project.json based projects since allowedVersion is only applicable to packages.config
            var packagesConfigProjects = _nugetProjects.Where(project => !(project is INuGetIntegratedProject));

            foreach (var project in packagesConfigProjects)
            {
                // cache allowed version range for each nuget project for current selected package
                var packageReference = (await project.GetInstalledPackagesAsync(CancellationToken.None))
                                       .FirstOrDefault(r => StringComparer.OrdinalIgnoreCase.Equals(r.PackageIdentity.Id, searchResultPackage.Id));

                _projectVersionRangeDict.Add(project.GetMetadata <string>(NuGetProjectMetadataKeys.Name), packageReference?.AllowedVersions);
            }

            // hook event handler for dependency behavior changed
            Options.SelectedChanged += DependencyBehavior_SelectedChanged;

            CreateVersions();
            OnCurrentPackageChanged();
        }
		PackageSearchResultViewModel CreatePackage (string id)
		{
			var packageViewModel = new PackageItemListViewModel {
				Id = id
			};
			return new PackageSearchResultViewModel (null, packageViewModel);
		}
		public TestablePackageSearchResultViewModel (
			PackageItemListViewModel viewModel)
			: this (
				new FakeSolutionManager (),
				new FakeDotNetProject (),
				viewModel)
		{
		}
Ejemplo n.º 4
0
        public async override Task SetCurrentPackage(
            PackageItemListViewModel searchResultPackage,
            ItemFilter filter)
        {
            await base.SetCurrentPackage(searchResultPackage, filter);

            UpdateInstalledVersion();
        }
Ejemplo n.º 5
0
        public IEnumerable <PackageItemListViewModel> GetCurrent()
        {
            if (_state.ItemsCount == 0)
            {
                return(Enumerable.Empty <PackageItemListViewModel>());
            }

            var listItems = _state.Results
                            .Select((metadata, index) =>
            {
                VersionRange allowedVersions = VersionRange.All;

                // get the allowed version range and pass it to package item view model to choose the latest version based on that
                if (_packageReferences != null)
                {
                    var matchedPackageReferences = _packageReferences.Where(r => StringComparer.OrdinalIgnoreCase.Equals(r.Identity.Id, metadata.Identity.Id));
                    var allowedVersionsRange     = matchedPackageReferences.Select(r => r.AllowedVersions).Where(v => v != null).ToArray();

                    if (allowedVersionsRange.Length > 0)
                    {
                        allowedVersions = allowedVersionsRange[0];
                    }
                }

                var listItem = new PackageItemListViewModel
                {
                    Id                  = metadata.Identity.Id,
                    Version             = metadata.Identity.Version,
                    IconUrl             = metadata.IconUrl,
                    Author              = metadata.Authors,
                    DownloadCount       = metadata.DownloadCount,
                    Summary             = metadata.Summary,
                    Versions            = AsyncLazy.New(metadata.GetVersionsAsync),
                    AllowedVersions     = allowedVersions,
                    PrefixReserved      = metadata.PrefixReserved && !IsMultiSource,
                    DeprecationMetadata = AsyncLazy.New(metadata.GetDeprecationMetadataAsync),
                    Vulnerabilities     = metadata.Vulnerabilities,
                    Recommended         = index < _recommendedCount,
                    PackageReader       = (metadata as PackageSearchMetadataBuilder.ClonedPackageSearchMetadata)?.PackageReader,
                };

                listItem.UpdatePackageStatus(_installedPackages);

                if (!_context.IsSolution && _context.PackageManagerProviders.Any())
                {
                    listItem.ProvidersLoader = AsyncLazy.New(
                        async() =>
                    {
                        string uniqueProjectName = await _context.Projects[0].GetUniqueNameOrNameAsync(CancellationToken.None);
                        return(await AlternativePackageManagerProviders.CalculateAlternativePackageManagersAsync(_context.PackageManagerProviders, listItem.Id, uniqueProjectName));
                    });
                }

                return(listItem);
            });

            return(listItems.ToArray());
        }
        private async Task LoadItemsAsync(PackageItemListViewModel selectedPackageItem, CancellationToken token)
        {
            // If there is another async loading process - cancel it.
            var loadCts = CancellationTokenSource.CreateLinkedTokenSource(token);

            Interlocked.Exchange(ref _loadCts, loadCts)?.Cancel();

            await RepopulatePackageListAsync(selectedPackageItem, _loader, loadCts);
        }
		void CreateViewModel (PackageItemListViewModel package)
		{
			metadataProvider = new FakePackageMetadataProvider ();
			packageSearchMetadata = metadataProvider.AddPackageMetadata (package.Id, package.Version.ToString ());
			var solutionManager = new FakeSolutionManager ();
			var project = new FakeDotNetProject ();
			parent = new TestableAllPackagesViewModel (solutionManager, project);
			viewModel = new TestablePackageSearchResultViewModel (parent, packageItemListViewModel);
		}
Ejemplo n.º 8
0
        public async override Task SetCurrentPackage(
            PackageItemListViewModel searchResultPackage,
            ItemFilter filter)
        {
            await base.SetCurrentPackage(searchResultPackage, filter);

            InstalledVersion = searchResultPackage.InstalledVersion;
            SelectedVersion.IsCurrentInstalled = InstalledVersion == SelectedVersion.Version;
            OnPropertyChanged(nameof(SelectedVersion));
        }
		public TestablePackageSearchResultViewModel (
			FakeSolutionManager solutionManager,
			FakeDotNetProject project,
			PackageItemListViewModel viewModel)
			: this (
				new TestableAllPackagesViewModel (solutionManager, project),
				viewModel)
		{
			SolutionManager = solutionManager;
			Project = project;
		}
		PackageItemListViewModel CreatePackageItemListViewModel ()
		{
			packageVersions = new List<VersionInfo> ();
			packageItemListViewModel = new PackageItemListViewModel {
				Id = "TestPackage",
				Version = new NuGetVersion ("1.2.3"),
				Versions = AsyncLazy.New (() => {
					return Task.FromResult (packageVersions.AsEnumerable ());
				})
			};
			return packageItemListViewModel;
		}
Ejemplo n.º 11
0
        /// <summary>
        /// Keep the previously selected package after a search.
        /// Otherwise, select the first on the search if none was selected before.
        /// </summary>
        /// <param name="selectedItem">Previously selected item</param>
        internal void UpdateSelectedItem(PackageItemListViewModel selectedItem)
        {
            if (selectedItem != null)
            {
                // select the the previously selected item if it still exists.
                selectedItem = PackageItems
                               .FirstOrDefault(item => item.Id.Equals(selectedItem.Id, StringComparison.OrdinalIgnoreCase));
            }

            // select the first item if none was selected before
            _list.SelectedItem = selectedItem ?? PackageItems.FirstOrDefault();
        }
Ejemplo n.º 12
0
        public IEnumerable <PackageItemListViewModel> GetCurrent()
        {
            if (_state.ItemsCount == 0)
            {
                return(Enumerable.Empty <PackageItemListViewModel>());
            }

            var listItems = _state.Results
                            .Select(metadata =>
            {
                VersionRange allowedVersions = VersionRange.All;

                // get the allowed version range and pass it to package item view model to choose the latest version based on that
                if (_packageReferences != null)
                {
                    var matchedPackageReferences = _packageReferences.Where(r => StringComparer.OrdinalIgnoreCase.Equals(r.PackageIdentity.Id, metadata.Identity.Id));
                    var allowedVersionsRange     = matchedPackageReferences.Select(r => r.AllowedVersions).Where(v => v != null).ToArray();

                    if (allowedVersionsRange.Length > 0)
                    {
                        allowedVersions = allowedVersionsRange[0];
                    }
                }

                var listItem = new PackageItemListViewModel
                {
                    Id                  = metadata.Identity.Id,
                    Version             = metadata.Identity.Version,
                    IconUrl             = metadata.IconUrl,
                    Author              = metadata.Authors,
                    DownloadCount       = metadata.DownloadCount,
                    Summary             = metadata.Summary,
                    Versions            = AsyncLazy.New(() => metadata.GetVersionsAsync()),
                    AllowedVersions     = allowedVersions,
                    PrefixReserved      = metadata.PrefixReserved && !IsMultiSource,
                    IsPackageDeprecated = metadata.DeprecationMetadata != null,
                };
                listItem.UpdatePackageStatus(_installedPackages);

                if (!_context.IsSolution && _context.PackageManagerProviders.Any())
                {
                    listItem.ProvidersLoader = AsyncLazy.New(
                        () => AlternativePackageManagerProviders.CalculateAlternativePackageManagersAsync(
                            _context.PackageManagerProviders,
                            listItem.Id,
                            _context.Projects[0]));
                }

                return(listItem);
            });

            return(listItems.ToArray());
        }
        /// <summary>
        /// Returns the list of projects that are selected for the given action
        /// </summary>
        //public abstract IEnumerable<NuGetProject> GetSelectedProjects(UserAction action);

        /// <summary>
        /// Sets the package to be displayed in the detail control.
        /// </summary>
        /// <param name="searchResultPackage">The package to be displayed.</param>
        /// <param name="filter">The current filter. This will used to select the default action.</param>
        public async virtual Task SetCurrentPackage(
            PackageItemListViewModel searchResultPackage)            //,
        //	ItemFilter filter)
        {
            _searchResultPackage = searchResultPackage;
            //_filter = filter;
            //OnPropertyChanged(nameof(Id));
            //OnPropertyChanged(nameof(IconUrl));

            var versions = await searchResultPackage.GetVersionsAsync();

            _allPackageVersions = versions.Select(v => v.Version).ToList();

            //CreateVersions();
            //OnCurrentPackageChanged();
        }
		/// <summary>
		/// Returns the list of projects that are selected for the given action
		/// </summary>
		//public abstract IEnumerable<NuGetProject> GetSelectedProjects(UserAction action);

		/// <summary>
		/// Sets the package to be displayed in the detail control.
		/// </summary>
		/// <param name="searchResultPackage">The package to be displayed.</param>
		/// <param name="filter">The current filter. This will used to select the default action.</param>
		public async virtual Task SetCurrentPackage(
			PackageItemListViewModel searchResultPackage)//,
		//	ItemFilter filter)
		{
			_searchResultPackage = searchResultPackage;
			//_filter = filter;
			//OnPropertyChanged(nameof(Id));
			//OnPropertyChanged(nameof(IconUrl));

			var versions = await searchResultPackage.GetVersionsAsync();

			_allPackageVersions = versions.Select(v => v.Version).ToList();

			//CreateVersions();
			//OnCurrentPackageChanged();
		}
Ejemplo n.º 15
0
        public async override Task SetCurrentPackageAsync(
            PackageItemListViewModel searchResultPackage,
            ItemFilter filter,
            Func <PackageItemListViewModel> getPackageItemListViewModel)
        {
            // Set InstalledVersion before fetching versions list.
            InstalledVersion = searchResultPackage.InstalledVersion;

            await base.SetCurrentPackageAsync(searchResultPackage, filter, getPackageItemListViewModel);

            // SetCurrentPackage can take long time to return, user might changed selected package.
            // Check selected package.
            if (getPackageItemListViewModel() != searchResultPackage)
            {
                return;
            }
            InstalledVersion = searchResultPackage.InstalledVersion;
            SelectedVersion.IsCurrentInstalled = InstalledVersion == SelectedVersion.Version;
        }
Ejemplo n.º 16
0
 public ToggleableItemAutomationPeer(object item, SelectorAutomationPeer selectorAutomationPeer)
     : base(item, selectorAutomationPeer)
 {
     _owner       = item as PackageItemListViewModel;
     _ownerParent = selectorAutomationPeer.Owner as InfiniteScrollListBox;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Sets the package to be displayed in the detail control.
        /// </summary>
        /// <param name="searchResultPackage">The package to be displayed.</param>
        /// <param name="filter">The current filter. This will used to select the default action.</param>
        public async virtual Task SetCurrentPackage(
            PackageItemListViewModel searchResultPackage,
            ItemFilter filter,
            Func <PackageItemListViewModel> getPackageItemListViewModel)
        {
            _searchResultPackage = searchResultPackage;
            _filter = filter;
            OnPropertyChanged(nameof(Id));
            OnPropertyChanged(nameof(IconUrl));

            var getVersionsTask = searchResultPackage.GetVersionsAsync();

            var cacheContext = new DependencyGraphCacheContext();

            _projectVersionConstraints = new List <ProjectVersionConstraint>();

            // Filter out projects that are not managed by NuGet.
            var projects = _nugetProjects.Where(project => !(project is ProjectKNuGetProjectBase)).ToArray();

            foreach (var project in projects)
            {
                if (project is MSBuildNuGetProject)
                {
                    // cache allowed version range for each nuget project for current selected package
                    var packageReference = (await project.GetInstalledPackagesAsync(CancellationToken.None))
                                           .FirstOrDefault(r => StringComparer.OrdinalIgnoreCase.Equals(r.PackageIdentity.Id, searchResultPackage.Id));

                    var range = packageReference?.AllowedVersions;

                    if (range != null && !VersionRange.All.Equals(range))
                    {
                        var constraint = new ProjectVersionConstraint()
                        {
                            ProjectName      = project.GetMetadata <string>(NuGetProjectMetadataKeys.Name),
                            VersionRange     = range,
                            IsPackagesConfig = true,
                        };

                        _projectVersionConstraints.Add(constraint);
                    }
                }
                else if (project is BuildIntegratedNuGetProject)
                {
                    var packageReferences = await project.GetInstalledPackagesAsync(CancellationToken.None);

                    // First the lowest auto referenced version of this package.
                    var autoReferenced = packageReferences.Where(e => StringComparer.OrdinalIgnoreCase.Equals(searchResultPackage.Id, e.PackageIdentity.Id) &&
                                                                 e.PackageIdentity.Version != null)
                                         .Select(e => e as BuildIntegratedPackageReference)
                                         .Where(e => e?.Dependency?.AutoReferenced == true)
                                         .OrderBy(e => e.PackageIdentity.Version)
                                         .FirstOrDefault();

                    if (autoReferenced != null)
                    {
                        // Add constraint for auto referenced package.
                        var constraint = new ProjectVersionConstraint()
                        {
                            ProjectName  = project.GetMetadata <string>(NuGetProjectMetadataKeys.Name),
                            VersionRange = new VersionRange(
                                minVersion: autoReferenced.PackageIdentity.Version,
                                includeMinVersion: true,
                                maxVersion: autoReferenced.PackageIdentity.Version,
                                includeMaxVersion: true),

                            IsAutoReferenced = true,
                        };

                        _projectVersionConstraints.Add(constraint);
                    }
                }
            }

            // Add Current package version to package versions list.
            _allPackageVersions = new List <NuGetVersion>()
            {
                searchResultPackage.Version
            };
            CreateVersions();
            OnCurrentPackageChanged();

            var versions = await getVersionsTask;

            // GetVersionAsync can take long time to finish, user might changed selected package.
            // Check selected package.
            if (getPackageItemListViewModel() != searchResultPackage)
            {
                return;
            }

            _allPackageVersions = versions.Select(v => v.Version).ToList();

            // hook event handler for dependency behavior changed
            Options.SelectedChanged += DependencyBehavior_SelectedChanged;

            CreateVersions();
            OnCurrentPackageChanged();
        }
		public TestablePackageSearchResultViewModel (
			TestableAllPackagesViewModel parent,
			PackageItemListViewModel viewModel)
			: base (parent, viewModel)
		{
		}
Ejemplo n.º 19
0
        private void LoadItems(PackageItemListViewModel selectedPackageItem, CancellationToken token)
        {
            // If there is another async loading process - cancel it.
            var loadCts = CancellationTokenSource.CreateLinkedTokenSource(token);

            Interlocked.Exchange(ref _loadCts, loadCts)?.Cancel();

            var currentLoader = _loader;

            _joinableTaskFactory.Value.RunAsync(async() =>
            {
                await TaskScheduler.Default;

                var addedLoadingIndicator = false;

                try
                {
                    // add Loading... indicator if not present
                    if (!Items.Contains(_loadingStatusIndicator))
                    {
                        Items.Add(_loadingStatusIndicator);
                        addedLoadingIndicator = true;
                    }

                    await LoadItemsCoreAsync(currentLoader, loadCts.Token);

                    await _joinableTaskFactory.Value.SwitchToMainThreadAsync();

                    if (selectedPackageItem != null)
                    {
                        UpdateSelectedItem(selectedPackageItem);
                    }
                }
                catch (OperationCanceledException) when(!loadCts.IsCancellationRequested)
                {
                    loadCts.Cancel();
                    loadCts.Dispose();
                    currentLoader.Reset();

                    await _joinableTaskFactory.Value.SwitchToMainThreadAsync();

                    // The user cancelled the login, but treat as a load error in UI
                    // So the retry button and message is displayed
                    // Do not log to the activity log, since it is not a NuGet error
                    _logger.Log(ProjectManagement.MessageLevel.Error, Resx.Resources.Text_UserCanceled);

                    _loadingStatusIndicator.SetError(Resx.Resources.Text_UserCanceled);


                    _loadingStatusBar.SetCancelled();
                    _loadingStatusBar.Visibility = Visibility.Visible;
                }
                catch (Exception ex) when(!loadCts.IsCancellationRequested)
                {
                    loadCts.Cancel();
                    loadCts.Dispose();
                    currentLoader.Reset();

                    // Write stack to activity log
                    Mvs.ActivityLog.LogError(LogEntrySource, ex.ToString());

                    await _joinableTaskFactory.Value.SwitchToMainThreadAsync();

                    var errorMessage = ExceptionUtilities.DisplayMessage(ex);
                    _logger.Log(ProjectManagement.MessageLevel.Error, errorMessage);

                    _loadingStatusIndicator.SetError(errorMessage);

                    _loadingStatusBar.SetError();
                    _loadingStatusBar.Visibility = Visibility.Visible;
                }
                finally
                {
                    if (_loadingStatusIndicator.Status != LoadingStatus.NoItemsFound &&
                        _loadingStatusIndicator.Status != LoadingStatus.ErrorOccurred)
                    {
                        // Ideally, After a serach, it should report its status and,
                        // do not keep the LoadingStatus.Loading forever.
                        // This is a workaround.
                        var emptyListCount = addedLoadingIndicator ? 1 : 0;
                        if (Items.Count == emptyListCount)
                        {
                            _loadingStatusIndicator.Status = LoadingStatus.NoItemsFound;
                        }
                        else
                        {
                            Items.Remove(_loadingStatusIndicator);
                        }
                    }
                }

                UpdateCheckBoxStatus();

                LoadItemsCompleted?.Invoke(this, EventArgs.Empty);
            });
        }
Ejemplo n.º 20
0
        private void LoadItems(PackageItemListViewModel selectedPackageItem)
        {
            var loadCts = new CancellationTokenSource();

            // If there is another async loading process - cancel it.
            Interlocked.Exchange(ref _loadCts, loadCts)?.Cancel();

            var currentLoader = _loader;

            NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await TaskScheduler.Default;

                try
                {
                    await LoadItemsCoreAsync(currentLoader, loadCts.Token);

                    await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    if (selectedPackageItem != null)
                    {
                        UpdateSelectedItem(selectedPackageItem);
                    }
                }
                catch (OperationCanceledException) when(!loadCts.IsCancellationRequested)
                {
                    loadCts.Cancel();
                    currentLoader.Reset();

                    await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    // The user cancelled the login, but treat as a load error in UI
                    // So the retry button and message is displayed
                    // Do not log to the activity log, since it is not a NuGet error
                    _logger.Log(ProjectManagement.MessageLevel.Error, Resx.Resources.Text_UserCanceled);

                    _loadingStatusIndicator.SetError(Resx.Resources.Text_UserCanceled);

                    _loadingStatusBar.SetCancelled();
                    _loadingStatusBar.Visibility = Visibility.Visible;
                }
                catch (Exception ex) when(!loadCts.IsCancellationRequested)
                {
                    loadCts.Cancel();
                    currentLoader.Reset();

                    // Write stack to activity log
                    Mvs.ActivityLog.LogError(LogEntrySource, ex.ToString());

                    await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    var errorMessage = ExceptionUtilities.DisplayMessage(ex);
                    _logger.Log(ProjectManagement.MessageLevel.Error, errorMessage);

                    _loadingStatusIndicator.SetError(errorMessage);

                    _loadingStatusBar.SetError();
                    _loadingStatusBar.Visibility = Visibility.Visible;
                }

                UpdateCheckBoxStatus();
            });
        }