-
Notifications
You must be signed in to change notification settings - Fork 748
Expand file tree
/
Copy pathPackageItemViewModel.cs
More file actions
920 lines (803 loc) · 33.1 KB
/
PackageItemViewModel.cs
File metadata and controls
920 lines (803 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Cache;
using System.Runtime.Caching;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Microsoft;
using Microsoft.VisualStudio.Threading;
using NuGet.PackageManagement.UI.ViewModels;
using NuGet.PackageManagement.VisualStudio;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Internal.Contracts;
using NuGet.VisualStudio.Telemetry;
using Resx = NuGet.PackageManagement.UI.Resources;
namespace NuGet.PackageManagement.UI
{
// This is the model class behind the package items in the infinite scroll list.
// Some of its properties, such as Latest Version, Status, are fetched on-demand in the background.
public sealed class PackageItemViewModel : INotifyPropertyChanged, ISelectableItem, IDisposable
{
internal const int DecodePixelWidth = 32;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly IPackageVulnerabilityService _vulnerabilityService;
public PackageItemViewModel(INuGetSearchService searchService, IPackageVulnerabilityService vulnerabilityService = default)
{
_cancellationTokenSource = new CancellationTokenSource();
_searchService = searchService;
_vulnerabilityService = vulnerabilityService;
}
// same URIs can reuse the bitmapImage that we've already used.
private static readonly ObjectCache BitmapImageCache = MemoryCache.Default;
private static readonly RequestCachePolicy RequestCacheIfAvailable = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable);
private static readonly ErrorFloodGate ErrorFloodGate = new ErrorFloodGate();
private INuGetSearchService _searchService;
public event PropertyChangedEventHandler PropertyChanged;
public string Id { get; set; }
public NuGetVersion Version { get; set; }
public VersionRange AllowedVersions { get; set; }
public VersionRange VersionOverride { get; set; }
public IReadOnlyCollection<PackageSourceContextInfo> Sources { get; set; }
public bool IncludePrerelease { get; set; }
public ImmutableList<KnownOwnerViewModel> KnownOwnerViewModels { get; internal set; }
public string Owner { get; internal set; }
private string _author;
public string Author
{
get
{
return _author;
}
set
{
_author = value;
OnPropertyChanged(nameof(Author));
OnPropertyChanged(nameof(ByAuthor));
}
}
/// <summary>
/// When a collection of <see cref="KnownOwnerViewModels"/> is available, this property returns the <see cref="PackageSearchMetadataContextInfo.Owners"/>
/// string which contains the package owner name(s).
/// If the collection exists but is empty, it's treated as there being no assigned owner for this package by returning an empty string.
/// Otherwise, when there's no collection or no Owners string, it returns null.
/// </summary>
private string ByOwner
{
get
{
// Owners is only used when we have Known Owners.
if (KnownOwnerViewModels == null)
{
return null;
}
// Empty Known Owners is treated as there being no assigned owner for this package.
if (KnownOwnerViewModels.IsEmpty)
{
return string.Empty;
}
// Having Known Owners but with an empty Owners string is treated as there being no assigned owner for this package.
if (string.IsNullOrWhiteSpace(Owner))
{
return string.Empty;
}
return string.Format(CultureInfo.CurrentCulture, Resx.Text_ByOwner, Owner);
}
}
public string ByAuthor
{
get
{
return !string.IsNullOrWhiteSpace(_author) ? string.Format(CultureInfo.CurrentCulture, Resx.Text_ByAuthor, _author) : null;
}
}
/// <summary>
/// Fallback to <see cref="ByAuthor"/> only when <see cref="ByOwner"> is null.
/// </summary>
public string ByOwnerOrAuthor
{
get
{
return ByOwner ?? ByAuthor;
}
}
/// <summary>
/// The installed version of the package.
/// </summary>
private NuGetVersion _installedVersion;
public NuGetVersion InstalledVersion
{
get
{
return _installedVersion;
}
set
{
if (!VersionEquals(_installedVersion, value))
{
_installedVersion = value;
OnPropertyChanged(nameof(InstalledVersion));
OnPropertyChanged(nameof(IsInstalledAndTransitive));
OnPropertyChanged(nameof(IsLatestInstalled));
// update tool tip
if (_installedVersion != null)
{
var displayVersion = new DisplayVersion(_installedVersion, string.Empty);
InstalledVersionToolTip = string.Format(
CultureInfo.CurrentCulture,
Resources.ToolTip_InstalledVersion,
displayVersion);
}
else
{
InstalledVersionToolTip = null;
}
}
}
}
/// <summary>
/// The version that can be installed or updated to. It is null
/// if the installed version is already the latest.
/// </summary>
private NuGetVersion _latestVersion;
public NuGetVersion LatestVersion
{
get
{
return _latestVersion;
}
set
{
if (!VersionEquals(_latestVersion, value))
{
_latestVersion = value;
OnPropertyChanged(nameof(IsNotInstalled));
OnPropertyChanged(nameof(IsUpdateAvailable));
OnPropertyChanged(nameof(LatestVersion));
OnPropertyChanged(nameof(IsUninstalledOrTransitive));
// update tool tip
if (_latestVersion != null)
{
var displayVersion = new DisplayVersion(_latestVersion, string.Empty);
string toolTipText = PackageLevel == PackageLevel.Transitive ? Resources.ToolTip_TransitiveDependencyVersion : Resources.ToolTip_LatestVersion;
LatestVersionToolTip = string.Format(
CultureInfo.CurrentCulture,
toolTipText,
displayVersion);
}
else
{
LatestVersionToolTip = null;
}
}
}
}
/// <summary>
/// True if the package is AutoReferenced
/// </summary>
private bool _autoReferenced;
public bool AutoReferenced
{
get
{
return _autoReferenced;
}
set
{
_autoReferenced = value;
OnPropertyChanged(nameof(AutoReferenced));
}
}
private string _installedVersionToolTip;
public string InstalledVersionToolTip
{
get
{
return _installedVersionToolTip;
}
set
{
_installedVersionToolTip = value;
OnPropertyChanged(nameof(InstalledVersionToolTip));
}
}
private string _latestVersionToolTip;
public string LatestVersionToolTip
{
get
{
return _latestVersionToolTip;
}
set
{
_latestVersionToolTip = value;
OnPropertyChanged(nameof(LatestVersionToolTip));
}
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
_isSelected = value;
OnPropertyChanged(nameof(IsSelected));
}
}
}
private bool VersionEquals(NuGetVersion v1, NuGetVersion v2)
{
if (v1 == null && v2 == null)
{
return true;
}
if (v1 == null)
{
return false;
}
return v1.Equals(v2, VersionComparison.Default);
}
private long? _downloadCount;
public long? DownloadCount
{
get
{
return _downloadCount;
}
set
{
_downloadCount = value;
OnPropertyChanged(nameof(DownloadCount));
}
}
public string Summary { get; set; }
private PackageStatus _status;
public PackageStatus Status
{
get
{
return _status;
}
private set
{
bool refresh = _status != value;
_status = value;
if (refresh)
{
OnPropertyChanged(nameof(Status));
OnPropertyChanged(nameof(IsLatestInstalled));
OnPropertyChanged(nameof(IsUpdateAvailable));
OnPropertyChanged(nameof(IsUninstallable));
OnPropertyChanged(nameof(IsNotInstalled));
OnPropertyChanged(nameof(IsUninstalledOrTransitive));
}
}
}
// If the values that help calculate this property change, make sure you raise OnPropertyChanged for IsNotInstalled
// in all those properties.
public bool IsNotInstalled
{
get
{
return (Status == PackageStatus.NotInstalled && LatestVersion != null);
}
}
public bool IsUninstalledOrTransitive => (Status == PackageStatus.NotInstalled && LatestVersion != null) || PackageLevel == PackageLevel.Transitive;
public bool IsInstalledAndTransitive => PackageLevel == PackageLevel.Transitive || InstalledVersion != null;
// If the values that help calculate this property change, make sure you raise OnPropertyChanged for IsUninstallable
// in all those properties.
public bool IsUninstallable
{
get
{
return (Status == PackageStatus.Installed || Status == PackageStatus.UpdateAvailable);
}
}
// If the values that help calculate this property change, make sure you raise OnPropertyChanged for IsLatestInstalled
// in all those properties.
public bool IsLatestInstalled
{
get
{
return (Status == PackageStatus.Installed && InstalledVersion != null);
}
}
// If the values that help calculate this property change, make sure you raise OnPropertyChanged for IsUpdateAvailable
// in all those properties.
public bool IsUpdateAvailable
{
get
{
return (Status == PackageStatus.UpdateAvailable && LatestVersion != null);
}
}
private bool _recommended;
public bool Recommended
{
get { return _recommended; }
set
{
if (_recommended != value)
{
_recommended = value;
OnPropertyChanged(nameof(Recommended));
}
}
}
private (string modelVersion, string vsixVersion)? _recommenderVersion;
public (string modelVersion, string vsixVersion)? RecommenderVersion
{
get { return _recommenderVersion; }
set
{
_recommenderVersion = value;
OnPropertyChanged(nameof(RecommenderVersion));
}
}
private bool _prefixReserved;
public bool PrefixReserved
{
get { return _prefixReserved; }
set
{
if (_prefixReserved != value)
{
_prefixReserved = value;
OnPropertyChanged(nameof(PrefixReserved));
}
}
}
private bool _isPackageDeprecated;
public bool IsPackageDeprecated
{
get { return _isPackageDeprecated; }
set
{
if (_isPackageDeprecated != value)
{
_isPackageDeprecated = value;
OnPropertyChanged(nameof(IsPackageDeprecated));
OnPropertyChanged(nameof(IsPackageWithWarnings));
}
}
}
public bool IsPackageVulnerable
{
get => VulnerabilityMaxSeverity > -1;
}
private int _vulnerabilityMaxSeverity = -1;
public int VulnerabilityMaxSeverity
{
get { return _vulnerabilityMaxSeverity; }
set
{
if (_vulnerabilityMaxSeverity != value)
{
_vulnerabilityMaxSeverity = value;
OnPropertyChanged(nameof(VulnerabilityMaxSeverity));
OnPropertyChanged(nameof(IsPackageVulnerable));
OnPropertyChanged(nameof(IsPackageWithWarnings));
}
}
}
public bool IsPackageWithWarnings
{
get => IsPackageDeprecated || IsPackageVulnerable;
}
private bool _isPackageWithNetworkErrors;
public bool IsPackageWithNetworkErrors
{
get => _isPackageWithNetworkErrors;
set
{
if (IsPackageWithNetworkErrors != value)
{
_isPackageWithNetworkErrors = value;
OnPropertyChanged(nameof(IsPackageWithNetworkErrors));
}
}
}
private Uri _iconUrl;
public Uri IconUrl
{
get { return _iconUrl; }
set
{
_iconUrl = value;
OnPropertyChanged(nameof(IconUrl));
}
}
private IconBitmapStatus _bitmapStatus;
public IconBitmapStatus BitmapStatus
{
get { return _bitmapStatus; }
set
{
if (_bitmapStatus != value)
{
_bitmapStatus = value;
OnPropertyChanged(nameof(BitmapStatus));
}
}
}
private BitmapSource _iconBitmap;
public BitmapSource IconBitmap
{
get
{
if (_iconBitmap == null)
{
if (BitmapStatus == IconBitmapStatus.None)
{
(BitmapSource iconBitmap, IconBitmapStatus nextStatus) = GetInitialIconBitmapAndStatus();
BitmapStatus = nextStatus;
_iconBitmap = iconBitmap;
if (BitmapStatus == IconBitmapStatus.NeedToFetch)
{
BitmapStatus = IconBitmapStatus.Fetching;
NuGetUIThreadHelper.JoinableTaskFactory
.RunAsync(FetchIconAsync)
.PostOnFailure(nameof(PackageItemViewModel), nameof(IconBitmap));
}
}
}
return _iconBitmap;
}
set
{
if (_iconBitmap != value)
{
_iconBitmap = value;
OnPropertyChanged(nameof(IconBitmap));
}
}
}
private string _transitiveToolTipMessage;
public string TransitiveToolTipMessage
{
get => _transitiveToolTipMessage;
set
{
if (_transitiveToolTipMessage != value)
{
_transitiveToolTipMessage = value;
OnPropertyChanged(nameof(TransitiveToolTipMessage));
}
}
}
private PackageLevel _packageLevel;
public PackageLevel PackageLevel
{
get => _packageLevel;
set
{
if (_packageLevel != value)
{
_packageLevel = value;
OnPropertyChanged(nameof(PackageLevel));
OnPropertyChanged(nameof(IsUninstalledOrTransitive));
OnPropertyChanged(nameof(IsInstalledAndTransitive));
}
}
}
public async Task<IReadOnlyCollection<VersionInfoContextInfo>> GetVersionsAsync()
{
var identity = new PackageIdentity(Id, Version);
var isTransitive = PackageLevel == PackageLevel.Transitive;
return await _searchService.GetPackageVersionsAsync(identity, Sources, IncludePrerelease, isTransitive, _cancellationTokenSource.Token);
}
public async Task<IReadOnlyCollection<VersionInfoContextInfo>> GetVersionsAsync(IEnumerable<IProjectContextInfo> projects)
{
var identity = new PackageIdentity(Id, Version);
var isTransitive = PackageLevel == PackageLevel.Transitive;
return await _searchService.GetPackageVersionsAsync(identity, Sources, IncludePrerelease, isTransitive, projects, _cancellationTokenSource.Token);
}
// This Lazy/AsyncLazy is just because DetailControlModel calls GetDetailedPackageSearchMetadataAsync directly,
// and there are tests that don't mock IServiceBroker and INuGetSearchService. It's called via a jtf.RunAsync that is
// not awaited. By keeping this AsyncLazy, we ensure that the exception is thrown in an async continuation. Whereas
// if we get rid of it and have GetDetailedPackageSearchMetadataAsync call _searchService directly, then the exception
// will not be thrown in a continuation, and the test will fail.
private Lazy<Task<(PackageSearchMetadataContextInfo, PackageDeprecationMetadataContextInfo)>> _detailedPackageSearchMetadata =>
new Common.AsyncLazy<(PackageSearchMetadataContextInfo, PackageDeprecationMetadataContextInfo)>(async () =>
{
var identity = new PackageIdentity(Id, Version);
return await _searchService.GetPackageMetadataAsync(identity, Sources, IncludePrerelease, _cancellationTokenSource.Token);
});
public Task<(PackageSearchMetadataContextInfo, PackageDeprecationMetadataContextInfo)> GetDetailedPackageSearchMetadataAsync()
{
return _detailedPackageSearchMetadata.Value;
}
private PackageDeprecationMetadataContextInfo _deprecationMetadata;
public PackageDeprecationMetadataContextInfo DeprecationMetadata
{
get => _deprecationMetadata;
set
{
if (_deprecationMetadata != value)
{
_deprecationMetadata = value;
OnPropertyChanged(nameof(DeprecationMetadata));
}
}
}
public IEnumerable<PackageVulnerabilityMetadataContextInfo> Vulnerabilities { get; set; }
private (BitmapSource, IconBitmapStatus) GetInitialIconBitmapAndStatus()
{
BitmapSource imageBitmap = null;
IconBitmapStatus status;
if (IconUrl == null)
{
imageBitmap = Images.DefaultPackageIcon;
status = IconBitmapStatus.DefaultIcon;
}
else if (!IconUrl.IsAbsoluteUri)
{
imageBitmap = Images.DefaultPackageIcon;
status = IconBitmapStatus.DefaultIconDueToRelativeUri;
}
else
{
string cacheKey = GenerateKeyFromIconUri(IconUrl);
var cachedBitmapImage = BitmapImageCache.Get(cacheKey) as BitmapSource;
if (cachedBitmapImage != null)
{
imageBitmap = cachedBitmapImage;
status = IconBitmapStatus.MemoryCachedIcon;
}
else
{
// Some people run on networks with internal NuGet feeds, but no access to the package images on the internet.
// This is meant to detect that kind of case, and stop spamming the network, so the app remains responsive.
if (ErrorFloodGate.HasTooManyNetworkErrors)
{
imageBitmap = Images.DefaultPackageIcon;
status = IconBitmapStatus.DefaultIconDueToNullStream;
}
else
{
imageBitmap = Images.DefaultPackageIcon;
status = IconBitmapStatus.NeedToFetch;
}
}
}
return (imageBitmap, status);
}
private static bool IsHandleableBitmapEncodingException(Exception ex)
{
return ex is ArgumentException ||
ex is COMException ||
ex is FileFormatException ||
ex is InvalidOperationException ||
ex is NotSupportedException ||
ex is OutOfMemoryException ||
ex is IOException ||
ex is UnauthorizedAccessException;
}
private async Task FetchIconAsync()
{
await TaskScheduler.Default;
Assumes.NotNull(IconUrl);
using (Stream stream = await PackageFileService.GetPackageIconAsync(new PackageIdentity(Id, Version), CancellationToken.None))
{
if (stream != null)
{
var iconBitmapImage = new BitmapImage();
iconBitmapImage.BeginInit();
// BitmapImage can download on its own from URIs, but in order
// to support downloading on a worker thread, we need to download the image
// data and put into a memorystream. Then have the BitmapImage decode the
// image from the memorystream.
using (var memoryStream = new MemoryStream())
{
// Cannot call CopyToAsync as we'll get an InvalidOperationException due to CheckAccess() in next line.
stream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
iconBitmapImage.StreamSource = memoryStream;
try
{
FinalizeBitmapImage(iconBitmapImage);
iconBitmapImage.Freeze();
IconBitmap = iconBitmapImage;
BitmapStatus = IconBitmapStatus.FetchedIcon;
}
catch (Exception ex) when (IsHandleableBitmapEncodingException(ex))
{
IconBitmap = Images.DefaultPackageIcon;
BitmapStatus = IconBitmapStatus.DefaultIconDueToDecodingError;
}
}
}
else
{
ErrorFloodGate.ReportBadNetworkError();
if (BitmapStatus == IconBitmapStatus.Fetching)
{
BitmapStatus = IconBitmapStatus.DefaultIconDueToNullStream;
}
}
ErrorFloodGate.ReportAttempt();
if (IconBitmap != null)
{
string cacheKey = GenerateKeyFromIconUri(IconUrl);
AddToCache(cacheKey, IconBitmap);
}
}
}
private static void FinalizeBitmapImage(BitmapImage iconBitmapImage)
{
// Default cache policy: Per MSDN, satisfies a request for a resource either by using the cached copy of the resource or by sending a request
// for the resource to the server. The action taken is determined by the current cache policy and the age of the content in the cache.
// This is the cache level that should be used by most applications.
iconBitmapImage.UriCachePolicy = RequestCacheIfAvailable;
// Instead of scaling larger images and keeping larger image in memory, this makes it so we scale it down, and throw away the bigger image.
// Only need to set this on one dimension, to preserve aspect ratio
iconBitmapImage.DecodePixelWidth = DecodePixelWidth;
// Workaround for https://github.com/dotnet/wpf/issues/3503
iconBitmapImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
iconBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
iconBitmapImage.EndInit();
}
private static string GenerateKeyFromIconUri(Uri iconUrl)
{
return iconUrl == null ? string.Empty : iconUrl.ToString();
}
private static void AddToCache(string cacheKey, BitmapSource iconBitmapImage)
{
var policy = new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromMinutes(10),
};
BitmapImageCache.Set(cacheKey, iconBitmapImage, policy);
}
private async System.Threading.Tasks.Task ReloadPackageVersionsAsync()
{
CancellationToken cancellationToken = _cancellationTokenSource.Token;
try
{
IReadOnlyCollection<VersionInfoContextInfo> packageVersions = await GetVersionsAsync();
// filter package versions based on allowed versions in packages.config
packageVersions = packageVersions.Where(v => AllowedVersions.Satisfies(v.Version)).ToList();
NuGetVersion result = packageVersions
.Select(p => p.Version)
.MaxOrDefault();
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
LatestVersion = result;
Status = GetPackageStatus(LatestVersion, InstalledVersion, AutoReferenced);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// UI requested cancellation
}
catch (TaskCanceledException)
{
// HttpClient throws TaskCanceledExceptions for HTTP timeouts
try
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
IsPackageWithNetworkErrors = true;
}
catch (OperationCanceledException)
{
// if cancellationToken cancelled before the above is scheduled on UI thread, don't log fault telemetry
}
}
}
private async Task ReloadPackageMetadataAsync()
{
CancellationToken cancellationToken = _cancellationTokenSource.Token;
try
{
var identity = new PackageIdentity(Id, Version);
if (PackageLevel == PackageLevel.TopLevel)
{
(PackageSearchMetadataContextInfo packageMetadata, PackageDeprecationMetadataContextInfo deprecationMetadata) =
await _searchService.GetPackageMetadataAsync(identity, Sources, IncludePrerelease, cancellationToken);
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
DeprecationMetadata = deprecationMetadata;
IsPackageDeprecated = deprecationMetadata != null;
VulnerabilityMaxSeverity = packageMetadata?.Vulnerabilities?.FirstOrDefault()?.Severity ?? -1;
}
else if (PackageLevel == PackageLevel.Transitive && _vulnerabilityService != null)
{
IEnumerable<PackageVulnerabilityMetadataContextInfo> vulnerabilityInfoList =
await _vulnerabilityService.GetVulnerabilityInfoAsync(identity, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
VulnerabilityMaxSeverity = vulnerabilityInfoList?.FirstOrDefault()?.Severity ?? -1;
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// UI requested cancellation.
}
catch (TaskCanceledException)
{
// HttpClient throws TaskCanceledExceptions for HTTP timeouts
try
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
IsPackageWithNetworkErrors = true;
}
catch (OperationCanceledException)
{
// if cancellationToken cancelled before the above is scheduled on UI thread, don't log fault telemetry
}
}
}
public void UpdatePackageStatus(IEnumerable<PackageCollectionItem> installedPackages)
{
// Get the maximum version installed in any target project/solution
InstalledVersion = installedPackages
.GetPackageVersions(Id)
.MaxOrDefault();
// Set auto referenced to true any reference for the given id contains the flag.
AutoReferenced = installedPackages.IsAutoReferenced(Id);
NuGetUIThreadHelper.JoinableTaskFactory
.RunAsync(ReloadPackageVersionsAsync)
.PostOnFailure(nameof(PackageItemViewModel), nameof(ReloadPackageVersionsAsync));
NuGetUIThreadHelper.JoinableTaskFactory
.RunAsync(ReloadPackageMetadataAsync)
.PostOnFailure(nameof(PackageItemViewModel), nameof(ReloadPackageMetadataAsync));
OnPropertyChanged(nameof(Status));
}
public void UpdateTransitivePackageStatus(NuGetVersion installedVersion)
{
InstalledVersion = installedVersion ?? throw new ArgumentNullException(nameof(installedVersion)); ;
// Transitive packages cannot be updated and can only be installed as top-level packages with their currently installed version.
LatestVersion = installedVersion;
NuGetUIThreadHelper.JoinableTaskFactory
.RunAsync(ReloadPackageMetadataAsync)
.PostOnFailure(nameof(PackageItemViewModel), nameof(ReloadPackageMetadataAsync));
OnPropertyChanged(nameof(Status));
}
private static PackageStatus GetPackageStatus(
NuGetVersion latestAvailableVersion,
NuGetVersion installedVersion,
bool autoReferenced)
{
var status = PackageStatus.NotInstalled;
if (autoReferenced)
{
status = PackageStatus.AutoReferenced;
}
else if (installedVersion != null)
{
status = PackageStatus.Installed;
if (VersionComparer.VersionRelease.Compare(installedVersion, latestAvailableVersion) < 0)
{
status = PackageStatus.UpdateAvailable;
}
}
return status;
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string PackagePath { get; set; }
public INuGetPackageFileService PackageFileService { get; internal set; }
public override string ToString()
{
return Id;
}
public void Dispose()
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
// Don't dispose _searchService. It's a shared instance.
}
}
}