Ejemplo n.º 1
0
        private async Task ExecuteAsync(object sender, EventArgs e)
        {
            Telemetry.TrackUserTask("Execute-ManageLibrariesCommand");

            Project project = await VsHelpers.GetProjectOfSelectedItemAsync();

            if (project != null)
            {
                string rootFolder = await project.GetRootFolderAsync();

                string configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName);

                if (File.Exists(configFilePath))
                {
                    await VsHelpers.OpenFileAsync(configFilePath);
                }
                else
                {
                    var      dependencies = _dependenciesFactory.FromConfigFile(configFilePath);
                    Manifest manifest     = await Manifest.FromFileAsync(configFilePath, dependencies, CancellationToken.None);

                    manifest.DefaultProvider = "cdnjs";
                    manifest.Version         = Manifest.SupportedVersions.Max().ToString();

                    await manifest.SaveAsync(configFilePath, CancellationToken.None);

                    await project.AddFileToProjectAsync(configFilePath);

                    Telemetry.TrackUserTask("Create-ConfigFile");
                }

                await VsHelpers.OpenFileAsync(configFilePath);
            }
        }
        private async Task<Dictionary<string, Manifest>> GetManifestFromConfigAsync(IEnumerable<string> configFiles, CancellationToken cancellationToken)
        {
            Dictionary<string, Manifest> manifests = new Dictionary<string, Manifest>();

            try
            {
                foreach (string configFilePath in configFiles)
                {
                    IDependencies dependencies = _dependenciesFactory.FromConfigFile(configFilePath);
                    Manifest manifest = await Manifest.FromFileAsync(configFilePath, dependencies, cancellationToken).ConfigureAwait(false);
                    manifests.Add(configFilePath, manifest);
                }
            }
            catch (Exception ex)
            {
                Logger.LogEvent(LibraryManager.Resources.Text.Restore_OperationFailed + Environment.NewLine + ex.Message, LogLevel.Operation);
                Telemetry.TrackException(nameof(GetManifestFromConfigAsync), ex);

                return null;
            }

            return manifests;
        }
Ejemplo n.º 3
0
        protected override IEnumerable <JsonCompletionEntry> GetEntries(JsonCompletionContext context)
        {
            MemberNode member = context.ContextNode.FindType <MemberNode>();

            if (member == null || (member.UnquotedNameText != ManifestConstants.Destination && member.UnquotedNameText != ManifestConstants.DefaultDestination))
            {
                yield break;
            }

            MemberNode parent = member.FindType <ObjectNode>()?.FindType <MemberNode>();

            if (member.UnquotedNameText == ManifestConstants.Destination && (parent == null || parent.UnquotedNameText != ManifestConstants.Libraries))
            {
                yield break;
            }

            if (member.UnquotedNameText == ManifestConstants.DefaultDestination && parent != null)
            {
                yield break;
            }

            int caretPosition = context.Session.TextView.Caret.Position.BufferPosition - member.Value.Start - 1;

            if (caretPosition > member.UnquotedValueText.Length)
            {
                yield break;
            }

            var    dependencies = _dependenciesFactory.FromConfigFile(ConfigFilePath);
            string cwd          = dependencies?.GetHostInteractions().WorkingDirectory;

            if (string.IsNullOrEmpty(cwd))
            {
                yield break;
            }

            IEnumerable <Tuple <string, string> > completions = GetCompletions(cwd, member.UnquotedValueText, caretPosition, out Span span);
            int           start        = member.Value.Start;
            ITrackingSpan trackingSpan = context.Snapshot.CreateTrackingSpan(start + 1 + span.Start, span.Length, SpanTrackingMode.EdgeInclusive);

            foreach (Tuple <string, string> item in completions)
            {
                yield return(new SimpleCompletionEntry(item.Item1, item.Item2, KnownMonikers.FolderClosed, trackingSpan, context.Session));
            }
        }
        protected override IEnumerable <JsonCompletionEntry> GetEntries(JsonCompletionContext context)
        {
            var member = context.ContextNode as MemberNode;

            if (member == null || (member.UnquotedNameText != ManifestConstants.Provider && member.UnquotedNameText != ManifestConstants.DefaultProvider))
            {
                yield break;
            }

            var dependencies = _dependenciesFactory.FromConfigFile(ConfigFilePath);
            IEnumerable <string> providerIds = dependencies.Providers?.Select(p => p.Id);

            if (providerIds == null || !providerIds.Any())
            {
                yield break;
            }

            foreach (string id in providerIds)
            {
                yield return(new SimpleCompletionEntry(id, _libraryIcon, context.Session));
            }
        }
