public void IServiceProviderExtensions_GetMefServiceAsync_NullArgChecks()
        {
            IAsyncServiceProvider nullServiceProvider = null;

            Exceptions.Expect <ArgumentNullException>(() => nullServiceProvider.GetMefServiceAsync <IService>());
            Exceptions.Expect <ArgumentNullException>(() => IServiceProviderExtensions.GetMefServiceAsync <IService>(nullServiceProvider));
        }
Esempio n. 2
0
        private async Task ShutdownAsync()
        {
            // we are shutting down, cancel any pending work.
            _cancellationTokenSource.Cancel();

            await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (_priorityCommandTargetCookie != VSConstants.VSCOOKIE_NIL)
            {
                var priorityCommandTargetRegistrar = IServiceProviderExtensions.GetService <SVsRegisterPriorityCommandTarget, IVsRegisterPriorityCommandTarget>(_serviceProvider);
                var cookie = _priorityCommandTargetCookie;
                _priorityCommandTargetCookie = VSConstants.VSCOOKIE_NIL;
                var hr = priorityCommandTargetRegistrar.UnregisterPriorityCommandTarget(cookie);

                if (ErrorHandler.Failed(hr))
                {
                    FatalError.ReportWithoutCrash(Marshal.GetExceptionForHR(hr));
                }
            }

            if (_oleComponent != null)
            {
                _oleComponent.Dispose();
                _oleComponent = null;
            }
        }
        public void IServiceProviderExtensions_GetServiceOfTU_NullArgChecks()
        {
            IServiceProvider nullServiceProvider = null;

            Exceptions.Expect <ArgumentNullException>(() => nullServiceProvider.GetService <IService, IOther>());
            Exceptions.Expect <ArgumentNullException>(() => IServiceProviderExtensions.GetService <IService, IOther>(nullServiceProvider));
        }
Esempio n. 4
0
        public bool TryNavigateToSymbol(ISymbol symbol, Project project, NavigationOptions options, CancellationToken cancellationToken)
        {
            if (project == null || symbol == null)
            {
                return(false);
            }

            symbol = symbol.OriginalDefinition;

            // Prefer visible source locations if possible.
            var sourceLocations        = symbol.Locations.Where(loc => loc.IsInSource);
            var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
            var sourceLocation         = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();

            if (sourceLocation != null)
            {
                var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
                if (targetDocument != null)
                {
                    var editorWorkspace   = targetDocument.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetRequiredService <IDocumentNavigationService>();
                    return(navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options, cancellationToken));
                }
            }

            // We don't have a source document, so show the Metadata as Source view in a preview tab.

            if (!_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
            {
                return(false);
            }

            // Should we prefer navigating to the Object Browser over metadata-as-source?
            if (_globalOptions.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
            {
                var libraryService = project.LanguageServices.GetService <ILibraryService>();
                if (libraryService == null)
                {
                    return(false);
                }

                var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                var navInfo     = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
                if (navInfo == null)
                {
                    navInfo = libraryService.NavInfoFactory.CreateForProject(project);
                }

                if (navInfo != null)
                {
                    var navigationTool = IServiceProviderExtensions.GetService <SVsObjBrowser, IVsNavigationTool>(_serviceProvider);
                    return(navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK);
                }

                // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
            }

            // Generate new source or retrieve existing source for the symbol in question
            return(ThreadingContext.JoinableTaskFactory.Run(() => TryNavigateToMetadataAsync(project, symbol, options, cancellationToken)));
        }
Esempio n. 5
0
        private async Task <bool> TryNavigateToMetadataAsync(Project project, ISymbol symbol, OptionSet options, CancellationToken cancellationToken)
        {
            var allowDecompilation = _globalOptions.GetOption(FeatureOnOffOptions.NavigateToDecompiledSources);

            var result = await _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, signaturesOnly : false, allowDecompilation, cancellationToken).ConfigureAwait(false);

            await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var vsRunningDocumentTable4 = IServiceProviderExtensions.GetService <SVsRunningDocumentTable, IVsRunningDocumentTable4>(_serviceProvider);
            var fileAlreadyOpen         = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);

            var openDocumentService = IServiceProviderExtensions.GetService <SVsUIShellOpenDocument, IVsUIShellOpenDocument>(_serviceProvider);

            openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out _, out var windowFrame);

            var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);

            var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);

            // Set the buffer to read only, just in case the file isn't
            ErrorHandler.ThrowOnFailure(vsTextBuffer.GetStateFlags(out var flags));
            flags |= (int)BUFFERSTATEFLAGS.BSF_USER_READONLY;
            ErrorHandler.ThrowOnFailure(vsTextBuffer.SetStateFlags(flags));

            var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);

            if (!fileAlreadyOpen)
            {
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
            }

            windowFrame.Show();

            var openedDocument = textBuffer?.AsTextContainer().GetRelatedDocuments().FirstOrDefault();

            if (openedDocument != null)
            {
                var editorWorkspace   = openedDocument.Project.Solution.Workspace;
                var navigationService = editorWorkspace.Services.GetRequiredService <IDocumentNavigationService>();

                return(navigationService.TryNavigateToSpan(
                           editorWorkspace,
                           openedDocument.Id,
                           result.IdentifierLocation.SourceSpan,
                           options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true),
                           cancellationToken));
            }

            return(true);
        }
