-
Notifications
You must be signed in to change notification settings - Fork 698
/
Copy pathPackageSourcesOptionsControl.cs
778 lines (672 loc) · 31.6 KB
/
PackageSourcesOptionsControl.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
// 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.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft;
using Microsoft.ServiceHub.Framework;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.Configuration;
using NuGet.PackageManagement.VisualStudio;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Common;
using NuGet.VisualStudio.Internal.Contracts;
using NuGet.VisualStudio.Telemetry;
using StreamJsonRpc;
using StreamJsonRpc.Protocol;
using GelUtilities = Microsoft.Internal.VisualStudio.PlatformUI.Utilities;
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;
using Task = System.Threading.Tasks.Task;
namespace NuGet.PackageManagement.UI.Options
{
/// <summary>
/// Represents the Tools - Options - Package Manager dialog
/// </summary>
/// <remarks>
/// The code in this class assumes that while the dialog is open, noone is modifying the
/// VSPackageSourceProvider directly.
/// Otherwise, we have a problem with synchronization with the package source provider.
/// </remarks>
public partial class PackageSourcesOptionsControl : UserControl
{
private BindingSource _packageSources;
private BindingSource _machineWidepackageSources;
private readonly IAsyncServiceProvider _asyncServiceProvider;
private bool _initialized;
private IReadOnlyList<PackageSourceContextInfo> _originalPackageSources;
#pragma warning disable ISB001 // Dispose of proxies, disposed in disposing event or in ClearSettings
private INuGetSourcesService _nugetSourcesService; // Store proxy object in case the dialog is up and we lose connection we wont grab the local proxy and try to save to that
#pragma warning restore ISB001 // Dispose of proxies, disposed in disposing event or in ClearSettings
private static IVsImageService2 ImageService
{
get
{
ThreadHelper.ThrowIfNotOnUIThread();
return (IVsImageService2)Package.GetGlobalService(typeof(SVsImageService));
}
}
public static Image WarningIcon { get; private set; }
public static Image ErrorIcon { get; private set; }
public PackageSourcesOptionsControl(IAsyncServiceProvider asyncServiceProvider)
{
ThreadHelper.ThrowIfNotOnUIThread();
InitializeComponent();
_asyncServiceProvider = asyncServiceProvider;
SetupEventHandlers();
UpdateDPI();
ThreadHelper.ThrowIfNotOnUIThread();
ImageAttributes attributes = new ImageAttributes
{
StructSize = Marshal.SizeOf(typeof(ImageAttributes)),
ImageType = (uint)_UIImageType.IT_Bitmap,
Format = (uint)_UIDataFormat.DF_WinForms,
LogicalWidth = 16,
LogicalHeight = 16,
Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags
};
IVsUIObject uIObj = ImageService.GetImage(KnownMonikers.StatusWarning, attributes);
WarningIcon = (Image)GelUtilities.GetObjectData(uIObj);
uIObj = ImageService.GetImage(KnownMonikers.StatusError, attributes);
ErrorIcon = (Image)GelUtilities.GetObjectData(uIObj);
}
private void UpdateDPI()
{
var imgs = images16px;
if (addButton.Height > 72)
{
imgs = images64px;
}
else if (addButton.Height > 40)
{
imgs = images32px;
}
addButton.ImageList = imgs;
removeButton.ImageList = imgs;
}
private void SetupEventHandlers()
{
Disposed += PackageSourcesOptionsControl_Disposed;
NewPackageName.TextChanged += (o, e) => UpdateUI();
NewPackageSource.TextChanged += (o, e) => UpdateUI();
NewPackageName.Focus();
UpdateUI();
}
private void UpdateUI()
{
// It is only allowed for 1 of the listboxes to be selected at any time or neither
// Never MUST both the listboxes be selected
Debug.Assert(PackageSourcesListBox.SelectedItem == null || MachineWidePackageSourcesListBox.SelectedItem == null);
var selectedSource = (PackageSourceContextInfo)PackageSourcesListBox.SelectedItem;
var selectedMachineSource = (PackageSourceContextInfo)MachineWidePackageSourcesListBox.SelectedItem;
if (selectedMachineSource != null)
{
// This block corresponds to MachineWidePackageSourcesListBox
addButton.Enabled = false;
removeButton.Enabled = false;
BrowseButton.Enabled = false;
updateButton.Enabled = false;
NewPackageName.ReadOnly = NewPackageSource.ReadOnly = true;
}
else
{
bool allowEditing = selectedSource != null;
BrowseButton.Enabled = updateButton.Enabled = removeButton.Enabled = allowEditing;
NewPackageName.ReadOnly = NewPackageSource.ReadOnly = !allowEditing;
// Always enable addButton for PackageSourceListBox
addButton.Enabled = true;
}
// Show HttpError for the selected source if needed
if (selectedSource != null)
{
SetHttpErrorVisibilityForSelectedSource(selectedSource);
}
else if (selectedMachineSource != null)
{
SetHttpErrorVisibilityForSelectedSource(selectedMachineSource);
}
}
internal async Task InitializeOnActivatedAsync(CancellationToken cancellationToken)
{
try
{
if (_initialized)
{
return;
}
_initialized = true;
IServiceBrokerProvider serviceBrokerProvider = await ServiceLocator.GetComponentModelServiceAsync<IServiceBrokerProvider>();
IServiceBroker serviceBroker = await serviceBrokerProvider.GetAsync();
#pragma warning disable ISB001 // Dispose of proxies, disposed in disposing event or in ClearSettings
_nugetSourcesService = await serviceBroker.GetProxyAsync<INuGetSourcesService>(
NuGetServices.SourceProviderService,
cancellationToken: cancellationToken);
#pragma warning restore ISB001 // Dispose of proxies, disposed in disposing event or in ClearSettings
Assumes.NotNull(_nugetSourcesService);
// get packages sources
_originalPackageSources = await _nugetSourcesService.GetPackageSourcesAsync(cancellationToken);
// packageSources and machineWidePackageSources are deep cloned when created, no need to worry about re-querying for sources to diff changes
var allPackageSources = _originalPackageSources;
var packageSources = allPackageSources.Where(ps => !ps.IsMachineWide).ToList();
var machineWidePackageSources = allPackageSources.Where(ps => ps.IsMachineWide).ToList();
// bind to the package sources, excluding Aggregate
_packageSources = new BindingSource(packageSources.Select(ps => ps.Clone()).ToList(), null);
_packageSources.CurrentChanged += OnSelectedPackageSourceChanged;
PackageSourcesListBox.GotFocus += PackageSourcesListBox_GotFocus;
PackageSourcesListBox.DataSource = _packageSources;
ResetItemsCheckedState(PackageSourcesListBox, _packageSources);
if (machineWidePackageSources.Count > 0)
{
_machineWidepackageSources = new BindingSource(machineWidePackageSources.Select(ps => ps.Clone()).ToList(), null);
_machineWidepackageSources.CurrentChanged += OnSelectedMachineWidePackageSourceChanged;
MachineWidePackageSourcesListBox.GotFocus += MachineWidePackageSourcesListBox_GotFocus;
MachineWidePackageSourcesListBox.DataSource = _machineWidepackageSources;
ResetItemsCheckedState(MachineWidePackageSourcesListBox, _machineWidepackageSources);
}
else
{
MachineWidePackageSourcesListBox.Visible = MachineWideSourcesLabel.Visible = false;
}
OnSelectedPackageSourceChanged(null, EventArgs.Empty);
}
// Thrown during creating or saving NuGet.Config.
catch (NuGetConfigurationException ex)
{
MessageHelper.ShowErrorMessage(ex.Message, Resources.ErrorDialogBoxTitle);
}
// Thrown if no nuget.config found.
catch (InvalidOperationException ex)
{
MessageHelper.ShowErrorMessage(ex.Message, Resources.ErrorDialogBoxTitle);
}
catch (UnauthorizedAccessException)
{
MessageHelper.ShowErrorMessage(Resources.ShowError_ConfigUnauthorizedAccess, Resources.ErrorDialogBoxTitle);
}
// Unknown exception.
catch (Exception ex)
{
MessageHelper.ShowErrorMessage(Resources.ShowError_SettingActivatedFailed, Resources.ErrorDialogBoxTitle);
ActivityLog.LogError(NuGetUI.LogEntrySource, ex.ToString());
}
}
private void ResetItemsCheckedState(PackageSourceCheckedListBox checkedListBox, BindingSource bindingSource)
{
var list = (IList<PackageSourceContextInfo>)bindingSource.List;
for (int i = 0; i < list.Count; i++)
{
var isEnabled = list[i].IsEnabled;
checkedListBox.SetItemChecked(i, isEnabled);
}
}
private void MachineWidePackageSourcesListBox_GotFocus(object sender, EventArgs e)
{
if (MachineWidePackageSourcesListBox.SelectedItem == null)
{
MachineWidePackageSourcesListBox.SelectedItem = _machineWidepackageSources.Current;
}
OnSelectedMachineWidePackageSourceChanged(sender, null);
}
private void PackageSourcesListBox_GotFocus(object sender, EventArgs e)
{
if (PackageSourcesListBox.SelectedItem == null &&
_packageSources != null)
{
PackageSourcesListBox.SelectedItem = _packageSources.Current;
}
OnSelectedPackageSourceChanged(sender, null);
}
/// <summary>
/// Persist the package sources, which was add/removed via the Options page, to the VS Settings store.
/// This gets called when users click OK button.
/// </summary>
internal async Task<bool> ApplyChangedSettingsAsync(CancellationToken cancellationToken)
{
// if user presses Enter after filling in Name/Source but doesn't click Update
// the options will be closed without adding the source, try adding before closing
// Only apply if nothing was updated or the update was successfull
var result = TryUpdateSource();
if (result != TryUpdateSourceResults.NotUpdated &&
result != TryUpdateSourceResults.Unchanged &&
result != TryUpdateSourceResults.Successful)
{
return false;
}
// get package sources as ordered list
List<PackageSourceContextInfo> packageSources = PackageSourcesListBox.Items.Cast<PackageSourceContextInfo>().ToList();
packageSources.AddRange(MachineWidePackageSourcesListBox.Items.Cast<PackageSourceContextInfo>().ToList());
try
{
if (SourcesChanged(_originalPackageSources, packageSources))
{
await _nugetSourcesService.SavePackageSourceContextInfosAsync(packageSources, cancellationToken);
}
}
catch (Exception ex)
{
if (ex is RemoteInvocationException remoteException &&
remoteException.DeserializedErrorData is CommonErrorData commonError)
{
if (commonError.TypeName == typeof(NuGetConfigurationException).FullName || // Thrown during creating or saving NuGet.Config.
commonError.TypeName == typeof(InvalidOperationException).FullName) // Thrown if no nuget.config found.
{
MessageHelper.ShowErrorMessage(ex.Message, Resources.ErrorDialogBoxTitle);
return false;
}
else if (commonError.TypeName == typeof(UnauthorizedAccessException).FullName)
{
MessageHelper.ShowErrorMessage(Resources.ShowError_ConfigUnauthorizedAccess, Resources.ErrorDialogBoxTitle);
return false;
}
}
else
{
MessageHelper.ShowErrorMessage(Resources.ShowError_ApplySettingFailed, Resources.ErrorDialogBoxTitle);
}
ActivityLog.LogError(NuGetUI.LogEntrySource, ex.ToString());
return false;
}
// find the enabled package source
return true;
}
// Returns true if there are no changes between existingSources and packageSources.
private static bool SourcesChanged(IReadOnlyList<PackageSourceContextInfo> existingSources, IReadOnlyList<PackageSourceContextInfo> packageSources)
{
if (existingSources.Count != packageSources.Count)
{
return true;
}
for (int i = 0; i < existingSources.Count; ++i)
{
if (!existingSources[i].Equals(packageSources[i]) ||
existingSources[i].IsEnabled != packageSources[i].IsEnabled)
{
return true;
}
}
return false;
}
/// <summary>
/// This gets called when users close the Options dialog
/// </summary>
internal void ClearSettings()
{
// clear this flag so that we will set up the bindings again when the option page is activated next time
_initialized = false;
_nugetSourcesService?.Dispose();
_nugetSourcesService = null;
_packageSources = null;
ClearNameSource();
UpdateUI();
}
private void OnRemoveButtonClick(object sender, EventArgs e)
{
if (PackageSourcesListBox.SelectedItem == null)
{
return;
}
_packageSources.Remove(PackageSourcesListBox.SelectedItem);
// changing _packageSources appears to clear all the checked items, so now we have to reset all the checkbox states
ResetItemsCheckedState(PackageSourcesListBox, _packageSources);
UpdateUI();
}
private void OnAddButtonClick(object sender, EventArgs e)
{
if (_packageSources == null)
{
return;
}
_packageSources.Add(CreateNewPackageSource());
// changing _packageSources appears to clear all the checked items, so now we have to reset all the checkbox states
ResetItemsCheckedState(PackageSourcesListBox, _packageSources);
// auto-select the newly-added item
PackageSourcesListBox.SelectedIndex = PackageSourcesListBox.Items.Count - 1;
UpdateUI();
}
private PackageSourceContextInfo CreateNewPackageSource()
{
var sourcesList = (IEnumerable<PackageSourceContextInfo>)_packageSources.List;
for (int i = 0; ; i++)
{
var newName = i == 0 ? "Package source" : "Package source " + i;
var newSource = i == 0 ? "https://packagesource" : "https://packagesource" + i;
var packageSource = new PackageSourceContextInfo(newSource, newName);
if (sourcesList.All(ps => !ps.Equals(packageSource)))
{
return packageSource;
}
}
}
private void OnUpdateButtonClick(object sender, EventArgs e)
{
TryUpdateSourceResults result = TryUpdateSource();
if (result == TryUpdateSourceResults.NotUpdated)
{
MessageHelper.ShowWarningMessage(Resources.ShowWarning_NameAndSourceRequired, Resources.ShowWarning_Title);
SelectAndFocus(NewPackageName);
}
}
private TryUpdateSourceResults TryUpdateSource()
{
var name = NewPackageName.Text.Trim();
var source = NewPackageSource.Text.Trim();
if (string.IsNullOrWhiteSpace(name)
&& string.IsNullOrWhiteSpace(source))
{
return TryUpdateSourceResults.NotUpdated;
}
// validate name
if (string.IsNullOrWhiteSpace(name))
{
MessageHelper.ShowWarningMessage(Resources.ShowWarning_NameRequired, Resources.ShowWarning_Title);
SelectAndFocus(NewPackageName);
return TryUpdateSourceResults.InvalidSource;
}
// validate source
if (string.IsNullOrWhiteSpace(source))
{
MessageHelper.ShowWarningMessage(Resources.ShowWarning_SourceRequried, Resources.ShowWarning_Title);
SelectAndFocus(NewPackageSource);
return TryUpdateSourceResults.InvalidSource;
}
if (!(Common.PathValidator.IsValidLocalPath(source) || Common.PathValidator.IsValidUncPath(source) || Common.PathValidator.IsValidUrl(source)))
{
MessageHelper.ShowWarningMessage(Resources.ShowWarning_InvalidSource, Resources.ShowWarning_Title);
SelectAndFocus(NewPackageSource);
return TryUpdateSourceResults.InvalidSource;
}
var selectedPackageSource = (PackageSourceContextInfo)PackageSourcesListBox.SelectedItem;
if (selectedPackageSource == null)
{
return TryUpdateSourceResults.NotUpdated;
}
if (selectedPackageSource.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase) && selectedPackageSource.Source.Equals(source, StringComparison.OrdinalIgnoreCase))
{
return TryUpdateSourceResults.Unchanged;
}
var sourcesList = (IEnumerable<PackageSourceContextInfo>)_packageSources.List;
// check to see if name has already been added
// also make sure it's not the same as the aggregate source ('All')
bool hasName = sourcesList.Any(ps => ps != selectedPackageSource && string.Equals(name, ps.Name, StringComparison.CurrentCultureIgnoreCase));
if (hasName)
{
MessageHelper.ShowWarningMessage(Resources.ShowWarning_UniqueName, Resources.ShowWarning_Title);
SelectAndFocus(NewPackageName);
return TryUpdateSourceResults.SourceConflicted;
}
// check to see if source has already been added
bool hasSource = sourcesList.Any(ps => ps != selectedPackageSource &&
string.Equals(PathValidator.GetCanonicalPath(source),
PathValidator.GetCanonicalPath(ps.Source),
StringComparison.OrdinalIgnoreCase));
if (hasSource)
{
MessageHelper.ShowWarningMessage(Resources.ShowWarning_UniqueSource, Resources.ShowWarning_Title);
SelectAndFocus(NewPackageSource);
return TryUpdateSourceResults.SourceConflicted;
}
PackageSource packageSource = new PackageSource(source, name);
if (packageSource.IsHttp && !packageSource.IsHttps)
{
// Updating to an http source. Request user confirmation
bool? addHttpSource = MessageHelper.ShowQueryMessage(Resources.Warn_Adding_HttpSource, Resources.DialogTitle_HttpSource, true);
if (addHttpSource == true)
{
selectedPackageSource.Name = name;
selectedPackageSource.Source = source;
selectedPackageSource.AllowInsecureConnections = true;
_packageSources.ResetCurrentItem();
SetHttpErrorVisibilityForSelectedSource(selectedPackageSource);
return TryUpdateSourceResults.Successful;
}
else
{
return TryUpdateSourceResults.Unchanged;
}
}
else
{
selectedPackageSource.Name = name;
selectedPackageSource.Source = source;
_packageSources.ResetCurrentItem();
SetHttpErrorVisibilityForSelectedSource(selectedPackageSource);
return TryUpdateSourceResults.Successful;
}
}
private static void SelectAndFocus(TextBox textBox)
{
textBox.Focus();
textBox.SelectAll();
}
private void ClearNameSource()
{
NewPackageName.Text = string.Empty;
NewPackageSource.Text = string.Empty;
NewPackageName.Focus();
}
private void PackageSourcesContextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
var currentListBox = PackageSourcesContextMenu.SourceControl as ListBox;
if (currentListBox != null
&& currentListBox.SelectedItem != null
&& e.ClickedItem == CopyPackageSourceStripMenuItem)
{
CopySelectedItem((PackageSourceContextInfo)currentListBox.SelectedItem);
}
}
private void PackageSourcesListBox_KeyUp(object sender, KeyEventArgs e)
{
var currentListBox = (PackageSourceCheckedListBox)sender;
if (e.KeyCode == Keys.C && e.Control)
{
CopySelectedItem((PackageSourceContextInfo)currentListBox.SelectedItem);
e.Handled = true;
}
}
private void PackageSourcesListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
var checkedListBox = sender as CheckedListBox;
if (checkedListBox == null)
{
return;
}
if (e.Index < 0 || e.Index >= checkedListBox.Items.Count)
{
return;
}
bool isEnabled = e.NewValue == CheckState.Checked;
var packageSource = (PackageSourceContextInfo)checkedListBox.Items[e.Index];
packageSource.IsEnabled = isEnabled;
}
private Rectangle GetCheckBoxRectangleForListBoxItem(PackageSourceCheckedListBox currentListBox, int itemIndex)
{
const int edgeMargin = 8;
var itemRectangle = currentListBox.GetItemRectangle(itemIndex);
// this is the bound of the checkbox
var checkBoxRectangle = new Rectangle(
itemRectangle.Left + edgeMargin + 2,
itemRectangle.Top + edgeMargin,
currentListBox.CheckBoxSize.Width,
currentListBox.CheckBoxSize.Height);
return checkBoxRectangle;
}
private static void CopySelectedItem(PackageSourceContextInfo selectedPackageSource)
{
Clipboard.Clear();
Clipboard.SetText(selectedPackageSource.Source);
}
private void PackageSourcesListBox_MouseMove(object sender, MouseEventArgs e)
{
var currentListBox = (ListBox)sender;
int index = currentListBox.IndexFromPoint(e.X, e.Y);
if (index >= 0
&& index < currentListBox.Items.Count
&& e.Y <= currentListBox.PreferredHeight)
{
var source = (PackageSourceContextInfo)currentListBox.Items[index];
string newToolTip = !string.IsNullOrEmpty(source.Description) ?
source.Description :
source.Source;
string currentToolTip = packageListToolTip.GetToolTip(currentListBox);
if (currentToolTip != newToolTip)
{
packageListToolTip.SetToolTip(currentListBox, newToolTip);
}
}
else
{
packageListToolTip.SetToolTip(currentListBox, null);
packageListToolTip.Hide(currentListBox);
}
}
private void OnSelectedPackageSourceChanged(object sender, EventArgs e)
{
MachineWidePackageSourcesListBox.ClearSelected();
UpdateUI();
UpdateTextBoxes((PackageSourceContextInfo)_packageSources.Current);
}
private void OnSelectedMachineWidePackageSourceChanged(object sender, EventArgs e)
{
PackageSourcesListBox.ClearSelected();
UpdateUI();
UpdateTextBoxes((PackageSourceContextInfo)_machineWidepackageSources.Current);
}
private void UpdateTextBoxes(PackageSourceContextInfo packageSource)
{
if (packageSource != null)
{
NewPackageName.Text = packageSource.Name;
NewPackageSource.Text = packageSource.Source;
}
else
{
NewPackageName.Text = string.Empty;
NewPackageSource.Text = string.Empty;
}
}
private void OnBrowseButtonClicked(object sender, EventArgs args)
{
NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(OnBrowseButtonClickedAsync).PostOnFailure(nameof(PackageSourcesOptionsControl), nameof(OnBrowseButtonClicked));
}
private async Task OnBrowseButtonClickedAsync()
{
await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
const int MaxDirectoryLength = 1000;
//const int BIF_RETURNONLYFSDIRS = 0x00000001; // For finding a folder to start document searching.
const int BIF_BROWSEINCLUDEURLS = 0x00000080; // Allow URLs to be displayed or entered.
var uiShell = await _asyncServiceProvider.GetServiceAsync<SVsUIShell, IVsUIShell2>();
Assumes.Present(uiShell);
var rgch = new char[MaxDirectoryLength + 1];
// allocate a buffer in unmanaged memory for file name (string)
var bufferPtr = Marshal.AllocCoTaskMem((rgch.Length + 1) * 2);
// copy initial path to bufferPtr
Marshal.Copy(rgch, 0, bufferPtr, rgch.Length);
var pBrowse = new VSBROWSEINFOW[1];
pBrowse[0] = new VSBROWSEINFOW
{
lStructSize = (uint)Marshal.SizeOf(pBrowse[0]),
dwFlags = BIF_BROWSEINCLUDEURLS,
pwzDlgTitle = Resources.BrowseFolderDialogDescription,
nMaxDirName = MaxDirectoryLength,
hwndOwner = Handle,
pwzDirName = bufferPtr,
pwzInitialDir = DetermineInitialDirectory()
};
var browseInfo = new VSNSEBROWSEINFOW[1] { new VSNSEBROWSEINFOW() };
var ret = uiShell.GetDirectoryViaBrowseDlgEx(pBrowse, "", Resources.BrowseFolderDialogSelectButton, "", browseInfo);
if (ret == VSConstants.S_OK)
{
var pathPtr = pBrowse[0].pwzDirName;
var path = Marshal.PtrToStringAuto(pathPtr);
NewPackageSource.Text = path;
// if the package name text box is empty, we fill it with the selected folder's name
if (string.IsNullOrEmpty(NewPackageName.Text))
{
NewPackageName.Text = Path.GetFileName(path);
}
}
}
private string DetermineInitialDirectory()
{
// determine the inital directory to show in the folder dialog
var initialDir = NewPackageSource.Text;
if (IsPathRootedSafe(initialDir)
&& Directory.Exists(initialDir))
{
return initialDir;
}
var selectedItem = (PackageSourceContextInfo)PackageSourcesListBox.SelectedItem;
if (selectedItem != null)
{
initialDir = selectedItem.Source;
if (IsPathRootedSafe(initialDir))
{
return initialDir;
}
}
// fallback to MyDocuments folder
return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
private void PackageSourcesOptionsControl_Disposed(object sender, EventArgs e)
{
Disposed -= PackageSourcesOptionsControl_Disposed;
_nugetSourcesService?.Dispose();
_nugetSourcesService = null;
_packageSources?.Dispose();
_machineWidepackageSources?.Dispose();
}
private static bool IsPathRootedSafe(string path)
{
// Check to make sure path does not contain any invalid chars.
// Otherwise, Path.IsPathRooted() will throw an ArgumentException.
return path.IndexOfAny(Path.GetInvalidPathChars()) == -1 && Path.IsPathRooted(path);
}
private void SetHttpErrorVisibilityForSelectedSource(PackageSourceContextInfo selectedSource)
{
var source = new PackageSource(selectedSource.Source, selectedSource.Name);
source.AllowInsecureConnections = selectedSource.AllowInsecureConnections;
if (source.IsHttp && !source.IsHttps && !source.AllowInsecureConnections)
{
// Error if the selected source is http, and the AllowInsecureConnections for this source is set to false.
HttpErrorOrWarning.Visible = true;
HttpErrorOrWarningIcon.Visible = true;
configurationLink.Visible = true;
HttpErrorOrWarningIcon.Image = ErrorIcon;
HttpErrorOrWarning.Text = Resources.Error_HttpSource_Single;
}
else if (source.AllowInsecureConnections)
{
// Warn if AllowInsecureConnections for this source is set to true.
HttpErrorOrWarning.Visible = true;
HttpErrorOrWarningIcon.Visible = true;
configurationLink.Visible = true;
HttpErrorOrWarningIcon.Image = WarningIcon;
HttpErrorOrWarning.Text = Resources.Warning_HTTPSource;
}
else
{
HttpErrorOrWarning.Visible = false;
HttpErrorOrWarningIcon.Visible = false;
configurationLink.Visible = false;
}
}
}
internal enum TryUpdateSourceResults
{
NotUpdated = 0,
Successful = 1,
InvalidSource = 2,
SourceConflicted = 3,
Unchanged = 4
}
}