-
Notifications
You must be signed in to change notification settings - Fork 701
/
Copy pathVSSolutionManager.cs
1118 lines (907 loc) · 43.7 KB
/
VSSolutionManager.cs
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.ComponentModel.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.PackageManagement.Telemetry;
using NuGet.ProjectManagement;
using NuGet.ProjectManagement.Projects;
using NuGet.ProjectModel;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Common.Telemetry.PowerShell;
using NuGet.VisualStudio.Telemetry;
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;
using Task = System.Threading.Tasks.Task;
namespace NuGet.PackageManagement.VisualStudio
{
[Export(typeof(ISolutionManager))]
[Export(typeof(IVsSolutionManager))]
[PartCreationPolicy(CreationPolicy.Shared)]
public sealed class VSSolutionManager : IVsSolutionManager, IVsSelectionEvents, IVsSolutionEvents, IDisposable
{
private static readonly INuGetProjectContext EmptyNuGetProjectContext = new EmptyNuGetProjectContext();
private const string VSNuGetClientName = "NuGet VS VSIX";
private readonly INuGetLockService _initLock;
private readonly ReentrantSemaphore _semaphoreLock = ReentrantSemaphore.Create(1, NuGetUIThreadHelper.JoinableTaskFactory.Context, ReentrantSemaphore.ReentrancyMode.Freeform);
private SolutionEvents _solutionEvents;
private CommandEvents _solutionSaveEvent;
private CommandEvents _solutionSaveAsEvent;
private IVsMonitorSelection _vsMonitorSelection;
private uint _solutionLoadedUICookie;
private IVsSolution _vsSolution;
private uint _selectionEventsCookie;
private uint _solutionEventsCookie;
private readonly IAsyncServiceProvider _asyncServiceProvider;
private readonly IProjectSystemCache _projectSystemCache;
private readonly NuGetProjectFactory _projectSystemFactory;
private readonly ICredentialServiceProvider _credentialServiceProvider;
private readonly IVsProjectAdapterProvider _vsProjectAdapterProvider;
private readonly Common.ILogger _logger;
private readonly Lazy<ISettings> _settings;
private bool _initialized;
private bool _cacheInitialized;
//add solutionOpenedRasied to make sure ProjectRename and ProjectAdded event happen after solutionOpened event
private bool _solutionOpenedRaised;
private string _solutionDirectoryBeforeSaveSolution;
public INuGetProjectContext NuGetProjectContext { get; set; }
public Task InitializationTask { get; set; }
public bool IsInitialized
{
get
{
return _initialized;
}
}
public async Task<NuGetProject> GetDefaultNuGetProjectAsync()
{
await EnsureInitializeAsync();
if (string.IsNullOrEmpty(DefaultNuGetProjectName))
{
return null;
}
_projectSystemCache.TryGetNuGetProject(DefaultNuGetProjectName, out var defaultNuGetProject);
return defaultNuGetProject;
}
public string DefaultNuGetProjectName { get; set; }
#region Events
public event EventHandler<NuGetProjectEventArgs> NuGetProjectAdded;
public event EventHandler<NuGetProjectEventArgs> NuGetProjectRemoved;
public event EventHandler<NuGetProjectEventArgs> NuGetProjectRenamed;
public event EventHandler<NuGetProjectEventArgs> NuGetProjectUpdated;
public event EventHandler<NuGetProjectEventArgs> AfterNuGetProjectRenamed;
public event EventHandler<NuGetEventArgs<string>> AfterNuGetCacheUpdated;
public event EventHandler SolutionClosed;
public event EventHandler SolutionClosing;
public event EventHandler SolutionOpened;
public event EventHandler SolutionOpening;
public event EventHandler<ActionsExecutedEventArgs> ActionsExecuted;
#endregion Events
[ImportingConstructor]
internal VSSolutionManager(
IProjectSystemCache projectSystemCache,
NuGetProjectFactory projectSystemFactory,
ICredentialServiceProvider credentialServiceProvider,
IVsProjectAdapterProvider vsProjectAdapterProvider,
[Import("VisualStudioActivityLogger")]
Common.ILogger logger,
Lazy<ISettings> settings,
JoinableTaskContext joinableTaskContext)
: this(AsyncServiceProvider.GlobalProvider,
projectSystemCache,
projectSystemFactory,
credentialServiceProvider,
vsProjectAdapterProvider,
logger,
settings,
joinableTaskContext)
{ }
internal VSSolutionManager(
IAsyncServiceProvider asyncServiceProvider,
IProjectSystemCache projectSystemCache,
NuGetProjectFactory projectSystemFactory,
ICredentialServiceProvider credentialServiceProvider,
IVsProjectAdapterProvider vsProjectAdapterProvider,
ILogger logger,
Lazy<ISettings> settings,
JoinableTaskContext joinableTaskContext)
{
Assumes.Present(asyncServiceProvider);
Assumes.Present(projectSystemCache);
Assumes.Present(projectSystemFactory);
Assumes.Present(credentialServiceProvider);
Assumes.Present(vsProjectAdapterProvider);
Assumes.Present(logger);
Assumes.Present(settings);
Assumes.Present(joinableTaskContext);
_asyncServiceProvider = asyncServiceProvider;
_projectSystemCache = projectSystemCache;
_projectSystemFactory = projectSystemFactory;
_credentialServiceProvider = credentialServiceProvider;
_vsProjectAdapterProvider = vsProjectAdapterProvider;
_logger = logger;
_settings = settings;
_initLock = new NuGetLockService(joinableTaskContext);
}
private async Task InitializeAsync()
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
_vsSolution = await _asyncServiceProvider.GetServiceAsync<SVsSolution, IVsSolution>();
var dte = await _asyncServiceProvider.GetDTEAsync();
UserAgent.SetUserAgentString(
new UserAgentStringBuilder(VSNuGetClientName).WithVisualStudioSKU(dte.GetFullVsVersionString()));
HttpHandlerResourceV3.CredentialService = new Lazy<ICredentialService>(() =>
{
return NuGetUIThreadHelper.JoinableTaskFactory.Run(async () =>
{
return await _credentialServiceProvider.GetCredentialServiceAsync();
});
});
_vsMonitorSelection = await _asyncServiceProvider.GetServiceAsync<SVsShellMonitorSelection, IVsMonitorSelection>();
var solutionLoadedGuid = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid;
_vsMonitorSelection.GetCmdUIContextCookie(ref solutionLoadedGuid, out _solutionLoadedUICookie);
var hr = _vsMonitorSelection.AdviseSelectionEvents(this, out _selectionEventsCookie);
ErrorHandler.ThrowOnFailure(hr);
hr = _vsSolution.AdviseSolutionEvents(this, out _solutionEventsCookie);
ErrorHandler.ThrowOnFailure(hr);
// Keep a reference to SolutionEvents so that it doesn't get GC'ed. Otherwise, we won't receive events.
_solutionEvents = dte.Events.SolutionEvents;
_solutionEvents.BeforeClosing += OnBeforeClosing;
_solutionEvents.AfterClosing += OnAfterClosing;
_solutionEvents.ProjectAdded += OnEnvDTEProjectAdded;
_solutionEvents.ProjectRemoved += OnEnvDTEProjectRemoved;
_solutionEvents.ProjectRenamed += OnEnvDTEProjectRenamed;
var vSStd97CmdIDGUID = VSConstants.GUID_VSStandardCommandSet97.ToString("B");
var solutionSaveID = (int)VSConstants.VSStd97CmdID.SaveSolution;
var solutionSaveAsID = (int)VSConstants.VSStd97CmdID.SaveSolutionAs;
_solutionSaveEvent = dte.Events.get_CommandEvents(vSStd97CmdIDGUID, solutionSaveID);
_solutionSaveAsEvent = dte.Events.get_CommandEvents(vSStd97CmdIDGUID, solutionSaveAsID);
_solutionSaveEvent.BeforeExecute += SolutionSaveAs_BeforeExecute;
_solutionSaveEvent.AfterExecute += SolutionSaveAs_AfterExecute;
_solutionSaveAsEvent.BeforeExecute += SolutionSaveAs_BeforeExecute;
_solutionSaveAsEvent.AfterExecute += SolutionSaveAs_AfterExecute;
_projectSystemCache.CacheUpdated += NuGetCacheUpdate_After;
}
public async Task<NuGetProject> GetNuGetProjectAsync(string nuGetProjectSafeName)
{
if (string.IsNullOrEmpty(nuGetProjectSafeName))
{
throw new ArgumentException(
Strings.Argument_Cannot_Be_Null_Or_Empty,
nameof(nuGetProjectSafeName));
}
await EnsureInitializeAsync();
NuGetProject nuGetProject = null;
// Project system cache could be null when solution is not open.
if (_projectSystemCache != null)
{
_projectSystemCache.TryGetNuGetProject(nuGetProjectSafeName, out nuGetProject);
}
return nuGetProject;
}
// Return short name if it's non-ambiguous.
// Return CustomUniqueName for projects that have ambigous names (such as same project name under different solution folder)
// Example: return Folder1/ProjectA if there are both ProjectA under Folder1 and Folder2
public async Task<string> GetNuGetProjectSafeNameAsync(NuGetProject nuGetProject)
{
if (nuGetProject == null)
{
throw new ArgumentNullException(nameof(nuGetProject));
}
await EnsureInitializeAsync();
// Try searching for simple names first
var name = nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name);
if ((await GetNuGetProjectAsync(name)) == nuGetProject)
{
return name;
}
return NuGetProject.GetUniqueNameOrName(nuGetProject);
}
public async Task<IEnumerable<NuGetProject>> GetNuGetProjectsAsync()
{
InitializationTask = EnsureInitializeAsync();
await InitializationTask;
// In certain cases project cache is populated with incomplete project data
// Filter out null entries here.
var projects = _projectSystemCache
.GetNuGetProjects()
.Where(p => p != null)
.ToList();
InitializationTask = null;
return projects;
}
public async Task<bool> IsAllProjectsNominatedAsync()
{
var netCoreProjects = (await GetNuGetProjectsAsync())
.Where(e => IsRestoredOnSolutionLoad(e))
.Cast<BuildIntegratedNuGetProject>()
.ToList();
foreach (var project in netCoreProjects)
{
// check if this .Net core project is nominated or not.
DependencyGraphSpec projectRestoreInfo;
if (!_projectSystemCache.TryGetProjectRestoreInfo(project.MSBuildProjectPath, out projectRestoreInfo, nominationMessages: out _) ||
projectRestoreInfo == null)
{
// there are projects still to be nominated.
return false;
}
}
// return true if all the net core projects have been nominated.
return true;
}
public IReadOnlyList<object> GetAllProjectRestoreInfoSources()
{
return _projectSystemCache.GetProjectRestoreInfoSources();
}
private static bool IsRestoredOnSolutionLoad(NuGetProject nuGetProject)
{
if (nuGetProject is CpsPackageReferenceProject)
{
return true;
}
if (nuGetProject is LegacyPackageReferenceProject legacyPackageReferenceProject)
{
return legacyPackageReferenceProject.ProjectServices.Capabilities.NominatesOnSolutionLoad;
}
return false;
}
/// <summary>
/// IsSolutionOpen is true, if the dte solution is open
/// and is saved as required
/// </summary>
public bool IsSolutionOpen
{
get
{
return NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
{
return await IsSolutionOpenAsync();
});
}
}
public async Task<bool> IsSolutionOpenAsync()
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var dte = await _asyncServiceProvider.GetDTEAsync();
return dte != null &&
dte.Solution != null &&
dte.Solution.IsOpen;
}
public async Task<bool> IsSolutionAvailableAsync()
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!await IsSolutionOpenAsync())
{
// Solution is not open. Return false.
return false;
}
await EnsureInitializeAsync();
if (!DoesSolutionRequireAnInitialSaveAs())
{
// Solution is open and 'Save As' is not required. Return true.
return true;
}
var projects = _projectSystemCache.GetNuGetProjects();
if (!projects.Any() || projects.Any(project => !(project is INuGetIntegratedProject)))
{
// Solution is open, but not saved. That is, 'Save as' is required.
// And, there are no projects or there is a packages.config based project. Return false.
return false;
}
// Solution is open and not saved. And, only contains project.json based projects.
// Check if globalPackagesFolder is a full path. If so, solution is available.
var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(_settings.Value);
return Path.IsPathRooted(globalPackagesFolder);
}
public async Task<bool> DoesNuGetSupportsAnyProjectAsync()
{
// Do NOT initialize VSSolutionManager through this API (by calling EnsureInitializeAsync)
// This is a fast check implemented specifically for right click context menu to be
// quick and does not involve initializing VSSolutionManager. Otherwise it will make
// the UI stop responding for right click on solution.
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// first check with DTE, and if we find any supported project, then return immediately.
var dte = await _asyncServiceProvider.GetDTEAsync();
var isSupported = false;
foreach (Project project in await EnvDTESolutionUtility.GetAllEnvDTEProjectsAsync(dte))
{
if (await EnvDTEProjectUtility.IsSupportedAsync(project))
{
isSupported = true;
break;
}
}
return isSupported;
}
public void EnsureSolutionIsLoaded()
{
NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
await EnsureInitializeAsync();
});
}
public string SolutionDirectory => NuGetUIThreadHelper.JoinableTaskFactory.Run(GetSolutionDirectoryAsync);
public async Task<string> GetSolutionDirectoryAsync()
{
if (!await IsSolutionOpenAsync())
{
return null;
}
var solutionFilePath = await GetSolutionFilePathAsync();
if (string.IsNullOrEmpty(solutionFilePath))
{
return null;
}
return Path.GetDirectoryName(solutionFilePath);
}
public async Task<string> GetSolutionFilePathAsync()
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// Use .Properties.Item("Path") instead of .FullName because .FullName might not be
// available if the solution is just being created
string solutionFilePath;
var dte = await _asyncServiceProvider.GetDTEAsync();
var property = dte.Solution.Properties.Item("Path");
if (property == null)
{
return null;
}
try
{
// When using a temporary solution, (such as by saying File -> New File), querying this value throws.
// Since we wouldn't be able to do manage any packages at this point, we return null. Consumers of this property typically
// use a String.IsNullOrEmpty check either way, so it's alright.
solutionFilePath = (string)property.Value;
}
catch (COMException)
{
return null;
}
return solutionFilePath;
}
/// <summary>
/// Checks whether the current solution is saved to disk, as opposed to be in memory.
/// </summary>
private bool DoesSolutionRequireAnInitialSaveAs()
{
ThreadHelper.ThrowIfNotOnUIThread();
// Check if user is doing File - New File without saving the solution.
var value = GetVSSolutionProperty((int)(__VSPROPID.VSPROPID_IsSolutionSaveAsRequired));
if ((bool)value)
{
return true;
}
// Check if user unchecks the "Tools - Options - Project & Soltuions - Save new projects when created" option
value = GetVSSolutionProperty((int)(__VSPROPID2.VSPROPID_DeferredSaveSolution));
return (bool)value;
}
private object GetVSSolutionProperty(int propId)
{
ThreadHelper.ThrowIfNotOnUIThread();
object value;
var hr = _vsSolution.GetProperty(propId, out value);
ErrorHandler.ThrowOnFailure(hr);
return value;
}
private async Task OnSolutionExistsAndFullyLoadedAsync()
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
SolutionOpening?.Invoke(this, EventArgs.Empty);
NuGetPowerShellUsage.RaiseSolutionOpenEvent();
// although the SolutionOpened event fires, the solution may be only in memory (e.g. when
// doing File - New File). In that case, we don't want to act on the event.
if (!await IsSolutionOpenAsync())
{
return;
}
await EnsureNuGetAndVsProjectAdapterCacheAsync();
SolutionOpened?.Invoke(this, EventArgs.Empty);
_solutionOpenedRaised = true;
}
private void OnAfterClosing()
{
DefaultNuGetProjectName = null;
_projectSystemCache.Clear();
_cacheInitialized = false;
SolutionClosed?.Invoke(this, EventArgs.Empty);
_solutionOpenedRaised = false;
}
private void OnBeforeClosing()
{
NuGetPowerShellUsage.RaiseSolutionCloseEvent();
SolutionClosing?.Invoke(this, EventArgs.Empty);
}
private void SolutionSaveAs_BeforeExecute(
string Guid,
int ID,
object CustomIn,
object CustomOut,
ref bool CancelDefault)
{
_solutionDirectoryBeforeSaveSolution = SolutionDirectory;
}
private void SolutionSaveAs_AfterExecute(string Guid, int ID, object CustomIn, object CustomOut)
{
// If SolutionDirectory before solution save was null
// Or, if SolutionDirectory before solution save is different from the current one
// Reset cache among other things
if (string.IsNullOrEmpty(_solutionDirectoryBeforeSaveSolution)
|| !string.Equals(
_solutionDirectoryBeforeSaveSolution,
SolutionDirectory,
StringComparison.OrdinalIgnoreCase))
{
// Call OnBeforeClosing() to reset the project cache among other things
// After that, call OnSolutionExistsAndFullyLoaded() to load cache, raise events and more
OnBeforeClosing();
NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
{
await OnSolutionExistsAndFullyLoadedAsync();
});
}
}
private void OnEnvDTEProjectRenamed(Project envDTEProject, string oldName)
{
NuGetUIThreadHelper.JoinableTaskFactory.Run(async () =>
{
if (!string.IsNullOrEmpty(oldName) && await IsSolutionOpenAsync() && _solutionOpenedRaised)
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
await EnsureNuGetAndVsProjectAdapterCacheAsync();
if (await EnvDTEProjectUtility.IsSupportedAsync(envDTEProject))
{
RemoveVsProjectAdapterFromCache(oldName);
var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(envDTEProject);
await AddVsProjectAdapterToCacheAsync(vsProjectAdapter);
_projectSystemCache.TryGetNuGetProject(envDTEProject.Name, out var nuGetProject);
NuGetProjectRenamed?.Invoke(this, new NuGetProjectEventArgs(nuGetProject));
// VSSolutionManager susbscribes to this Event, in order to update the caption on the DocWindow Tab.
// This needs to fire after NugetProjectRenamed so that PackageManagerModel has been updated with
// the right project context.
AfterNuGetProjectRenamed?.Invoke(this, new NuGetProjectEventArgs(nuGetProject));
}
else if (await EnvDTEProjectUtility.IsSolutionFolderAsync(envDTEProject))
{
// In the case where a solution directory was changed, project FullNames are unchanged.
// We only need to invalidate the projects under the current tree so as to sync the CustomUniqueNames.
foreach (var item in await EnvDTEProjectUtility.GetSupportedChildProjectsAsync(envDTEProject))
{
RemoveVsProjectAdapterFromCache(item.FullName);
var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(item);
if (await vsProjectAdapter.IsSupportedAsync())
{
await AddVsProjectAdapterToCacheAsync(vsProjectAdapter);
}
}
}
}
});
}
private void OnEnvDTEProjectRemoved(EnvDTE.Project envDTEProject)
{
// This is a solution event. Should be on the UI thread
ThreadHelper.ThrowIfNotOnUIThread();
NuGetProject nuGetProject;
_projectSystemCache.TryGetNuGetProject(envDTEProject.Name, out nuGetProject);
RemoveVsProjectAdapterFromCache(envDTEProject.FullName);
NuGetProjectRemoved?.Invoke(this, new NuGetProjectEventArgs(nuGetProject));
}
private void OnEnvDTEProjectAdded(Project envDTEProject)
{
NuGetUIThreadHelper.JoinableTaskFactory.Run(async () =>
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (await IsSolutionOpenAsync()
&& await EnvDTEProjectUtility.IsSupportedAsync(envDTEProject)
&& !EnvDTEProjectUtility.IsParentProjectExplicitlyUnsupported(envDTEProject)
&& _solutionOpenedRaised)
{
await EnsureNuGetAndVsProjectAdapterCacheAsync();
var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(envDTEProject);
await AddVsProjectAdapterToCacheAsync(vsProjectAdapter);
NuGetProject nuGetProject;
_projectSystemCache.TryGetNuGetProject(envDTEProject.Name, out nuGetProject);
NuGetProjectAdded?.Invoke(this, new NuGetProjectEventArgs(nuGetProject));
}
});
}
private async Task SetDefaultProjectNameAsync()
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
IEnumerable<object> startupProjects;
try
{
// when a new solution opens, we set its startup project as the default project in NuGet Console
var dte = await _asyncServiceProvider.GetDTEAsync();
var solutionBuild = dte.Solution.SolutionBuild as SolutionBuild2;
startupProjects = solutionBuild?.StartupProjects as IEnumerable<object>;
}
catch (COMException)
{
// get_StartupProjects misbehaves for certain project types, so ignore this failure
return;
}
var startupProjectName = startupProjects?.Cast<string>().FirstOrDefault();
if (!string.IsNullOrEmpty(startupProjectName))
{
if (_projectSystemCache.TryGetProjectNames(startupProjectName, out var projectName))
{
DefaultNuGetProjectName = _projectSystemCache.IsAmbiguous(projectName.ShortName) ?
projectName.CustomUniqueName :
projectName.ShortName;
}
}
}
private async Task EnsureNuGetAndVsProjectAdapterCacheAsync()
{
await _initLock.ExecuteNuGetOperationAsync(async () =>
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!_cacheInitialized && await IsSolutionOpenAsync())
{
try
{
var dte = await _asyncServiceProvider.GetDTEAsync();
var supportedProjects = new List<Project>();
foreach (Project project in await EnvDTESolutionUtility.GetAllEnvDTEProjectsAsync(dte))
{
if (await EnvDTEProjectUtility.IsSupportedAsync(project))
{
supportedProjects.Add(project);
}
}
foreach (var project in supportedProjects)
{
try
{
var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(project);
await AddVsProjectAdapterToCacheAsync(vsProjectAdapter);
}
catch (Exception e)
{
// Ignore failed projects.
_logger.LogWarning($"The project {project.Name} failed to initialize as a NuGet project.");
_logger.LogError(e.ToString());
}
// Consider that the cache is initialized only when there are any projects to add.
_cacheInitialized = true;
}
await SetDefaultProjectNameAsync();
}
catch
{
_projectSystemCache.Clear();
_cacheInitialized = false;
DefaultNuGetProjectName = null;
throw;
}
}
}, CancellationToken.None);
}
private async Task AddVsProjectAdapterToCacheAsync(IVsProjectAdapter vsProjectAdapter)
{
_projectSystemCache.TryGetProjectNameByShortName(vsProjectAdapter.ProjectName, out var oldProjectName);
// Create the NuGet project first. If this throws we bail out and do not change the cache.
var nuGetProject = await CreateNuGetProjectAsync(vsProjectAdapter);
// Then create the project name from the project.
var newProjectName = vsProjectAdapter.ProjectNames;
// Finally, try to add the project to the cache.
var added = _projectSystemCache.AddProject(newProjectName, vsProjectAdapter, nuGetProject);
if (added && nuGetProject != null)
{
// Emit project specific telemetry as we are adding the project to the cache.
// This ensures we do not emit the events over and over while the solution is
// open.
TelemetryActivity.EmitTelemetryEvent(await VSTelemetryServiceUtility.GetProjectTelemetryEventAsync(nuGetProject));
}
if (string.IsNullOrEmpty(DefaultNuGetProjectName) ||
newProjectName.ShortName.Equals(DefaultNuGetProjectName, StringComparison.OrdinalIgnoreCase))
{
DefaultNuGetProjectName = oldProjectName != null ?
oldProjectName.CustomUniqueName :
newProjectName.ShortName;
}
}
private void RemoveVsProjectAdapterFromCache(string name)
{
// Do nothing if the cache hasn't been set up
if (_projectSystemCache == null)
{
return;
}
_projectSystemCache.TryGetProjectNames(name, out var projectNames);
// Remove the project from the cache
_projectSystemCache.RemoveProject(name);
if (!_projectSystemCache.ContainsKey(DefaultNuGetProjectName))
{
DefaultNuGetProjectName = null;
}
// for LightSwitch project, the main project is not added to _projectCache, but it is called on removal.
// in that case, projectName is null.
if (projectNames != null
&& projectNames.CustomUniqueName.Equals(DefaultNuGetProjectName, StringComparison.OrdinalIgnoreCase)
&& !_projectSystemCache.IsAmbiguous(projectNames.ShortName))
{
DefaultNuGetProjectName = projectNames.ShortName;
}
}
private async Task EnsureInitializeAsync()
{
try
{
// If already initialized, need not be on the UI thread
if (_initialized)
{
await EnsureNuGetAndVsProjectAdapterCacheAsync();
return;
}
// Ensure all initialization finished when needed, it still runs as async and prevents _initialized set true too early.
// Setting '_initialized = true' too early caused random timing bug.
await _semaphoreLock.ExecuteAsync(async () =>
{
if (_initialized)
{
return;
}
NuGetVSTelemetryService.Initialize();
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
await InitializeAsync();
var dte = await _asyncServiceProvider.GetDTEAsync();
if (dte.Solution.IsOpen)
{
await OnSolutionExistsAndFullyLoadedAsync();
}
_initialized = true;
});
}
catch (Exception e)
{
// ignore errors
Debug.Fail(e.ToString());
_logger.LogError(e.ToString());
}
}
private async Task<NuGetProject> CreateNuGetProjectAsync(IVsProjectAdapter project, INuGetProjectContext projectContext = null)
{
var context = new ProjectProviderContext(
projectContext ?? EmptyNuGetProjectContext,
() => PackagesFolderPathUtility.GetPackagesFolderPath(this, _settings.Value));
return await _projectSystemFactory.TryCreateNuGetProjectAsync(project, context);
}
internal async Task<IDictionary<string, List<IVsProjectAdapter>>> GetDependentProjectsDictionaryAsync()
{
// Get all of the projects in the solution and build the reverse graph. i.e.
// if A has a project reference to B (A -> B) the this will return B -> A
// We need to run this on the ui thread so that it doesn't freeze for websites. Since there might be a
// large number of references.
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
await EnsureInitializeAsync();
var dependentProjectsDictionary = new Dictionary<string, List<IVsProjectAdapter>>();
var vsProjectAdapters = await GetAllVsProjectAdaptersAsync();
foreach (var vsProjectAdapter in vsProjectAdapters)
{
var referencedProjects = await vsProjectAdapter.GetReferencedProjectsAsync();
foreach (var projectProjectPath in referencedProjects)
{
var result = _projectSystemCache.TryGetVsProjectAdapter(projectProjectPath, out var vsReferencedProject);
if (result)
{
AddDependentProject(dependentProjectsDictionary, vsReferencedProject, vsProjectAdapter);
}
}
}
return dependentProjectsDictionary;
}
private static void AddDependentProject(
IDictionary<string, List<IVsProjectAdapter>> dependentProjectsDictionary,
IVsProjectAdapter vsProjectAdapter,
IVsProjectAdapter dependentVsProjectAdapter)
{
var uniqueName = vsProjectAdapter.UniqueName;
if (!dependentProjectsDictionary.TryGetValue(uniqueName, out var dependentProjects))
{
dependentProjects = new List<IVsProjectAdapter>();
dependentProjectsDictionary[uniqueName] = dependentProjects;
}
dependentProjects.Add(dependentVsProjectAdapter);
}
/// <summary>
/// This method is invoked when ProjectSystemCache fires a CacheUpdated event.
/// This method inturn invokes AfterNuGetCacheUpdated event which is consumed by PackageManagerControl.xaml.cs
/// </summary>
/// <param name="sender">Event sender object</param>
/// <param name="e">Event arguments. This will be EventArgs.Empty</param>
private void NuGetCacheUpdate_After(object sender, NuGetEventArgs<string> e)
{
// The AfterNuGetCacheUpdated event is raised on a separate Task to prevent blocking of the caller.
// E.g. - If Restore updates the cache entries on CPS nomination, then restore should not be blocked till UI is restored.
NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(() => FireNuGetCacheUpdatedEventAsync(e)).PostOnFailure(nameof(VSSolutionManager));
}
private async Task FireNuGetCacheUpdatedEventAsync(NuGetEventArgs<string> e)
{
try
{
// Await a delay of 100 mSec to batch multiple cache updated events.
// This ensures the minimum duration between 2 consecutive UI refresh, caused by cache update, to be 100 mSec.
await Task.Delay(100);
// Check if the cache is still dirty
if (_projectSystemCache.TestResetDirtyFlag())
{
// Fire the event only if the cache is dirty
AfterNuGetCacheUpdated?.Invoke(this, e);
}
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
}
}
#region IVsSelectionEvents
public int OnCmdUIContextChanged(uint dwCmdUICookie, int fActive)
{
return VSConstants.S_OK;
}
public int OnElementValueChanged(uint elementid, object varValueOld, object varValueNew)
{
return VSConstants.S_OK;
}
public int OnSelectionChanged(IVsHierarchy pHierOld, uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew)
{
return VSConstants.S_OK;
}
public void OnActionsExecuted(IEnumerable<ResolvedAction> actions)
{
ActionsExecuted?.Invoke(this, new ActionsExecutedEventArgs(actions));
}
#endregion IVsSelectionEvents
#region IVsSolutionManager
public async Task<NuGetProject> GetOrCreateProjectAsync(EnvDTE.Project project, INuGetProjectContext projectContext)
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var projectSafeName = await project.GetCustomUniqueNameAsync();
var nuGetProject = await GetNuGetProjectAsync(projectSafeName);
// if the project does not exist in the solution (this is true for new templates)
// create it manually
if (nuGetProject == null)
{
var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(project);
nuGetProject = await CreateNuGetProjectAsync(vsProjectAdapter, projectContext);
}
return nuGetProject;
}
public async Task<IVsProjectAdapter> GetVsProjectAdapterAsync(string nuGetProjectSafeName)
{
Assumes.NotNullOrEmpty(nuGetProjectSafeName);
await EnsureInitializeAsync();
_projectSystemCache.TryGetVsProjectAdapter(nuGetProjectSafeName, out var vsProjectAdapter);
return vsProjectAdapter;
}
public async Task<IVsProjectAdapter> GetVsProjectAdapterAsync(NuGetProject nuGetProject)
{
Assumes.Present(nuGetProject);
await EnsureInitializeAsync();
var nuGetProjectSafeName = await GetNuGetProjectSafeNameAsync(nuGetProject);
_projectSystemCache.TryGetVsProjectAdapter(nuGetProjectSafeName, out var vsProjectAdapter);
return vsProjectAdapter;
}
public async Task<bool> IsSolutionFullyLoadedAsync()
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
await EnsureInitializeAsync();
var value = GetVSSolutionProperty((int)(__VSPROPID4.VSPROPID_IsSolutionFullyLoaded));
return (bool)value;
}
public async Task<IEnumerable<IVsProjectAdapter>> GetAllVsProjectAdaptersAsync()
{
await EnsureInitializeAsync();