/////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);

            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var componentModel = (IComponentModel) await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true);

            var menuCommandService = (IMenuCommandService) await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true);

            cancellationToken.ThrowIfCancellationRequested();

            Assumes.Present(componentModel);
            Assumes.Present(menuCommandService);

            _threadingContext = componentModel.GetService <IThreadingContext>();

            var workspace = componentModel.GetService <VisualStudioWorkspace>();

            _forceLowMemoryMode = new ForceLowMemoryMode(workspace.Services.GetService <IOptionService>());

            // Add our command handlers for menu (commands must exist in the .vsct file)
            if (menuCommandService is OleMenuCommandService mcs)
            {
                // Create the command for the tool window
                CommandID   toolwndCommandID = new CommandID(GuidList.guidVisualStudioDiagnosticsWindowCmdSet, (int)PkgCmdIDList.CmdIDRoslynDiagnosticWindow);
                MenuCommand menuToolWin      = new MenuCommand(ShowToolWindow, toolwndCommandID);
                mcs.AddCommand(menuToolWin);
            }

            // set logger at start up
            var optionService = componentModel.GetService <IGlobalOptionService>();
            var remoteService = workspace.Services.GetService <IRemoteHostClientService>();

            PerformanceLoggersPage.SetLoggers(optionService, _threadingContext, remoteService);
        }
Exemple #2
0
        public SolutionRestoreJob(
            [Import(typeof(SVsServiceProvider))]
            IServiceProvider serviceProvider,
            IPackageRestoreManager packageRestoreManager,
            IVsSolutionManager solutionManager,
            ISourceRepositoryProvider sourceRepositoryProvider,
            IRestoreEventsPublisher restoreEventsPublisher,
            ISettings settings)
        {
            Assumes.Present(serviceProvider);
            Assumes.Present(packageRestoreManager);
            Assumes.Present(solutionManager);
            Assumes.Present(sourceRepositoryProvider);
            Assumes.Present(restoreEventsPublisher);
            Assumes.Present(settings);

            _serviceProvider          = serviceProvider;
            _packageRestoreManager    = packageRestoreManager;
            _solutionManager          = solutionManager;
            _sourceRepositoryProvider = sourceRepositoryProvider;
            _restoreEventsPublisher   = restoreEventsPublisher;
            _settings = settings;
            _packageRestoreConsent = new PackageRestoreConsent(_settings);
        }
        public RemoteLanguageServiceWorkspace(ExportProvider exportProvider,
                                              IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
                                              SVsServiceProvider serviceProvider,
                                              IDiagnosticService diagnosticService,
                                              ITableManagerProvider tableManagerProvider,
                                              IThreadingContext threadingContext)
            : base(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.AnyCodeRoslynWorkspace)

        {
            _serviceProvider = serviceProvider;

            _remoteDiagnosticListTable = new RemoteDiagnosticListTable(serviceProvider, this, diagnosticService, tableManagerProvider);

            var componentModel = _serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;

            Assumes.Present(componentModel);

            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

            var runningDocumentTable = (IVsRunningDocumentTable)serviceProvider.GetService(typeof(SVsRunningDocumentTable));

            _runningDocumentTableEventTracker = new RunningDocumentTableEventTracker(threadingContext, editorAdaptersFactoryService, runningDocumentTable, this);
            _threadingContext = threadingContext;
        }
Exemple #4
0
        internal void ShowMessageBox(string message, bool isError = false)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IVsUIShell uiShell = (IVsUIShell)this.GetService(typeof(SVsUIShell));

            Assumes.Present(uiShell);
            Guid clsid = Guid.Empty;

            // This has a pszTitle parameter, but it isn't used for the MessageBox's title.
            // VS just appends the pszTitle to the front of the pszText and separates it
            // with a couple of newlines.
            ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(
                                            0,
                                            ref clsid,
                                            string.Empty,
                                            message,
                                            string.Empty,
                                            0,
                                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                                            isError ? OLEMSGICON.OLEMSGICON_CRITICAL : OLEMSGICON.OLEMSGICON_INFO,
                                            0, // false
                                            out _));
        }
Exemple #5
0
        public async Task <NuGetProject> TryCreateNuGetProjectAsync(
            IVsProjectAdapter vsProjectAdapter,
            ProjectProviderContext context,
            bool forceProjectType)
        {
            Assumes.Present(vsProjectAdapter);

            await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

            var projectServices = await TryCreateProjectServicesAsync(
                vsProjectAdapter,
                forceCreate : forceProjectType);

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

            return(new LegacyPackageReferenceProject(
                       vsProjectAdapter,
                       vsProjectAdapter.ProjectId,
                       projectServices,
                       _threadingService));
        }
Exemple #6
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);

            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            _componentModel = (IComponentModel) await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true);

            cancellationToken.ThrowIfCancellationRequested();
            Assumes.Present(_componentModel);

            // Fetch the session synchronously on the UI thread; if this doesn't happen before we try using this on
            // the background thread then we will experience hangs like we see in this bug:
            // https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=190808 or
            // https://devdiv.visualstudio.com/DevDiv/_workitems?id=296981&_a=edit
            var telemetrySession = TelemetryService.DefaultSession;

            WatsonReporter.InitializeFatalErrorHandlers(telemetrySession);

            // Ensure the options persisters are loaded since we have to fetch options from the shell
            _componentModel.GetExtensions <IOptionPersister>();

            _workspace = _componentModel.GetService <VisualStudioWorkspace>();
            _workspace.Services.GetService <IExperimentationService>();

            RoslynTelemetrySetup.Initialize(this, telemetrySession);

            InitializeColors();

            // load some services that have to be loaded in UI thread
            LoadComponentsInUIContextOnceSolutionFullyLoadedAsync(cancellationToken).Forget();

            _solutionEventMonitor = new SolutionEventMonitor(_workspace);

            TrackBulkFileOperations();
        }