Esempio n. 6
0
        public VisualStudioSymbolNavigationService(
            SVsServiceProvider serviceProvider,
            VisualStudio14StructureTaggerProvider outliningTaggerProvider)
            : base(outliningTaggerProvider.ThreadingContext)
        {
            _serviceProvider = serviceProvider;

            var componentModel = IServiceProviderExtensions.GetService <SComponentModel, IComponentModel>(_serviceProvider);

            _editorAdaptersFactory       = componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _metadataAsSourceFileService = componentModel.GetService <IMetadataAsSourceFileService>();
            _sourceGeneratedFileManager  = componentModel.GetService <SourceGeneratedFileManager>();
        }
Esempio n. 7
0
        private void InitializeCore()
        {
            AssertIsForeground();

            // Ensure one of the flights is enabled, otherwise bail
            _experimentationService = _workspace.Services.GetRequiredService <IExperimentationService>();
            if (!_experimentationService.IsExperimentEnabled(ExternalFlightName) && !_experimentationService.IsExperimentEnabled(InternalFlightName))
            {
                return;
            }

            var vsShell = IServiceProviderExtensions.GetService <SVsShell, IVsShell>(_serviceProvider);
            var hr      = vsShell.IsPackageInstalled(ReSharperPackageGuid, out var extensionEnabled);

            if (ErrorHandler.Failed(hr))
            {
                FatalError.ReportWithoutCrash(Marshal.GetExceptionForHR(hr));
                return;
            }

            _resharperExtensionInstalledAndEnabled = extensionEnabled != 0;

            if (_resharperExtensionInstalledAndEnabled)
            {
                // We need to monitor for suspend/resume commands, so create and install the command target and the modal callback.
                var priorityCommandTargetRegistrar = IServiceProviderExtensions.GetService <SVsRegisterPriorityCommandTarget, IVsRegisterPriorityCommandTarget>(_serviceProvider);
                hr = priorityCommandTargetRegistrar.RegisterPriorityCommandTarget(
                    dwReserved: 0 /* from docs must be 0 */,
                    pCmdTrgt: this,
                    pdwCookie: out _priorityCommandTargetCookie);

                if (ErrorHandler.Failed(hr))
                {
                    FatalError.ReportWithoutCrash(Marshal.GetExceptionForHR(hr));
                    return;
                }

                // Initialize the OleComponent to listen for modal changes (which will tell us when Tools->Options is closed)
                _oleComponent = OleComponent.CreateHostedComponent("Keybinding Reset Detector");
                _oleComponent.ModalStateChanged += OnModalStateChanged;
            }

            // run it from background and fire and forget
            StartUpdateStateMachine();
        }
Esempio n. 8
0
        private void RestoreVsKeybindings()
        {
            AssertIsForeground();

            if (_uiShell == null)
            {
                _uiShell = IServiceProviderExtensions.GetService <SVsUIShell, IVsUIShell>(_serviceProvider);
            }

            ErrorHandler.ThrowOnFailure(_uiShell.PostExecCommand(
                                            VSConstants.GUID_VSStandardCommandSet97,
                                            (uint)VSConstants.VSStd97CmdID.CustomizeKeyboard,
                                            (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT,
                                            null));

            KeybindingsResetLogger.Log("KeybindingsReset");

            _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options
                                                                              .WithChangedOption(KeybindingResetOptions.NeedsReset, false)));
        }