Ejemplo n.º 5
0
        private async Task ExecuteAsync(object sender, EventArgs e)
        {
            ProjectItem projectItem = await VsHelpers.GetSelectedItemAsync();

            Project project = await VsHelpers.GetProjectOfSelectedItemAsync();

            try
            {
                var dependencies = _dependenciesFactory.FromConfigFile(projectItem.FileNames[1]);
                IEnumerable <string> packageIds = dependencies.Providers
                                                  .Where(p => p.NuGetPackageId != null)
                                                  .Select(p => p.NuGetPackageId)
                                                  .Distinct();

                if (!_isPackageInstalled)
                {
                    if (!UserWantsToInstall())
                    {
                        return;
                    }

                    await Task.Run(() =>
                    {
                        Logger.LogEvent(Resources.Text.Nuget_InstallingPackage, LogLevel.Status);

                        try
                        {
                            foreach (string packageId in packageIds)
                            {
                                IVsPackageInstaller2 installer = _componentModel.GetService <IVsPackageInstaller2>();
                                installer.InstallLatestPackage(null, project, packageId, true, false);
                            }

                            Telemetry.TrackUserTask("Install-NugetPackage");
                            Logger.LogEvent(Resources.Text.Nuget_PackageInstalled, LogLevel.Status);
                        }
                        catch (Exception ex)
                        {
                            Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex);
                            Logger.LogEvent(Resources.Text.Nuget_PackageFailedToInstall, LogLevel.Status);
                        }
                    });
                }
                else
                {
                    await Task.Run(() =>
                    {
                        Logger.LogEvent(Resources.Text.Nuget_UninstallingPackage, LogLevel.Status);

                        try
                        {
                            foreach (string packageId in packageIds)
                            {
                                IVsPackageUninstaller uninstaller = _componentModel.GetService <IVsPackageUninstaller>();
                                uninstaller.UninstallPackage(project, packageId, false);
                            }

                            Telemetry.TrackUserTask("Uninstall-NugetPackage");
                            Logger.LogEvent(Resources.Text.Nuget_PackageUninstalled, LogLevel.Status);
                        }
                        catch (Exception ex)
                        {
                            Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex);
                            Logger.LogEvent(Resources.Text.Nuget_PackageFailedToUninstall, LogLevel.Status);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex);
                Logger.LogEvent(Resources.Text.Nuget_PackageFailedToInstall, LogLevel.Status);
            }
        }
        protected override IEnumerable <JsonCompletionEntry> GetEntries(JsonCompletionContext context)
        {
            MemberNode member = context.ContextNode.FindType <MemberNode>();

            if (member == null || member.UnquotedNameText != "files")
            {
                yield break;
            }

            var parent = member.Parent as ObjectNode;

            if (!JsonHelpers.TryGetInstallationState(parent, out ILibraryInstallationState state))
            {
                yield break;
            }

            if (string.IsNullOrEmpty(state.Name))
            {
                yield break;
            }

            var             dependencies = _dependenciesFactory.FromConfigFile(ConfigFilePath);
            IProvider       provider     = dependencies.GetProvider(state.ProviderId);
            ILibraryCatalog catalog      = provider?.GetCatalog();

            if (catalog == null)
            {
                yield break;
            }

            Task <ILibrary>      task      = catalog.GetLibraryAsync(state.Name, state.Version, CancellationToken.None);
            FrameworkElement     presenter = GetPresenter(context);
            IEnumerable <string> usedFiles = GetUsedFiles(context);

            if (task.IsCompleted)
            {
                if (!(task.Result is ILibrary library))
                {
                    yield break;
                }

                foreach (string file in library.Files.Keys)
                {
                    if (!usedFiles.Contains(file))
                    {
                        ImageSource glyph = WpfUtil.GetIconForFile(presenter, file, out bool isThemeIcon);
                        yield return(new SimpleCompletionEntry(file, glyph, context.Session));
                    }
                }
            }
            else
            {
                yield return(new SimpleCompletionEntry(Resources.Text.Loading, string.Empty, KnownMonikers.Loading, context.Session));

                _ = task.ContinueWith(async(t) =>
                {
                    await VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    if (!(t.Result is ILibrary library))
                    {
                        return;
                    }

                    if (!context.Session.IsDismissed)
                    {
                        var results = new List <JsonCompletionEntry>();

                        foreach (string file in library.Files.Keys)
                        {
                            if (!usedFiles.Contains(file))
                            {
                                ImageSource glyph = WpfUtil.GetIconForFile(presenter, file, out bool isThemeIcon);
                                results.Add(new SimpleCompletionEntry(file, glyph, context.Session));
                            }
                        }

                        UpdateListEntriesSync(context, results);
                    }
                }, TaskScheduler.Default);
            }
        }
Ejemplo n.º 7
0
        private async Task ExecuteAsync(object sender, EventArgs e)
        {
            Telemetry.TrackUserTask("Execute-InstallLibraryCommand");

            ProjectItem item = await VsHelpers.GetSelectedItemAsync().ConfigureAwait(false);

            Project project = await VsHelpers.GetProjectOfSelectedItemAsync().ConfigureAwait(false);

            if (project != null)
            {
                string rootFolder = await project.GetRootFolderAsync().ConfigureAwait(false);

                string        configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName);
                IDependencies dependencies   = _dependenciesFactory.FromConfigFile(configFilePath);

                Manifest manifest = await GetManifestAsync(configFilePath, dependencies).ConfigureAwait(false);

                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                // If the manifest contains errors, we will not invoke the "Add Client-Side libraries" dialog
                // Instead we will display a message box indicating the syntax errors in manifest file.
                if (manifest == null)
                {
                    IVsUIShell shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell;
                    int        result;

                    shell.ShowMessageBox(dwCompRole: 0,
                                         rclsidComp: Guid.Empty,
                                         pszTitle: null,
                                         pszText: PredefinedErrors.ManifestMalformed().Message,
                                         pszHelpFile: null,
                                         dwHelpContextID: 0,
                                         msgbtn: OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                         msgdefbtn: OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                                         msgicon: OLEMSGICON.OLEMSGICON_WARNING,
                                         fSysAlert: 0,
                                         pnResult: out result);

                    return;
                }

                string target = string.Empty;

                // Install command was invoked from a folder.
                // So the initial target location should be name of the folder from which
                // the command was invoked.
                if (item != null)
                {
                    target = item.FileNames[1];
                }
                else
                {
                    // Install command was invoked from project scope.
                    // If wwwroot exists, initial target location should be - wwwroot/lib.
                    // Else, target location should be - lib
                    if (Directory.Exists(Path.Combine(rootFolder, "wwwroot")))
                    {
                        target = Path.Combine(rootFolder, "wwwroot", "lib") + Path.DirectorySeparatorChar;
                    }
                    else
                    {
                        target = Path.Combine(rootFolder, "lib") + Path.DirectorySeparatorChar;
                    }
                }

                string initialTargetLocation = CalculateSuggestedInstallPath(target, rootFolder);


                var selectedProviderBinding = new SelectedProviderBinding();
                var libraryIdViewModel      = new LibraryIdViewModel(new ProviderCatalogSearchService(() => selectedProviderBinding.SelectedProvider),
                                                                     string.Empty);

                var libraryNameBinding      = new LibraryNameBinding();
                var targetLocationViewModel = new TargetLocationViewModel(initialTargetLocation,
                                                                          libraryNameBinding,
                                                                          new LocationSearchService(dependencies.GetHostInteractions()));

                var dialogViewModel = new InstallDialogViewModel(
                    _libraryCommandService,
                    configFilePath,
                    dependencies,
                    libraryIdViewModel,
                    targetLocationViewModel,
                    selectedProviderBinding,
                    libraryNameBinding,
                    target,
                    project);

                var dialog = new UI.InstallDialog(dialogViewModel);
                dialog.ShowModal();

                Telemetry.TrackUserTask("Open-InstallDialog");
            }
        }