Exemple #7
0
        /// <summary>
        /// Retrieves the value or body of a macro based on the macro's name.
        /// </summary>
        /// <param name="bstrBuildMacroName">String containing the name of the macro.</param>
        /// <param name="pbstrBuildMacroValue">String containing the value or body of the macro.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public int GetBuildMacroValue(string bstrBuildMacroName, out string?pbstrBuildMacroValue)
        {
            if (_configuredProject == null)
            {
                pbstrBuildMacroValue = null;
                return(HResult.Unexpected);
            }

            Assumes.Present(_configuredProject.Value.Services.ProjectPropertiesProvider);

            pbstrBuildMacroValue = null;
            ProjectSystem.Properties.IProjectProperties commonProperties = _configuredProject.Value.Services.ProjectPropertiesProvider.GetCommonProperties();
            pbstrBuildMacroValue = _threadingService?.ExecuteSynchronously(() => commonProperties.GetEvaluatedPropertyValueAsync(bstrBuildMacroName));

            if (string.IsNullOrEmpty(pbstrBuildMacroValue))
            {
                pbstrBuildMacroValue = string.Empty;
                return(HResult.Fail);
            }
            else
            {
                return(HResult.OK);
            }
        }
        async Task <CloneDialogResult> ShowCloneDialogAsync(IProgress <ServiceProgressData> downloadProgress,
                                                            CancellationToken cancellationToken, string url = null)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var componentModel = await ServiceProvider.GetGlobalServiceAsync <SComponentModel, IComponentModel>();

            Assumes.Present(componentModel);
            var compositionServices = componentModel.DefaultExportProvider.GetExportedValue <CompositionServices>();
            var exportProvider      = compositionServices.GetExportProvider();

            var dialogService     = exportProvider.GetExportedValue <IDialogService>();
            var cloneDialogResult = await dialogService.ShowCloneDialog(null, url);

            if (cloneDialogResult != null)
            {
                var repositoryCloneService = exportProvider.GetExportedValue <IRepositoryCloneService>();
                await repositoryCloneService.CloneOrOpenRepository(cloneDialogResult, downloadProgress, cancellationToken);

                return(cloneDialogResult);
            }

            return(null);
        }
Exemple #9
0
        public static async Task AdjustFontSizeAsync(string categoryGuid, short change)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsFontAndColorStorage storage = await VS.Shell.GetFontAndColorStorageAsync();

            Assumes.Present(storage);
            // ReSharper disable once SuspiciousTypeConversion.Global
            var utilities = storage as IVsFontAndColorUtilities;

            if (utilities == null)
            {
                return;
            }

            var pLOGFONT = new LOGFONTW[1];
            var pInfo    = new FontInfo[1];
            var category = new Guid(categoryGuid);

            ErrorHandler.ThrowOnFailure(storage.OpenCategory(category, (uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES)));
            try
            {
                if (!ErrorHandler.Succeeded(storage.GetFont(pLOGFONT, pInfo)))
                {
                    return;
                }

                pInfo[0].wPointSize = checked ((ushort)(pInfo[0].wPointSize + change));
                ErrorHandler.ThrowOnFailure(storage.SetFont(pInfo));
                ErrorHandler.ThrowOnFailure(utilities.FreeFontInfo(pInfo));
            }
            finally
            {
                storage.CloseCategory();
            }
        }
Exemple #10
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true);

            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var shell = (IVsShell) await GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true);

            _componentModel = (IComponentModel) await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true);

            var menuCommandService = (OleMenuCommandService) await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true);

            cancellationToken.ThrowIfCancellationRequested();
            Assumes.Present(shell);
            Assumes.Present(_componentModel);
            Assumes.Present(menuCommandService);

            // Set both handlers to non-fatal Watson. Never fail-fast the VS process.
            // Any exception that is not recovered from shall be propagated.
            var nonFatalHandler = new Action <Exception>(WatsonReporter.ReportNonFatal);
            var fatalHandler    = nonFatalHandler;

            InteractiveHostFatalError.Handler         = fatalHandler;
            InteractiveHostFatalError.NonFatalHandler = nonFatalHandler;

            // Load the Roslyn package so that its FatalError handlers are hooked up.
            shell.LoadPackage(Guids.RoslynPackageId, out var roslynPackage);

            // Explicitly set up FatalError handlers for the InteractiveWindowPackage.
            SetErrorHandlers(typeof(IInteractiveWindow).Assembly, fatalHandler, nonFatalHandler);
            SetErrorHandlers(typeof(IVsInteractiveWindow).Assembly, fatalHandler, nonFatalHandler);

            _interactiveWindowProvider = _componentModel.DefaultExportProvider.GetExportedValue <TVsInteractiveWindowProvider>();

            InitializeMenuCommands(menuCommandService);
        }
    public async Task ClientCanWriteAndReadFromTwoWayStream()
    {
        var remoteStream = await this.clientRpc.InvokeAsync <Stream>(nameof(Server.ServerMethodThatWritesAndReadsFromTwoWayStream));

        Assumes.Present(remoteStream);

        var readOnlyStream  = new StreamReader(remoteStream);
        var writeOnlyStream = new StreamWriter(remoteStream);

        // Read server message
        var serverReply = await readOnlyStream.ReadLineAsync().ConfigureAwait(false);

        Assert.Equal("Streamed bits!", serverReply);

        // Verify server received client response
        await writeOnlyStream.WriteLineAsync("Returned bytes").ConfigureAwait(false);

        await writeOnlyStream.FlushAsync().WithCancellation(this.TimeoutToken);

        Assumes.NotNull(this.server.ChatLaterTask);
        await this.server.ChatLaterTask.WithCancellation(this.TimeoutToken);

        remoteStream.Dispose();
    }
Exemple #12
0
        private void InitializeOptions(ITextBuffer textBuffer)
        {
            // Ideally we would initialize options based on Razor specific options in the context menu.
            // But since we don't have support for that yet, we will temporarily use the settings from Html.

            var textManager = _serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager2;

            Assumes.Present(textManager);

            var langPrefs2 = new LANGPREFERENCES2[] { new LANGPREFERENCES2()
                                                      {
                                                          guidLang = HtmlLanguageServiceGuid
                                                      } };

            if (VSConstants.S_OK == textManager.GetUserPreferences2(null, null, langPrefs2, null))
            {
                var insertSpaces = langPrefs2[0].fInsertTabs == 0;
                var tabSize      = langPrefs2[0].uTabSize;

                var razorOptions = _editorOptionsFactory.GetOptions(textBuffer);
                razorOptions.SetOptionValue(DefaultOptions.ConvertTabsToSpacesOptionId, insertSpaces);
                razorOptions.SetOptionValue(DefaultOptions.TabSizeOptionId, (int)tabSize);
            }
        }
Exemple #13
0
        private async Task StartStopRestartAsync(bool isReload)
        {
            try {
                if (isReload)
                {
                    isReloading = true;
                }
                OnStopping();
                await StopAsync?.InvokeAsync(this, EventArgs.Empty);

                OnStopped();
                await StartAsync?.InvokeAsync(this, EventArgs.Empty);

                var componentModel = ServiceProvider.GetService(typeof(SComponentModel)) as IComponentModel;
                Assumes.Present(componentModel);

                var agentService = componentModel.GetService <ICodeStreamAgentService>();
                await agentService.ReinitializeAsync();

                Interlocked.Exchange(ref _state, 1);
                Log.Debug($"SetState={_state}");
            }
            catch (NullReferenceException ex) {
                Log.LocalWarning(ex?.Message);
            }
            catch (Exception ex) {
                Log.Error(ex, nameof(RestartAsync));
            }
            finally {
                if (isReload)
                {
                    isReloading = false;
                }
            }
            await Task.CompletedTask;
        }