Esempio n. 9
0
        public App()
        {
            var c = new ServiceCollection();

            c.AddSingleton(p => Navigation);
            useMobileAppCache();
            Services       = this.SetupDependencies(c);
            Log.Logged    += onLogged;
            Log.QueryAsync = onQueryLogAsync;
            InitializeComponent();
            try
            {
                var navigationPage = new NavigationPage(new MainPage {
                    BindingContext = IServiceProviderExtensions.GetService <MainViewModel>(Services)
                });
                MainPage   = navigationPage;
                Navigation = navigationPage.Navigation;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 10
0
        public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet?options, CancellationToken cancellationToken)
        {
            if (project == null || symbol == null)
            {
                return(false);
            }

            options ??= project.Solution.Options;
            symbol = symbol.OriginalDefinition;

            // Prefer visible source locations if possible.
            var sourceLocations        = symbol.Locations.Where(loc => loc.IsInSource);
            var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
            var sourceLocation         = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();

            if (sourceLocation != null)
            {
                var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
                if (targetDocument != null)
                {
                    var editorWorkspace   = targetDocument.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetRequiredService <IDocumentNavigationService>();
                    return(navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options, cancellationToken));
                }
            }

            // We don't have a source document, so show the Metadata as Source view in a preview tab.

            var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();

            if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
            {
                return(false);
            }

            // Should we prefer navigating to the Object Browser over metadata-as-source?
            if (_globalOptions.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
            {
                var libraryService = project.LanguageServices.GetService <ILibraryService>();
                if (libraryService == null)
                {
                    return(false);
                }

                var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                var navInfo     = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
                if (navInfo == null)
                {
                    navInfo = libraryService.NavInfoFactory.CreateForProject(project);
                }

                if (navInfo != null)
                {
                    var navigationTool = IServiceProviderExtensions.GetService <SVsObjBrowser, IVsNavigationTool>(_serviceProvider);
                    return(navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK);
                }

                // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
            }

            // Generate new source or retrieve existing source for the symbol in question
            var allowDecompilation = false;

            // Check whether decompilation is supported for the project. We currently only support this for C# projects.
            if (project.LanguageServices.GetService <IDecompiledSourceService>() != null)
            {
                allowDecompilation = project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.NavigateToDecompiledSources) && !symbol.IsFromSource();
            }

            var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, allowDecompilation, cancellationToken).WaitAndGetResult(cancellationToken);

            var vsRunningDocumentTable4 = IServiceProviderExtensions.GetService <SVsRunningDocumentTable, IVsRunningDocumentTable4>(_serviceProvider);
            var fileAlreadyOpen         = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);

            var openDocumentService = IServiceProviderExtensions.GetService <SVsUIShellOpenDocument, IVsUIShellOpenDocument>(_serviceProvider);

            openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out var localServiceProvider, out var hierarchy, out var itemId, out var windowFrame);

            var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);

            // The cast from dynamic to object doesn't change semantics, but avoids loading the dynamic binder
            // which saves us JIT time in this method.
            var vsTextBuffer = (IVsTextBuffer)(object)vsRunningDocumentTable4.GetDocumentData(documentCookie);
            var textBuffer   = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);

            if (!fileAlreadyOpen)
            {
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
            }

            windowFrame.Show();

            var openedDocument = textBuffer?.AsTextContainer().GetRelatedDocuments().FirstOrDefault();

            if (openedDocument != null)
            {
                var editorWorkspace   = openedDocument.Project.Solution.Workspace;
                var navigationService = editorWorkspace.Services.GetRequiredService <IDocumentNavigationService>();

                return(navigationService.TryNavigateToSpan(
                           editorWorkspace,
                           openedDocument.Id,
                           result.IdentifierLocation.SourceSpan,
                           options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true),
                           cancellationToken));
            }

            return(true);
        }
