Пример #1
0
        /// <summary>
        /// Returns an IVsTextView for the given file path, if the given file is open in Visual Studio.
        /// </summary>
        /// <param name="serviceProvider">The package Service Provider.</param>
        /// <param name="filePath">Full Path of the file you are looking for.</param>
        /// <returns>
        /// The IVsTextView for this file, if it is open, null otherwise.
        /// </returns>
        internal static async Task <IWpfTextView> GetWpfTextViewByFilePathAsync(this Shell.IAsyncServiceProvider serviceProvider, string filePath)
        {
            if (filePath.IsNullOrWhiteSpace() || serviceProvider == null)
            {
                return(null);
            }

            if (!Shell.ThreadHelper.CheckAccess())
            {
                await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            }

            DTE2 dte2 = await serviceProvider.GetServiceAsync <Shell.Interop.SDTE, DTE2>();

            var oleServiceProvider = dte2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

            if (dte2 == null || oleServiceProvider == null)
            {
                return(null);
            }

            Shell.ServiceProvider shellServiceProvider = new Shell.ServiceProvider(oleServiceProvider);

            if (Shell.VsShellUtilities.IsDocumentOpen(shellServiceProvider, filePath, Guid.Empty, out var uiHierarchy, out var itemID, out var windowFrame))
            {
                IVsTextView textView = Shell.VsShellUtilities.GetTextView(windowFrame);                   // Get the IVsTextView from the windowFrame
                return(await serviceProvider.GetWpfTextViewFromTextViewAsync(textView));
            }

            return(null);
        }
        public VisualStudioActiveDocumentTracker(
            IThreadingContext threadingContext,
            [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider,
            IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
            : base(threadingContext, assertIsForeground: false)
        {
            _editorAdaptersFactoryService = editorAdaptersFactoryService;
            ThreadingContext.RunWithShutdownBlockAsync(async cancellationToken =>
            {
                await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                var monitorSelectionService = (IVsMonitorSelection)await asyncServiceProvider.GetServiceAsync(typeof(SVsShellMonitorSelection)).ConfigureAwait(true);
                Assumes.Present(monitorSelectionService);

                // No need to track windows if we are shutting down
                cancellationToken.ThrowIfCancellationRequested();

                if (ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var value)))
                {
                    if (value is IVsWindowFrame windowFrame)
                    {
                        TrackNewActiveWindowFrame(windowFrame);
                    }
                }

                monitorSelectionService.AdviseSelectionEvents(this, out var _);
            });
        }
Пример #3
0
        private string GetActiveFilePath(Microsoft.VisualStudio.Shell.IAsyncServiceProvider serviceProvider)
        {
            Task <object> t = serviceProvider.GetServiceAsync(typeof(EnvDTE.DTE));

            t.Wait( );
            EnvDTE80.DTE2 applicationObject = t.Result as EnvDTE80.DTE2;


            foreach (EnvDTE.SelectedItem selectedItem in applicationObject.SelectedItems)
            {
                if (selectedItem.ProjectItem == null)
                {
                    return(null);
                }
                var projectItem      = selectedItem.ProjectItem;
                var fullPathProperty = projectItem.Properties.Item("FullPath");
                if (fullPathProperty == null)
                {
                    return(null);
                }
                var fullPath = fullPathProperty.Value.ToString( );
                return(fullPath);
            }

            return(null);
        }
Пример #4
0
        protected BaseCommand(IAsyncServiceProvider serviceProvider)
        {
            ServiceProvider = serviceProvider
                              ?? throw new ArgumentNullException(nameof(serviceProvider));

            ThreadHelper.JoinableTaskFactory.Run(SetupCommandsAsync);
        }