Exemple #14
0
        /// <summary>
        /// Restarts the LSP agent based on the currently registered LSP manager
        /// </summary>
        /// <returns></returns>
        private async System.Threading.Tasks.Task RestartLanguageServerAsync()
        {
            try {
                var componentModel = _serviceProvider.GetService(typeof(SComponentModel)) as IComponentModel;
                Assumes.Present(componentModel);
                if (componentModel == null)
                {
                    Log.Error(nameof(componentModel) + " is null");
                }

                var languageServerClientManager = componentModel.GetService <ILanguageServerClientManager>();
                if (languageServerClientManager != null)
                {
                    await languageServerClientManager.RestartAsync();
                }
                else
                {
                    Log.IsNull(nameof(ILanguageServerClientManager));
                }
            }
            catch (Exception ex) {
                Log.Error(ex, nameof(RestartLanguageServerAsync));
            }
        }
Exemple #15
0
        public async Task <ActiveConfiguredObjects <ProjectConfiguration>?> GetActiveProjectConfigurationsAsync()
        {
            ProjectConfiguration?activeSolutionConfiguration = _services.ActiveConfiguredProjectProvider?.ActiveProjectConfiguration;

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

            IProjectConfigurationsService?projectConfigurationsService = _services.ProjectConfigurationsService;

            Assumes.Present(projectConfigurationsService);

            IImmutableSet <ProjectConfiguration> configurations = await projectConfigurationsService.GetKnownProjectConfigurationsAsync();

            var builder = PooledArray <ProjectConfiguration> .GetInstance();

            IImmutableSet <string> dimensionNames = GetDimensionNames();

            foreach (ProjectConfiguration configuration in configurations)
            {
                if (IsActiveConfigurationCandidate(activeSolutionConfiguration, configuration, dimensionNames))
                {
                    builder.Add(configuration);
                }
            }

            if (builder.Count == 0)
            {
                // Active config is different to the known configs,
                // however we should still return it
                builder.Add(activeSolutionConfiguration);
            }

            return(new ActiveConfiguredObjects <ProjectConfiguration>(builder.ToImmutableAndFree(), dimensionNames));
        }
        public LegacyPackageReferenceRestoreUtilityTests(DispatcherThreadFixture fixture)
        {
            Assumes.Present(fixture);

            _threadingService = new TestProjectThreadingService(fixture.JoinableTaskFactory);
        }
        public static void Log(IServiceProvider serviceProvider, string path)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));

            Assumes.Present(componentModel);
            var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(SDTE));

            var workspace = componentModel.GetService <VisualStudioWorkspace>();
            var solution  = workspace.CurrentSolution;

            var threadedWaitDialog = (IVsThreadedWaitDialog3)serviceProvider.GetService(typeof(SVsThreadedWaitDialog));

            Assumes.Present(threadedWaitDialog);
            var threadedWaitCallback = new ThreadedWaitCallback();

            int projectsProcessed = 0;

            threadedWaitDialog.StartWaitDialogWithCallback(RoslynLoggingResources.ProjectSystemTools, RoslynLoggingResources.LoggingRoslynWorkspaceStructure, null, null, null, true, 0, true, solution.ProjectIds.Count, 0, threadedWaitCallback);
            var cancellationToken = threadedWaitCallback.CancellationToken;

            try
            {
                var document         = new XDocument();
                var workspaceElement = new XElement("workspace");
                workspaceElement.SetAttributeValue("kind", workspace.Kind);
                document.Add(workspaceElement);

                foreach (var project in solution.GetProjectDependencyGraph().GetTopologicallySortedProjects(threadedWaitCallback.CancellationToken).Select(solution.GetProject))
                {
                    // Dump basic project attributes
                    var projectElement = new XElement("project");
                    workspaceElement.Add(projectElement);

                    projectElement.SetAttributeValue("id", SanitizePath(project.Id.ToString()));
                    projectElement.SetAttributeValue("name", project.Name);
                    projectElement.SetAttributeValue("assemblyName", project.AssemblyName);
                    projectElement.SetAttributeValue("language", project.Language);
                    projectElement.SetAttributeValue("path", SanitizePath(project.FilePath ?? "(none)"));
                    projectElement.SetAttributeValue("outputPath", SanitizePath(project.OutputFilePath ?? "(none)"));

                    var hasSuccesfullyLoaded = TryGetHasSuccessfullyLoaded(project, cancellationToken);

                    if (hasSuccesfullyLoaded.HasValue)
                    {
                        projectElement.SetAttributeValue("hasSuccessfullyLoaded", hasSuccesfullyLoaded.Value);
                    }

                    // Dump MSBuild <Reference> nodes
                    if (project.FilePath != null)
                    {
                        var msbuildProject   = XDocument.Load(project.FilePath);
                        var msbuildNamespace = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");

                        var msbuildReferencesElement = new XElement("msbuildReferences");
                        projectElement.Add(msbuildReferencesElement);

                        msbuildReferencesElement.Add(msbuildProject.Descendants(msbuildNamespace + "ProjectReference"));
                        msbuildReferencesElement.Add(msbuildProject.Descendants(msbuildNamespace + "Reference"));
                        msbuildReferencesElement.Add(msbuildProject.Descendants(msbuildNamespace + "ReferencePath"));
                    }

                    // Dump DTE references
                    var langProjProject = TryFindLangProjProject(dte, project);

                    if (langProjProject != null)
                    {
                        var dteReferences = new XElement("dteReferences");
                        projectElement.Add(dteReferences);

                        foreach (var reference in langProjProject.References.Cast <VSLangProj.Reference>())
                        {
                            if (reference.SourceProject != null)
                            {
                                dteReferences.Add(new XElement("projectReference", new XAttribute("projectName", reference.SourceProject.Name)));
                            }
                            else
                            {
                                dteReferences.Add(new XElement("metadataReference",
                                                               reference.Path != null ? new XAttribute("path", SanitizePath(reference.Path)) : null,
                                                               new XAttribute("name", reference.Name)));
                            }
                        }
                    }

                    // Dump the actual metadata references in the workspace
                    var workspaceReferencesElement = new XElement("workspaceReferences");
                    projectElement.Add(workspaceReferencesElement);

                    foreach (var metadataReference in project.MetadataReferences)
                    {
                        workspaceReferencesElement.Add(CreateElementForPortableExecutableReference(metadataReference));
                    }

                    // Dump project references in the workspace
                    foreach (var projectReference in project.AllProjectReferences)
                    {
                        var referenceElement = new XElement("projectReference", new XAttribute("id", SanitizePath(projectReference.ProjectId.ToString())));

                        if (!project.ProjectReferences.Contains(projectReference))
                        {
                            referenceElement.SetAttributeValue("missingInSolution", "true");
                        }

                        workspaceReferencesElement.Add(referenceElement);
                    }

                    projectElement.Add(new XElement("workspaceDocuments", CreateElementsForDocumentCollection(project.Documents, "document", cancellationToken)));
                    projectElement.Add(new XElement("workspaceAdditionalDocuments", CreateElementsForDocumentCollection(project.AdditionalDocuments, "additionalDocuments", cancellationToken)));

                    // Read AnalyzerConfigDocuments via reflection, as our target version may not be on a Roslyn
                    // new enough to support it.
                    var analyzerConfigDocumentsProperty = project.GetType().GetProperty("AnalyzerConfigDocuments");

                    if (analyzerConfigDocumentsProperty != null)
                    {
                        var analyzerConfigDocuments = (IEnumerable <TextDocument>)analyzerConfigDocumentsProperty.GetValue(project);
                        projectElement.Add(new XElement("workspaceAnalyzerConfigDocuments", CreateElementsForDocumentCollection(analyzerConfigDocuments, "analyzerConfigDocument", cancellationToken)));
                    }

                    // Dump references from the compilation; this should match the workspace but can help rule out
                    // cross-language reference bugs or other issues like that
#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits -- this is fine since it's a Roslyn API
                    var compilation = project.GetCompilationAsync(cancellationToken).Result;
#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits

                    if (compilation != null)
                    {
                        var compilationReferencesElement = new XElement("compilationReferences");
                        projectElement.Add(compilationReferencesElement);

                        foreach (var reference in compilation.References)
                        {
                            compilationReferencesElement.Add(CreateElementForPortableExecutableReference(reference));
                        }

                        projectElement.Add(CreateElementForCompilation(compilation));

                        // Dump all diagnostics
                        var diagnosticsElement = new XElement("diagnostics");
                        projectElement.Add(diagnosticsElement);

                        foreach (var diagnostic in compilation.GetDiagnostics(cancellationToken))
                        {
                            diagnosticsElement.Add(
                                new XElement("diagnostic",
                                             new XAttribute("id", diagnostic.Id),
                                             new XAttribute("severity", diagnostic.Severity.ToString()),
                                             new XAttribute("path", SanitizePath(diagnostic.Location.GetLineSpan().Path ?? "(none)")),
                                             diagnostic.GetMessage()));
                        }
                    }

                    projectsProcessed++;

                    bool cancelled;
                    threadedWaitDialog.UpdateProgress(null, null, null, projectsProcessed, solution.ProjectIds.Count, false, out cancelled);
                }

                File.Delete(path);

                using (var zipFile = ZipFile.Open(path, ZipArchiveMode.Create))
                {
                    var zipFileEntry = zipFile.CreateEntry("Workspace.xml", CompressionLevel.Fastest);
                    using (var stream = zipFileEntry.Open())
                    {
                        document.Save(stream);
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // They cancelled
            }
            finally
            {
                int cancelled;
                threadedWaitDialog.EndWaitDialog(out cancelled);
            }
        }
Exemple #18
0
        public SolutionRestoreBuildHandlerTests(DispatcherThreadFixture fixture)
        {
            Assumes.Present(fixture);

            _jtf = fixture.JoinableTaskFactory;
        }
 public ProjectApiUser()
 {
     this.projectSystemQueryService = ProjectApiUserVsixPackage.QueryService;
     Assumes.Present <IProjectSystemQueryService>(this.projectSystemQueryService);
 }
Exemple #20
0
        async Task <object> CreateService(IAsyncServiceContainer container, CancellationToken cancellationToken, Type serviceType)
        {
            if (serviceType == null)
            {
                return(null);
            }

            if (container != this)
            {
                return(null);
            }

            if (serviceType == typeof(IGitHubServiceProvider))
            {
                //var sp = await GetServiceAsync(typeof(SVsServiceProvider)) as IServiceProvider;
                var result = new GitHubServiceProvider(this, this);
                await result.Initialize();

                return(result);
            }
            else if (serviceType == typeof(ILoginManager))
            {
                // These services are got through MEF and we will take a performance hit if ILoginManager is requested during
                // InitializeAsync. TODO: We can probably make LoginManager a normal MEF component rather than a service.
                var serviceProvider = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                Assumes.Present(serviceProvider);

                var keychain      = serviceProvider.GetService <IKeychain>();
                var oauthListener = serviceProvider.GetService <IOAuthCallbackListener>();

                // HACK: We need to make sure this is run on the main thread. We really
                // shouldn't be injecting a view model concern into LoginManager - this
                // needs to be refactored. See #1398.
#pragma warning disable VSTHRD011 // Use AsyncLazy<T>
                var lazy2Fa = new Lazy <ITwoFactorChallengeHandler>(() =>
                                                                    ThreadHelper.JoinableTaskFactory.Run(async() =>
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                    return(serviceProvider.GetService <ITwoFactorChallengeHandler>());
                }));
#pragma warning restore VSTHRD011 // Use AsyncLazy<T>

                return(new LoginManager(
                           keychain,
                           lazy2Fa,
                           oauthListener,
                           ApiClientConfiguration.ClientId,
                           ApiClientConfiguration.ClientSecret,
                           ApiClientConfiguration.MinimumScopes,
                           ApiClientConfiguration.RequestedScopes,
                           ApiClientConfiguration.AuthorizationNote,
                           ApiClientConfiguration.MachineFingerprint));
            }
            else if (serviceType == typeof(IUsageService))
            {
                var sp = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                Assumes.Present(sp);

                var environment = new Rothko.Environment();
                return(new UsageService(sp, environment));
            }
            else if (serviceType == typeof(IUsageTracker))
            {
                var usageService = await GetServiceAsync(typeof(IUsageService)) as IUsageService;

                var serviceProvider = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                var settings = await GetServiceAsync(typeof(IPackageSettings)) as IPackageSettings;

                Assumes.Present(usageService);
                Assumes.Present(serviceProvider);
                Assumes.Present(settings);

                return(new UsageTracker(serviceProvider, usageService, settings));
            }
            else if (serviceType == typeof(IVSGitExt))
            {
                var vsVersion = ApplicationInfo.GetHostVersionInfo().FileMajorPart;
                return(new VSGitExtFactory(vsVersion, this, GitService.GitServiceHelper).Create());
            }
            else if (serviceType == typeof(IGitHubToolWindowManager))
            {
                return(this);
            }
            else if (serviceType == typeof(IPackageSettings))
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var sp = new ServiceProvider(Services.Dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
                return(new PackageSettings(sp));
            }
            else if (serviceType == typeof(ITippingService))
            {
                return(new TippingService(this));
            }
            // go the mef route
            else
            {
                var sp = await GetServiceAsync(typeof(IGitHubServiceProvider)) as IGitHubServiceProvider;

                Assumes.Present(sp);

                return(sp.TryGetService(serviceType));
            }
        }
        public int CreateEditorInstance(uint vsCreateEditorFlags, string fileName, string physicalView,
                                        IVsHierarchy hierarchy, uint itemid, IntPtr existingDocData,
                                        out IntPtr docView, out IntPtr docData,
                                        out string caption, out Guid cmdUIGuid, out int flags)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            object docViewObject = null;

            docView   = IntPtr.Zero;
            docData   = IntPtr.Zero;
            caption   = null;
            cmdUIGuid = Guid.Empty;
            flags     = 0;

            if ((vsCreateEditorFlags & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }

            try
            {
                object docDataObject;

                // if needed create our DocData object
                if (existingDocData == IntPtr.Zero)
                {
                    ILocalRegistry localRegistry = serviceProvider.GetService(typeof(SLocalRegistry)) as ILocalRegistry;
                    Assumes.Present(localRegistry);

                    Guid   guidUnknown = VSConstants.IID_IUnknown;
                    IntPtr newDocDataPtr;
                    ErrorHandler.ThrowOnFailure(localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref guidUnknown, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out newDocDataPtr));

                    try
                    {
                        docDataObject = Marshal.GetObjectForIUnknown(newDocDataPtr);
                    }
                    finally
                    {
                        Marshal.Release(newDocDataPtr);
                    }

                    IObjectWithSite ows = docDataObject as IObjectWithSite;
                    if (ows != null)
                    {
                        ows.SetSite(this.site);
                    }
                }
                else
                {
                    // if document is already open
                    docDataObject = Marshal.GetObjectForIUnknown(existingDocData);
                    IVsTextLines textLines = docDataObject as IVsTextLines;
                    Marshal.Release(existingDocData);

                    if (textLines == null)
                    {
                        return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                    }
                }

                docViewObject = this.CreateDocView(this.serviceProvider, hierarchy, itemid, fileName, docDataObject, out cmdUIGuid);
                Debug.Assert(docViewObject != null);

                // todo: maybe check to see if we need to add readonly to caption?
                caption = "";

                docView       = Marshal.GetIUnknownForObject(docViewObject);
                docData       = Marshal.GetIUnknownForObject(docDataObject);
                docViewObject = null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                // if we have a disposable view here, clean it up
                IDisposable disposableView;
                if ((disposableView = docViewObject as IDisposable) != null)
                {
                    disposableView.Dispose();
                }
            }

            return(VSConstants.S_OK);
        }
        /// <summary>
        /// Invoked when the UnconfiguredProject is first loaded to initialize language services.
        /// </summary>
        protected async Task InitializeAsync()
        {
            ProjectAsynchronousTasksService.UnloadCancellationToken.ThrowIfCancellationRequested();

            // Don't start until the project has been loaded as far as the IDE is concerned.
#pragma warning disable CA2007 // Do not directly await a Task (see https://github.com/dotnet/roslyn/issues/6770)
            await ProjectAsyncLoadDashboard.ProjectLoadedInHost;
#pragma warning restore CA2007 // Do not directly await a Task

            // Defer this work until VS has idle time.  Otherwise we'll block the UI thread to load the MSBuild project evaluation
            // during synchronous project load time.
            await ThreadHelper.JoinableTaskFactory.RunAsync(
                VsTaskRunContext.UIThreadBackgroundPriority,
                async delegate
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                await Task.Yield();

                using (ProjectAsynchronousTasksService.LoadedProject())
                {
                    // hack to ensure webproj package is properly sited, by forcing it to load with a QueryService call for
                    // one of the services it implements.
                    var tmpObj = Package.GetGlobalService(typeof(SWebApplicationCtxSvc)) as IWebApplicationCtxSvc;
                    Report.IfNotPresent(tmpObj);
                    if (tmpObj == null)
                    {
                        return;
                    }

                    // Create the Intellisense engine for C#
                    var registry = ServiceProvider.GetService(typeof(SLocalRegistry)) as ILocalRegistry3;
                    Assumes.Present(registry);
                    IntPtr pIntellisenseEngine = IntPtr.Zero;
                    try
                    {
                        Marshal.ThrowExceptionForHR(registry.CreateInstance(
                                                        IntelliSenseProviderGuid,
                                                        null,
                                                        typeof(IVsIntellisenseProject).GUID,
                                                        (uint)CLSCTX.CLSCTX_INPROC_SERVER,
                                                        out pIntellisenseEngine));

                        _intellisenseEngine = Marshal.GetObjectForIUnknown(pIntellisenseEngine) as IVsIntellisenseProject;
                    }
                    finally
                    {
                        if (pIntellisenseEngine != IntPtr.Zero)
                        {
                            Marshal.Release(pIntellisenseEngine);
                        }
                    }

                    Marshal.ThrowExceptionForHR(_intellisenseEngine.Init(this));
#pragma warning disable CA2007 // Do not directly await a Task (see https://github.com/dotnet/roslyn/issues/6770)
                    await LanguageServiceRegister.RegisterProjectAsync(this);
#pragma warning restore CA2007 // Do not directly await a Task
                }
            });

            // The rest of this can execute on a worker thread.
            await TaskScheduler.Default;
            using (ProjectAsynchronousTasksService.LoadedProject())
            {
                var designTimeBuildBlock = new ActionBlock <IProjectVersionedValue <IProjectSubscriptionUpdate> >(
                    ProjectBuildRuleBlock_ChangedAsync);
                _designTimeBuildSubscriptionLink = ActiveConfiguredProjectSubscriptionService.JointRuleSource.SourceBlock.LinkTo(
                    designTimeBuildBlock,
                    ruleNames: WatchedEvaluationRules.Union(WatchedDesignTimeBuildRules));

                var evaluationBlock = new ActionBlock <IProjectVersionedValue <IProjectSubscriptionUpdate> >(
                    ProjectRuleBlock_ChangedAsync);
                _evaluationSubscriptionLink = ActiveConfiguredProjectSubscriptionService.JointRuleSource.SourceBlock.LinkTo(
                    evaluationBlock,
                    ruleNames: WatchedEvaluationRules);
            }
        }
        private async Task WarnUserOfIncompatibleProjectAsync(CompatibilityLevel compatLevel, VersionCompatibilityData compatData, bool isPreviewSDKInUse)
        {
            if (!_threadHandling.Value.IsOnMainThread)
            {
                await _threadHandling.Value.SwitchToUIThread();
            }

            // Check if already warned - this could happen in the off chance two projects are added very quickly since the detection work is
            // scheduled on idle.
            if (CompatibilityLevelWarnedForCurrentSolution < compatLevel)
            {
                // Only want to warn once per solution
                CompatibilityLevelWarnedForCurrentSolution = compatLevel;

                IVsUIShell?uiShell = await _vsUIShellService.GetValueAsync();

                Assumes.Present(uiShell);

                uiShell.GetAppName(out string caption);

                if (compatLevel == CompatibilityLevel.Supported)
                {
                    // Get current dontShowAgain value
                    ISettingsManager?settingsManager = await _settingsManagerService.GetValueAsync();

                    bool suppressPrompt = false;
                    if (settingsManager != null)
                    {
                        suppressPrompt = settingsManager.GetValueOrDefault(SuppressDotNewCoreWarningKey, defaultValue: false);
                    }

                    if (compatData.OpenSupportedPreviewMessage is null && isPreviewSDKInUse)
                    {
                        // There is no message to show the user in this case so we return
                        return;
                    }

                    if (!suppressPrompt)
                    {
                        string msg;
                        if (compatData.OpenSupportedPreviewMessage is object && isPreviewSDKInUse)
                        {
                            msg = string.Format(compatData.OpenSupportedPreviewMessage, compatData.SupportedVersion !.Major, compatData.SupportedVersion.Minor);
                        }
                        else
                        {
                            msg = string.Format(compatData.OpenSupportedMessage, compatData.SupportedVersion !.Major, compatData.SupportedVersion.Minor);
                        }

                        suppressPrompt = _dialogServices.Value.DontShowAgainMessageBox(caption, msg, VSResources.DontShowAgain, false, VSResources.LearnMore, SupportedLearnMoreFwlink);
                        if (suppressPrompt && settingsManager != null)
                        {
                            await settingsManager.SetValueAsync(SuppressDotNewCoreWarningKey, suppressPrompt, isMachineLocal : true);
                        }
                    }
                }
                else
                {
                    string msg;
                    if (compatData.UnsupportedVersion != null)
                    {
                        msg = string.Format(compatData.OpenUnsupportedMessage, compatData.UnsupportedVersion.Major, compatData.UnsupportedVersion.Minor);
                    }
                    else
                    {
                        msg = string.Format(compatData.OpenUnsupportedMessage, compatData.SupportedVersion !.Major, compatData.SupportedVersion.Minor);
                    }

                    _dialogServices.Value.DontShowAgainMessageBox(caption, msg, null, false, VSResources.LearnMore, UnsupportedLearnMoreFwlink);
                }
            }
        }