Esempio n. 11
0
        public bool ExecuteCommand(SyncClassViewCommandArgs args, CommandExecutionContext context)
        {
            this.AssertIsForeground();

            var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1;

            if (caretPosition < 0)
            {
                return(false);
            }

            var snapshot = args.SubjectBuffer.CurrentSnapshot;

            using var waitScope = context.OperationContext.AddScope(
                      allowCancellation: true,
                      string.Format(ServicesVSResources.Synchronizing_with_0, ClassView)
                      );
            var document = snapshot
                           .GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync(
                context.OperationContext
                )
                           .WaitAndGetResult(context.OperationContext.UserCancellationToken);

            if (document == null)
            {
                return(true);
            }

            var syntaxFactsService = document.GetLanguageService <ISyntaxFactsService>();

            if (syntaxFactsService == null)
            {
                return(true);
            }

            var libraryService = document.GetLanguageService <ILibraryService>();

            if (libraryService == null)
            {
                return(true);
            }

            var userCancellationToken = context.OperationContext.UserCancellationToken;
            var semanticModel         = document
                                        .GetSemanticModelAsync(userCancellationToken)
                                        .WaitAndGetResult(userCancellationToken);

            var root = semanticModel.SyntaxTree
                       .GetRootAsync(userCancellationToken)
                       .WaitAndGetResult(userCancellationToken);

            var memberDeclaration = syntaxFactsService.GetContainingMemberDeclaration(
                root,
                caretPosition
                );

            var symbol =
                memberDeclaration != null
                    ? semanticModel.GetDeclaredSymbol(memberDeclaration, userCancellationToken)
                    : null;

            while (symbol != null && !IsValidSymbolToSynchronize(symbol))
            {
                symbol = symbol.ContainingSymbol;
            }

            IVsNavInfo navInfo = null;

            if (symbol != null)
            {
                navInfo = libraryService.NavInfoFactory.CreateForSymbol(
                    symbol,
                    document.Project,
                    semanticModel.Compilation,
                    useExpandedHierarchy: true
                    );
            }

            if (navInfo == null)
            {
                navInfo = libraryService.NavInfoFactory.CreateForProject(document.Project);
            }

            if (navInfo == null)
            {
                return(true);
            }

            var navigationTool = IServiceProviderExtensions.GetService <
                SVsClassView,
                IVsNavigationTool
                >(_serviceProvider);

            navigationTool.NavigateToNavInfo(navInfo);
            return(true);
        }
Esempio n. 12
0
 public void GetRequiredServiceFailsWithNullThis()
 {
     Assert.Throws <ArgumentNullException>(() => IServiceProviderExtensions.GetRequiredService <object>(null));
 }
Esempio n. 13
0
        /// <summary>
        /// Returns true if ReSharper is installed, enabled, and not suspended.
        /// </summary>
        private async ValueTask <ReSharperStatus> IsReSharperRunningAsync(CancellationToken cancellationToken)
        {
            // Quick exit if resharper is either uninstalled or not enabled
            if (!_resharperExtensionInstalledAndEnabled)
            {
                return(ReSharperStatus.NotInstalledOrDisabled);
            }

            await EnsureOleCommandTargetAsync().ConfigureAwait(false);

            // poll until either suspend or resume botton is available, or until operation is canceled
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var suspendFlag = await QueryStatusAsync(SuspendId).ConfigureAwait(false);

                // In the case of an error when attempting to get the status, pretend that ReSharper isn't enabled. We also
                // shut down monitoring so we don't keep hitting this.
                if (suspendFlag == 0)
                {
                    return(ReSharperStatus.NotInstalledOrDisabled);
                }

                var resumeFlag = await QueryStatusAsync(ResumeId).ConfigureAwait(false);

                if (resumeFlag == 0)
                {
                    return(ReSharperStatus.NotInstalledOrDisabled);
                }

                // When ReSharper is running, the ReSharper_Suspend command is Enabled and not Invisible
                if (suspendFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !suspendFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE))
                {
                    return(ReSharperStatus.Enabled);
                }

                // When ReSharper is suspended, the ReSharper_Resume command is Enabled and not Invisible
                if (resumeFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !resumeFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE))
                {
                    return(ReSharperStatus.Suspended);
                }

                // ReSharper has not finished initializing, so try again later
                await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false);
            }

            async Task <OLECMDF> QueryStatusAsync(uint cmdId)
            {
                var cmds = new OLECMD[1];

                cmds[0].cmdID = cmdId;
                cmds[0].cmdf  = 0;

                await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                var hr = _oleCommandTarget.QueryStatus(ReSharperCommandGroup, (uint)cmds.Length, cmds, IntPtr.Zero);

                if (ErrorHandler.Failed(hr))
                {
                    FatalError.ReportWithoutCrash(Marshal.GetExceptionForHR(hr));
                    await ShutdownAsync().ConfigureAwait(false);

                    return(0);
                }

                return((OLECMDF)cmds[0].cmdf);
            }

            async Task EnsureOleCommandTargetAsync()
            {
                if (_oleCommandTarget != null)
                {
                    return;
                }

                await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                _oleCommandTarget = IServiceProviderExtensions.GetService <SUIHostCommandDispatcher, IOleCommandTarget>(_serviceProvider);
            }
        }