Пример #5
0
        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);
        }
            public static async Task <RestoreOperationProgressUI> StartAsync(
                IAsyncServiceProvider asyncServiceProvider,
                JoinableTaskFactory jtf,
                CancellationToken token)
            {
                await jtf.SwitchToMainThreadAsync();

                var statusBar = await asyncServiceProvider.GetServiceAsync <SVsStatusbar, IVsStatusbar>();

                // Make sure the status bar is not frozen
                int frozen;

                statusBar.IsFrozen(out frozen);

                if (frozen != 0)
                {
                    statusBar.FreezeOutput(0);
                }

                statusBar.Animation(1, ref Icon);

                RestoreOperationProgressUI progress = new StatusBarProgress(statusBar, jtf);
                await progress.ReportProgressAsync(Resources.RestoringPackages);

                return(progress);
            }
Пример #7
0
        OutputConsoleProvider(
            Microsoft.VisualStudio.Shell.IAsyncServiceProvider asyncServiceProvider, // ambigiuous reference
            IEnumerable <Lazy <IHostProvider, IHostMetadata> > hostProviders)
        {
            if (asyncServiceProvider == null)
            {
                throw new ArgumentNullException(nameof(asyncServiceProvider));
            }

            if (hostProviders == null)
            {
                throw new ArgumentNullException(nameof(hostProviders));
            }

            _hostProviders = hostProviders;

            _vsOutputWindow = new AsyncLazy <IVsOutputWindow>(
                async() =>
            {
                return(await asyncServiceProvider.GetServiceAsync <SVsOutputWindow, IVsOutputWindow>());
            },
                NuGetUIThreadHelper.JoinableTaskFactory);

            _vsUIShell = new AsyncLazy <IVsUIShell>(
                async() =>
            {
                return(await asyncServiceProvider.GetServiceAsync <SVsUIShell, IVsUIShell>());
            },
                NuGetUIThreadHelper.JoinableTaskFactory);

            _cachedOutputConsole = new Lazy <IConsole>(
                () => new OutputConsole(VsOutputWindow, VsUIShell));
        }
        public static async Task <IWpfTextViewHost> GetCurrentViewHostAsync(IAsyncServiceProvider serviceProvider)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var txtMgr = await serviceProvider.GetServiceAsync <SVsTextManager, IVsTextManager>();

            int mustHaveFocus = 1;

            if (txtMgr == null)
            {
                return(null);
            }

            txtMgr.GetActiveView(mustHaveFocus, null, out IVsTextView vTextView);
            if (!(vTextView is IVsUserData userData))
            {
                return(null);
            }

            Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;

            userData.GetData(ref guidViewHost, out var holder);

            return(holder as IWpfTextViewHost);
        }
Пример #9
0
        public VisualStudioActiveDocumentTracker(
            IThreadingContext threadingContext,
            [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider,
            IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
            : base(threadingContext, assertIsForeground: false)
        {
            _editorAdaptersFactoryService = editorAdaptersFactoryService;
            _asyncTasks = new JoinableTaskCollection(threadingContext.JoinableTaskContext);
            _asyncTasks.Add(ThreadingContext.JoinableTaskFactory.RunAsync(async() =>
            {
                await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();

                var monitorSelectionService = (IVsMonitorSelection)await asyncServiceProvider.GetServiceAsync(typeof(SVsShellMonitorSelection)).ConfigureAwait(false);

                if (ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out var value)))
                {
                    if (value is IVsWindowFrame windowFrame)
                    {
                        TrackNewActiveWindowFrame(windowFrame);
                    }
                }

                monitorSelectionService.AdviseSelectionEvents(this, out var _);
            }));
        }
        private async Task SubscribeAsync(Microsoft.VisualStudio.Shell.IAsyncServiceProvider serviceProvider)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            _serviceProvider = serviceProvider;

            var commandService = await serviceProvider.GetServiceAsync <IMenuCommandService, IMenuCommandService>(throwOnFailure : false);

            var menuCommandId = new CommandID(CommandSet, CommandId);
            var menuItem      = new OleMenuCommand(
                OnRestorePackages, null, BeforeQueryStatusForPackageRestore, menuCommandId);

            commandService.AddCommand(menuItem);

            _vsMonitorSelection = await serviceProvider.GetServiceAsync <IVsMonitorSelection, IVsMonitorSelection>();

            Assumes.Present(_vsMonitorSelection);

            // get the solution not building and not debugging cookie
            var guidCmdUI = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid;

            _vsMonitorSelection.GetCmdUIContextCookie(
                ref guidCmdUI, out _solutionExistsAndFullyLoadedContextCookie);

            guidCmdUI = VSConstants.UICONTEXT.SolutionExistsAndNotBuildingAndNotDebugging_guid;
            _vsMonitorSelection.GetCmdUIContextCookie(
                ref guidCmdUI, out _solutionNotBuildingAndNotDebuggingContextCookie);
        }
        public static async Task ShowExceptionAsync(IAsyncServiceProvider serviceProvider, string title, Exception ex)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            MessageBox.Show($"An error has occured during conversion: {ex}",
                            title, MessageBoxButton.OK, MessageBoxImage.Error);
        }