Exemple #24
0
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            instance = this;
            ModelScannerEvents.Start();

            await base.InitializeAsync(cancellationToken, progress);

            _txtManager = await GetServiceAsync(typeof(SVsTextManager)) as IVsTextManager4;

            Assumes.Present(_txtManager);

            // register property changed event handler
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            XSharpXMLDocTools.Initialize();
            var shell = await this.GetServiceAsync(typeof(SVsShell)) as IVsShell;

            if (shell != null)
            {
                shell.AdviseShellPropertyChanges(this, out shellCookie);
            }

            IServiceContainer           serviceContainer = this as IServiceContainer;
            XSharpLegacyLanguageService languageService  = new XSharpLegacyLanguageService(serviceContainer);

            languageService.SetSite(this);

            serviceContainer.AddService(typeof(XSharpLegacyLanguageService),
                                        languageService,
                                        true);
            //if (!XSettings.DisableClassViewObjectView)
            //{
            //    ServiceCreatorCallback callback = new ServiceCreatorCallback(CreateLibraryService);
            //    serviceContainer.AddService(typeof(IXSharpLibraryManager), callback, true);
            //}

            RegisterDebuggerEvents();
            addOurFileExtensionsForDiffAndPeek("Diff\\SupportedContentTypes");
            addOurFileExtensionsForDiffAndPeek("Peek\\SupportedContentTypes");


            // Register a timer to call several services
            // idle periods.
            _oleComponentManager = await GetServiceAsync(typeof(SOleComponentManager)) as IOleComponentManager;

            if (m_componentID == 0 && _oleComponentManager != null)
            {
                OLECRINFO[] crinfo = new OLECRINFO[1];
                crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime |
                                   (uint)_OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal |
                                     (uint)_OLECADVF.olecadvfRedrawOff |
                                     (uint)_OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 1000;

                int hr = _oleComponentManager.FRegisterComponent(this, crinfo, out m_componentID);
            }
            GetIntellisenseSettings();
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            XSettings.LanguageService = this;
        }
        protected override async Task <IEnumerable <IProjectItem> > GetUnresolvedReferencesAsync(ConfiguredProjectServices services)
        {
            Assumes.Present(services.ProjectReferences);

            return((await services.ProjectReferences.GetUnresolvedReferencesAsync()).Cast <IProjectItem>());
        }