Ejemplo n.º 8
0
        protected override IEnumerable <JsonCompletionEntry> GetEntries(JsonCompletionContext context)
        {
            var member = context.ContextNode as MemberNode;

            if (member == null || member.UnquotedNameText != ManifestConstants.Library)
            {
                yield break;
            }

            var parent = member.Parent as ObjectNode;

            if (!JsonHelpers.TryGetInstallationState(parent, out ILibraryInstallationState state))
            {
                yield break;
            }

            var             dependencies = _dependenciesFactory.FromConfigFile(ConfigFilePath);
            IProvider       provider     = dependencies.GetProvider(state.ProviderId);
            ILibraryCatalog catalog      = provider?.GetCatalog();

            if (catalog == null)
            {
                yield break;
            }

            // member.Value is null when there is no value yet, e.g. when typing a space at "library":|
            // where | represents caret position. In this case, set caretPosition to "1" to short circuit execution of this function
            // and return no entries (member.UnquotedValueText will be empty string in that case).
            int caretPosition = member.Value != null ? context.Session.TextView.Caret.Position.BufferPosition - member.Value.Start - 1 : 1;

            if (caretPosition > member.UnquotedValueText.Length)
            {
                yield break;
            }

            Task <CompletionSet> task = catalog.GetLibraryCompletionSetAsync(member.UnquotedValueText, caretPosition);
            int count = 0;

            if (!context.Session.Properties.ContainsProperty(CompletionController.RetriggerCompletion))
            {
                context.Session.Properties.AddProperty(CompletionController.RetriggerCompletion, true);
            }

            if (task.IsCompleted)
            {
                CompletionSet completionSet = task.Result;

                if (completionSet.Completions != null)
                {
                    List <JsonCompletionEntry> results = GetCompletionList(member, context, completionSet, count);

                    foreach (JsonCompletionEntry completionEntry in results)
                    {
                        yield return(completionEntry);
                    }
                }
            }
            else
            {
                yield return(new SimpleCompletionEntry(Resources.Text.Loading, string.Empty, KnownMonikers.Loading, context.Session));

                _ = task.ContinueWith((t) =>
                {
                    if (!t.IsCanceled || !t.IsFaulted)
                    {
                        if (!context.Session.IsDismissed)
                        {
                            CompletionSet completionSet = t.Result;

                            if (completionSet.Completions != null)
                            {
                                List <JsonCompletionEntry> results = GetCompletionList(member, context, completionSet, count);

                                UpdateListEntriesSync(context, results);
                            }
                        }
                    }
                }, TaskScheduler.Default);
            }
        }