Пример #12
0
        public static async Task <(IWpfTextView WpfTextView, CaretPosition CaretPosition)> OpenCodeFileAndNavigateByLineAndCharAsync(
            this Shell.IAsyncServiceProvider serviceProvider,
            Solution solution, string filePath,
            int lineNumber, int character)
        {
            serviceProvider.ThrowOnNull(nameof(serviceProvider));

            if (lineNumber < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(lineNumber));
            }
            else if (character < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(character));
            }

            IWpfTextView wpfTextView = await OpenCodeWindowAsync(serviceProvider, solution, filePath);

            if (wpfTextView == null)
            {
                var(window, textDocument) = await OpenCodeFileNotInSolutionWithDTEAsync(serviceProvider, filePath);

                if (window == null)
                {
                    return(default);
        private static async Task <ITextSelection> GetSelectionInCurrentViewAsync(IAsyncServiceProvider serviceProvider,
                                                                                  Func <string, bool> predicate, bool mustHaveFocus)
        {
            var viewHost = await GetCurrentViewHostAsync(serviceProvider, predicate, mustHaveFocus);

            return(viewHost?.TextView.Selection);
        }
Пример #14
0
        public static async Task InitializeAsync(Shell.IAsyncServiceProvider provider)
        {
            await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            {
                s_ServerId = SERVER_PREFIX;// + System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
                s_PipePool = new PipePool(s_ServerId);
                s_PipePool.Start();
            }
            {
                s_Service = await provider.GetServiceAsync(typeof(SVsShellDebugger)) as IVsDebugger;

                s_DTE = await provider.GetServiceAsync(typeof(SDTE)) as DTE;
            }
            if (s_Service != null)
            {
                s_Service.AdviseDebuggerEvents(Instance, out s_Cookie);
                s_Service.AdviseDebugEventCallback(Instance);
            }
            try
            {
                await Task.Run(() => InitAdresses());
            }
            catch (Exception ex)
            {
                service.Output.WriteError(ex.ToString());
            }
        }
 public InvokeTidyService(Microsoft.VisualStudio.Shell.IAsyncServiceProvider provider)
 {
     // constructor should only be used for simple initialization
     // any usage of Visual Studio service, expensive background operations should happen in the
     // asynchronous InitializeAsync method for best performance
     asyncServiceProvider = provider;
 }
Пример #16
0
        public SolutionRestoreWorker(
            IAsyncServiceProvider asyncServiceProvider,
            Lazy <IVsSolutionManager> solutionManager,
            Lazy <INuGetLockService> lockService,
            Lazy <Common.ILogger> logger,
            Lazy <INuGetErrorList> errorList,
            Lazy <IOutputConsoleProvider> outputConsoleProvider)
        {
            if (asyncServiceProvider == null)
            {
                throw new ArgumentNullException(nameof(asyncServiceProvider));
            }

            if (solutionManager == null)
            {
                throw new ArgumentNullException(nameof(solutionManager));
            }

            if (lockService == null)
            {
                throw new ArgumentNullException(nameof(lockService));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (errorList == null)
            {
                throw new ArgumentNullException(nameof(errorList));
            }

            if (outputConsoleProvider == null)
            {
                throw new ArgumentNullException(nameof(outputConsoleProvider));
            }

            _asyncServiceProvider = asyncServiceProvider;
            _solutionManager      = solutionManager;
            _lockService          = lockService;
            _logger                = logger;
            _errorList             = errorList;
            _outputConsoleProvider = outputConsoleProvider;

            var joinableTaskContextNode = new JoinableTaskContextNode(ThreadHelper.JoinableTaskContext);

            _joinableCollection = joinableTaskContextNode.CreateCollection();
            JoinableTaskFactory = joinableTaskContextNode.CreateFactory(_joinableCollection);

            _componentModel = new AsyncLazy <IComponentModel>(async() =>
            {
                return(await asyncServiceProvider.GetServiceAsync <SComponentModel, IComponentModel>());
            },
                                                              JoinableTaskFactory);
            _solutionLoadedEvent = new AsyncManualResetEvent();
            _isCompleteEvent     = new AsyncManualResetEvent();

            Reset();
        }
Пример #17
0
        internal VSSolutionManager(
            IAsyncServiceProvider asyncServiceProvider,
            IProjectSystemCache projectSystemCache,
            NuGetProjectFactory projectSystemFactory,
            ICredentialServiceProvider credentialServiceProvider,
            IVsProjectAdapterProvider vsProjectAdapterProvider,
            ILogger logger,
            Lazy <ISettings> settings,
            INuGetFeatureFlagService featureFlagService,
            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(featureFlagService);
            Assumes.Present(joinableTaskContext);

            _asyncServiceProvider      = asyncServiceProvider;
            _projectSystemCache        = projectSystemCache;
            _projectSystemFactory      = projectSystemFactory;
            _credentialServiceProvider = credentialServiceProvider;
            _vsProjectAdapterProvider  = vsProjectAdapterProvider;
            _logger             = logger;
            _settings           = settings;
            _featureFlagService = featureFlagService;
            _initLock           = new NuGetLockService(joinableTaskContext);
            _dte             = new(() => asyncServiceProvider.GetDTEAsync(), NuGetUIThreadHelper.JoinableTaskFactory);
            _asyncVSSolution = new(() => asyncServiceProvider.GetServiceAsync <SVsSolution, IVsSolution>(), NuGetUIThreadHelper.JoinableTaskFactory);
        }
 public VisualStudioDecompilerEulaService(
     SVsServiceProvider serviceProvider,
     IThreadingContext threadingContext
     )
 {
     _serviceProvider  = (IAsyncServiceProvider)serviceProvider;
     _threadingContext = threadingContext;
 }
 internal DefaultVSCredentialServiceProvider(
     IAsyncServiceProvider asyncServiceProvider,
     Lazy <INuGetUILogger> outputConsoleLogger
     )
 {
     _asyncServiceProvider = asyncServiceProvider ?? throw new ArgumentNullException(nameof(asyncServiceProvider));
     _outputConsoleLogger  = outputConsoleLogger ?? throw new ArgumentNullException(nameof(outputConsoleLogger));
 }
Пример #20
0
        public static IVsTextView GetTextView(this IAsyncServiceProvider serviceProvider)
        {
            var service     = serviceProvider.GetServiceAsync(typeof(SVsTextManager)).Result;
            var textManager = service as IVsTextManager2;

            textManager.GetActiveView2(1, null, (uint)_VIEWFRAMETYPE.vftCodeWindow, out IVsTextView view);
            return(view);
        }
        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="serviceProvider">Owner package, not null.</param>
        public static async Task InitializeAsync(Microsoft.VisualStudio.Shell.IAsyncServiceProvider serviceProvider)
        {
            Assumes.Present(serviceProvider);

            _instance = new SolutionRestoreCommand();

            await _instance.SubscribeAsync(serviceProvider);
        }
Пример #22
0
 public RoslynVisualStudioWorkspace(
     ExportProvider exportProvider,
     Lazy <IStreamingFindUsagesPresenter> streamingPresenter,
     [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider)
     : base(exportProvider, asyncServiceProvider)
 {
     _streamingPresenter = streamingPresenter;
 }
Пример #23
0
        public NanoDeviceCommService(Microsoft.VisualStudio.Shell.IAsyncServiceProvider provider)
        {
            _serviceProvider = provider;

            // launches the serial client and service
            // create serial instance WITHOUT app associated because we don't care of app life cycle in VS extension
            DebugClient = PortBase.CreateInstanceForSerial("", null);
        }
Пример #24
0
 public CodeConversion(IAsyncServiceProvider serviceProvider, VisualStudioWorkspace visualStudioWorkspace,
                       Func <Task <ConverterOptionsPage> > getOptions, VisualStudioInteraction.OutputWindow outputWindow)
 {
     GetOptions             = getOptions;
     _serviceProvider       = serviceProvider;
     _visualStudioWorkspace = visualStudioWorkspace;
     _outputWindow          = outputWindow;
 }
        private static async Task <Span?> FirstSelectedSpanInCurrentViewPrivateAsync(
            IAsyncServiceProvider serviceProvider,
            Func <string, bool> predicate, bool mustHaveFocus)
        {
            var selection = await GetSelectionInCurrentViewAsync(serviceProvider, predicate, mustHaveFocus);

            return(selection?.SelectedSpans.First().Span);
        }
Пример #26
0
 public RoslynVisualStudioWorkspace(
     ExportProvider exportProvider,
     Lazy <IStreamingFindUsagesPresenter> streamingPresenter,
     [ImportMany] IEnumerable <IDocumentOptionsProviderFactory> documentOptionsProviderFactories,
     [Import(typeof(SVsServiceProvider))] IAsyncServiceProvider asyncServiceProvider)
     : base(exportProvider, asyncServiceProvider, documentOptionsProviderFactories)
 {
     _streamingPresenter = streamingPresenter;
 }
Пример #27
0
    public static async Task InitializeAsync(Shell.IAsyncServiceProvider provider, string name)
    {
        await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

        _output = await provider.GetServiceAsync(typeof(SVsOutputWindow)) as IVsOutputWindow;

        Assumes.Present(_output);
        _name = name;
    }
Пример #28
0
        public VsHierarchyItemManagerProvider([Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider services, JoinableTaskContext context)
        {
            hierarchyManager = new JoinableLazy <IVsHierarchyItemManager>(async() =>
            {
                var componentModel = await services.GetServiceAsync(typeof(SComponentModel)) as IComponentModel;

                return(componentModel?.GetService <IVsHierarchyItemManager>());
            }, context?.Factory, executeOnMainThread: true);
        }
Пример #29
0
        public VisualStudioLogHubLoggerFactory(
            [Import(typeof(SAsyncServiceProvider))] VSShell.IAsyncServiceProvider asyncServiceProvider,
            IThreadingContext threadingContext)
        {
            _asyncServiceProvider = asyncServiceProvider;
            _threadingContext     = threadingContext;

            _wasVSStartedWithLogParameterLazy = new AsyncLazy <bool>(WasVSStartedWithLogParameterAsync, _threadingContext.JoinableTaskFactory);
        }
Пример #30
0
        public async Task InitializeAsync(IAsyncServiceProvider asyncServiceProvider)
        {
            Assumes.Null(_solution);
            Assumes.True(_context.IsOnMainThread, "Must be on UI thread");

            _solution = await asyncServiceProvider.GetServiceAsync <IVsSolution, IVsSolution>();

            Verify.HResult(_solution.AdviseSolutionEvents(this, out _cookie));
        }