Exemple #26
0
        protected override IDisposable LinkExternalInput(ITargetBlock <IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> > targetBlock)
        {
            Assumes.Present(_configuredProject.Services.ProjectSubscription);

            bool attemptedStateRestore = false;

            // Initial state is empty. We will evolve this reference over time, updating it iteratively
            // on each new data update.
            UpToDateCheckImplicitConfiguredInput state = UpToDateCheckImplicitConfiguredInput.CreateEmpty(_configuredProject.ProjectConfiguration);

            IPropagatorBlock <IProjectVersionedValue <UpdateValues>, IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> > transformBlock
                = DataflowBlockSlim.CreateTransformBlock <IProjectVersionedValue <UpdateValues>, IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> >(TransformAsync);

            IProjectValueDataSource <IProjectSubscriptionUpdate> source1 = _configuredProject.Services.ProjectSubscription.JointRuleSource;
            IProjectValueDataSource <IProjectSubscriptionUpdate> source2 = _configuredProject.Services.ProjectSubscription.SourceItemsRuleSource;
            IProjectItemSchemaService source3 = _projectItemSchemaService;
            IProjectValueDataSource <IProjectCatalogSnapshot> source4 = _configuredProject.Services.ProjectSubscription.ProjectCatalogSource;

            return(new DisposableBag
            {
                // Sync-link various sources to our transform block
                ProjectDataSources.SyncLinkTo(
                    source1.SourceBlock.SyncLinkOptions(DataflowOption.WithRuleNames(ProjectPropertiesSchemas)),
                    source2.SourceBlock.SyncLinkOptions(),
                    source3.SourceBlock.SyncLinkOptions(),
                    source4.SourceBlock.SyncLinkOptions(),
                    target: transformBlock,
                    linkOptions: DataflowOption.PropagateCompletion,
                    CancellationToken.None),

                // Link the transform block to our target block
                transformBlock.LinkTo(targetBlock, DataflowOption.PropagateCompletion),

                JoinUpstreamDataSources(source1, source2, source3, source4)
            });

            async Task <IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> > TransformAsync(IProjectVersionedValue <UpdateValues> e)
            {
                if (!attemptedStateRestore)
                {
                    attemptedStateRestore = true;

                    if (_persistentState is not null)
                    {
                        // Restoring state requires the UI thread. We must use JTF.RunAsync here to ensure the UI
                        // thread is shared between related work and prevent deadlocks.
                        (int ItemHash, DateTime InputsChangedAtUtc)? restoredState =
                            await JoinableFactory.RunAsync(() => _persistentState.RestoreStateAsync(_configuredProject.UnconfiguredProject.FullPath, _configuredProject.ProjectConfiguration.Dimensions, _projectAsynchronousTasksService.UnloadCancellationToken));

                        if (restoredState is not null)
                        {
                            state = state.WithRestoredState(restoredState.Value.ItemHash, restoredState.Value.InputsChangedAtUtc);
                        }
                    }
                }

                int?     priorItemHash = state.ItemHash;
                DateTime priorLastItemsChangedAtUtc = state.LastItemsChangedAtUtc;

                state = state.Update(
                    jointRuleUpdate: e.Value.Item1,
                    sourceItemsUpdate: e.Value.Item2,
                    projectItemSchema: e.Value.Item3,
                    projectCatalogSnapshot: e.Value.Item4);

                if (state.ItemHash is not null && _persistentState is not null && (priorItemHash != state.ItemHash || priorLastItemsChangedAtUtc != state.LastItemsChangedAtUtc))
                {
                    await _persistentState.StoreStateAsync(_configuredProject.UnconfiguredProject.FullPath, _configuredProject.ProjectConfiguration.Dimensions, state.ItemHash.Value, state.LastItemsChangedAtUtc, _projectAsynchronousTasksService.UnloadCancellationToken);
                }

                return(new ProjectVersionedValue <UpToDateCheckImplicitConfiguredInput>(state, e.DataSourceVersions));
            }
        }
Exemple #27
0
        private async Task <IVsWindowFrame> CreateDocWindowAsync(
            Project project,
            string documentName,
            IVsHierarchy hier,
            uint itemId)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var windowFlags =
                (uint)_VSRDTFLAGS.RDT_DontAddToMRU |
                (uint)_VSRDTFLAGS.RDT_DontSaveAs;

            if (!await SolutionManager.Value.IsSolutionAvailableAsync())
            {
                throw new InvalidOperationException(Resources.SolutionIsNotSaved);
            }

            var uniqueName   = EnvDTEProjectInfoUtility.GetUniqueName(project);
            var nugetProject = await SolutionManager.Value.GetNuGetProjectAsync(uniqueName);

            // If we failed to generate a cache entry in the solution manager something went wrong.
            if (nugetProject == null)
            {
                throw new InvalidOperationException(
                          string.Format(Resources.ProjectHasAnInvalidNuGetConfiguration, project.Name));
            }

            // load packages.config. This makes sure that an exception will get thrown if there
            // are problems with packages.config, such as duplicate packages. When an exception
            // is thrown, an error dialog will pop up and this doc window will not be created.
            _ = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None);

            var uiController = UIFactory.Value.Create(nugetProject);

            var model = new PackageManagerModel(
                uiController,
                isSolution: false,
                editorFactoryGuid: GuidList.guidNuGetEditorType);

            var vsWindowSearchHostfactory = await GetServiceAsync(typeof(SVsWindowSearchHostFactory)) as IVsWindowSearchHostFactory;

            var vsShell = await GetServiceAsync(typeof(SVsShell)) as IVsShell4;

            var control = new PackageManagerControl(model, Settings.Value, vsWindowSearchHostfactory, vsShell, OutputConsoleLogger.Value);

            var windowPane     = new PackageManagerWindowPane(control);
            var guidEditorType = GuidList.guidNuGetEditorType;
            var guidCommandUI  = Guid.Empty;
            var caption        = string.Format(
                CultureInfo.CurrentCulture,
                Resx.Label_NuGetWindowCaption,
                project.Name);

            IVsWindowFrame windowFrame;
            var            uiShell = await GetServiceAsync(typeof(SVsUIShell)) as IVsUIShell;

            Assumes.Present(uiShell);
            var ppunkDocView = IntPtr.Zero;
            var ppunkDocData = IntPtr.Zero;
            var hr           = 0;

            try
            {
                ppunkDocView = Marshal.GetIUnknownForObject(windowPane);
                ppunkDocData = Marshal.GetIUnknownForObject(model);
                hr           = uiShell.CreateDocumentWindow(
                    windowFlags,
                    documentName,
                    (IVsUIHierarchy)hier,
                    itemId,
                    ppunkDocView,
                    ppunkDocData,
                    ref guidEditorType,
                    null,
                    ref guidCommandUI,
                    null,
                    caption,
                    string.Empty,
                    null,
                    out windowFrame);
                if (windowFrame != null)
                {
                    WindowFrameHelper.AddF1HelpKeyword(windowFrame, keywordValue: F1KeywordValuePmUI);
                }
            }
            finally
            {
                if (ppunkDocView != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocData);
                }

                if (ppunkDocData != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocView);
                }
            }

            ErrorHandler.ThrowOnFailure(hr);
            return(windowFrame);
        }
        protected int Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction, bool reopen = false)
        {
            windowFrame = null;
            if (this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed)
            {
                return(VSConstants.E_FAIL);
            }

            Debug.Assert(this.Node != null, "No node has been initialized for the document manager");
            Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager");
            Debug.Assert(this.Node is FileNode, "Node is not FileNode object");

            int    returnValue = VSConstants.S_OK;
            string caption     = this.GetOwnerCaption();
            string fullPath    = this.GetFullPathForDocument();

            IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;

            Assumes.Present(uiShellOpenDocument);

            IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;

            Assumes.Present(serviceProvider);

            var  openState  = uiShellOpenDocument as IVsUIShellOpenDocument3;
            bool showDialog = !reopen && (openState == null || !((__VSNEWDOCUMENTSTATE)openState.NewDocumentState).HasFlag(__VSNEWDOCUMENTSTATE.NDS_Provisional));

            // Make sure that the file is on disk before we open the editor and display message if not found
            if (!((FileNode)this.Node).IsFileOnDisk(showDialog))
            {
                // Bail since we are not able to open the item
                // Do not return an error code otherwise an internal error message is shown. The scenario for this operation
                // normally is already a reaction to a dialog box telling that the item has been removed.
                return(VSConstants.S_FALSE);
            }

            try
            {
                this.Node.ProjectMgr.OnOpenItem(fullPath);
                int result = VSConstants.E_FAIL;

                if (openWith)
                {
                    result = uiShellOpenDocument.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
                }
                else
                {
                    __VSOSEFLAGS openFlags = 0;
                    if (newFile)
                    {
                        openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile;
                    }

                    //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid
                    // of the node being opened, otherwise the debugger doesn't work.
                    if (editorType != Guid.Empty)
                    {
                        result = uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
                    }
                    else
                    {
                        openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor;
                        result     = uiShellOpenDocument.OpenStandardEditor((uint)openFlags, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame);
                    }
                }

                if (result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED)
                {
                    ErrorHandler.ThrowOnFailure(result);
                }

                if (windowFrame != null)
                {
                    object var;

                    if (newFile)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var));
                        IVsPersistDocData persistDocData = (IVsPersistDocData)var;
                        ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath));
                    }

                    var = null;
                    ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var));
                    this.Node.DocCookie = (uint)(int)var;

                    if (windowFrameAction == WindowFrameShowAction.Show)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.Show());
                    }
                    else if (windowFrameAction == WindowFrameShowAction.ShowNoActivate)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.ShowNoActivate());
                    }
                    else if (windowFrameAction == WindowFrameShowAction.Hide)
                    {
                        ErrorHandler.ThrowOnFailure(windowFrame.Hide());
                    }
                }
            }
            catch (COMException e)
            {
                XSharpProjectPackage.Instance.DisplayException(e);
                returnValue = e.ErrorCode;
                CloseWindowFrame(ref windowFrame);
            }

            return(returnValue);
        }
Exemple #29
0
        internal static bool IsOurSourceFile(string fileName)
        {
            var serviceProvider = XSharpEditorFactory.GetServiceProvider();

            if (serviceProvider == null)
            {
                return(false);
            }
            var type = XSharpModel.XFileTypeHelpers.GetFileType(fileName);

            switch (type)
            {
            case XSharpModel.XFileType.SourceCode:
            case XSharpModel.XFileType.Header:
            case XSharpModel.XFileType.PreprocessorOutput:
                break;

            default:
                return(false);
            }

            // Find the document in the Running Document Table and Get Its hierarchy object
            // so we can ask for a property that we can use to see if this is 'Ours'
            IVsRunningDocumentTable rdt = serviceProvider.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;

            Assumes.Present(rdt);
            uint         itemID;
            IVsHierarchy hierarchy;
            IntPtr       unkDocData;
            uint         cookie;

            rdt.FindAndLockDocument((uint)(_VSRDTFLAGS.RDT_NoLock), fileName, out hierarchy, out itemID, out unkDocData, out cookie);
            if (unkDocData != IntPtr.Zero)
            {
                Marshal.Release(unkDocData);
            }
            object result;
            bool   ours = false;

            if (string.Compare(XSharpProjectPackage.VsVersion.Substring(0, 3), "15.0") >= 0)
            {
                ours = true;
            }
            // Ask for the Language. X# returns the product name
            // the implementation for this property is inside XSharpFileNode.
            if (hierarchy != null)
            {
                hierarchy.GetProperty(itemID, (int)__VSHPROPID8.VSHPROPID_DiagHubLanguage, out result);
                ours = (result is string && (string)result == Constants.Product);
            }
            if (!ours)
            {
                // this could be a XAML generated source file that is not in the hierarchy
                // in that case it is part of the XSolution and we should be able to find its XAML parent
                var file = XSharpModel.XSolution.FindFullPath(fileName);
                ours = (file != null);
            }
            if (!ours)
            {
                // ask for a project root. If there is no project root, then we take ownership
                result = null;
                if (hierarchy != null)
                {
                    hierarchy.GetProperty(itemID, (int)__VSHPROPID.VSHPROPID_Root, out result);
                }
                ours = (result == null);
                if (ours)
                {
                    XSharpModel.XSolution.OrphanedFilesProject.AddFile(fileName);
                }
            }
            return(ours);
        }
        public async Task <IRule?> GetBrowseObjectRuleAsync(IDependency dependency, TargetFramework targetFramework, IProjectCatalogSnapshot?catalogs)
        {
            Requires.NotNull(dependency, nameof(dependency));

            IImmutableDictionary <string, IPropertyPagesCatalog> namedCatalogs = await GetNamedCatalogsAsync();

            Requires.NotNull(namedCatalogs, nameof(namedCatalogs));

            if (!namedCatalogs.TryGetValue(PropertyPageContexts.BrowseObject, out IPropertyPagesCatalog browseObjectsCatalog))
            {
                // Issue https://github.com/dotnet/project-system/issues/4860 suggests this code path
                // can exist, however a repro was not found to dig deeper into the underlying cause.
                // For now just return null as the upstream caller handles null correctly anyway.
                return(null);
            }

            string?itemSpec = string.IsNullOrEmpty(dependency.OriginalItemSpec)
                ? dependency.FilePath
                : dependency.OriginalItemSpec;

            var context = ProjectPropertiesContext.GetContext(
                UnconfiguredProject,
                itemType: dependency.SchemaItemType,
                itemName: itemSpec);

            Rule?schema = dependency.SchemaName != null?browseObjectsCatalog.GetSchema(dependency.SchemaName) : null;

            if (schema == null)
            {
                // Since we have no browse object, we still need to create *something* so
                // that standard property pages can pop up.
                Rule emptyRule = RuleExtensions.SynthesizeEmptyRule(context.ItemType);

                return(GetConfiguredProjectExports().PropertyPagesDataModelProvider.GetRule(
                           emptyRule,
                           context.File,
                           context.ItemType,
                           context.ItemName));
            }

            if (dependency.Resolved && !Strings.IsNullOrEmpty(dependency.OriginalItemSpec))
            {
                return(GetConfiguredProjectExports().RuleFactory.CreateResolvedReferencePageRule(
                           schema,
                           context,
                           dependency.OriginalItemSpec,
                           dependency.BrowseObjectProperties));
            }

            return(browseObjectsCatalog.BindToContext(schema.Name, context));

            async Task <IImmutableDictionary <string, IPropertyPagesCatalog> > GetNamedCatalogsAsync()
            {
                if (catalogs != null)
                {
                    return(catalogs.NamedCatalogs);
                }

                if (_namedCatalogs == null)
                {
                    Assumes.NotNull(ActiveConfiguredProject);
                    Assumes.Present(ActiveConfiguredProject.Services.PropertyPagesCatalog);

                    // Note: it is unlikely that we end up here, however for cases when node providers
                    // getting their node data not from Design time build events, we might have OnDependenciesChanged
                    // event coming before initial design time build event updates NamedCatalogs in this class.
                    // Thus, just in case, explicitly request it here (GetCatalogsAsync will acquire a project read lock)
                    _namedCatalogs = await ActiveConfiguredProject.Services.PropertyPagesCatalog.GetCatalogsAsync();
                }

                return(_namedCatalogs);
            }

            ConfiguredProjectExports GetConfiguredProjectExports()
            {
                Assumes.NotNull(ActiveConfiguredProject);

                ConfiguredProject project = targetFramework.Equals(TargetFramework.Any)
                    ? ActiveConfiguredProject
                    : _dependenciesSnapshotProvider.GetConfiguredProject(targetFramework) ?? ActiveConfiguredProject;

                return(GetActiveConfiguredProjectExports(project));
            }
        }