/// <summary> /// Executes the command. /// </summary> /// <returns>Returns <see langword="true"/> if the command was succesfully executed; otherwise <see langword="false"/>.</returns> public static async Task <bool> ExecuteAsync(this CommandID cmd, string argument = "") { if (!await cmd.IsAvailableAsync()) { return(false); } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IOleCommandTarget cs = await VS.GetRequiredServiceAsync <SUIHostCommandDispatcher, IOleCommandTarget>(); IntPtr vIn = IntPtr.Zero; Guid g = cmd.Guid; try { if (!string.IsNullOrWhiteSpace(argument)) { vIn = Marshal.AllocCoTaskMem(128); Marshal.GetNativeVariantForObject(argument, vIn); } int hr = cs.Exec(ref g, unchecked ((uint)cmd.ID), (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, vIn, IntPtr.Zero); return(ErrorHandler.Succeeded(hr)); } finally { if (vIn != IntPtr.Zero) { NativeMethods.VariantClear(vIn); Marshal.FreeCoTaskMem(vIn); } } }
private static async Task HideUnloadedProjectsInSolutionExplorerAsync() { ISolutionExplorer solutionExplorer; await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); solutionExplorer = await VS.GetRequiredServiceAsync <ISolutionExplorer, ISolutionExplorer>(); // The solution has opened, but Solution Explorer may not have been populated // yet, so keep looping until there is something in Solution Explorer. while (true) { bool?empty; empty = await solutionExplorer.IsEmptyAsync(); // If we know for sure that Solution Explorer is empty, then wait // a bit and try again. If we know it's not empty then we can hide // the unloaded projects. If we don't know if it's empty or not, then // we'll still try to hide the unloaded projects because if we don't now, // then we may never know, and then we'd end up looping here forever. if (empty.GetValueOrDefault()) { await Task.Delay(1000); } else { break; } } await solutionExplorer.HideUnloadedProjectsAsync(); }
private static async Task LogFailureAsync(string message, int result) { ILogger logger; logger = await VS.GetRequiredServiceAsync <ILogger, ILogger>(); await logger.WriteLineAsync($"{message} {Marshal.GetExceptionForHR(result).Message}"); }
protected async override Task ExecuteAsync(OleMenuCmdEventArgs e) { IFilterService filterService; FilterOptions? options; filterService = await VS.GetRequiredServiceAsync <IFilterService, IFilterService>(); options = await GetOptionsAsync(); if (options is not null) { await filterService.ApplyAsync(options); } }
// XSharpLanguageService _langService = null; #region Overridden Implementation /// <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 System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { // Give the codemodel a way to talk to the VS Shell oShellLink = new XSharpShellLink(); XSettings.ShellLink = oShellLink; this.RegisterToolWindows(); XSharpProjectPackage.instance = this; this.SolutionListeners.Add(new SolutionEvents(this)); await base.InitializeAsync(cancellationToken, progress); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // The project selector helps to choose between MPF and CPS projects //_projectSelector = new XSharpProjectSelector(); //await _projectSelector.InitAsync(this); this.settings = new XPackageSettings(this); VS.Events.BuildEvents.ProjectConfigurationChanged += BuildEvents_ProjectConfigurationChanged; this.RegisterProjectFactory(new XSharpProjectFactory(this)); // Indicate how to open the different source files : SourceCode or Designer ?? this.RegisterEditorFactory(new XSharpEditorFactory(this)); this.RegisterProjectFactory(new XSharpWPFProjectFactory(this)); // editors for the binaries base.RegisterEditorFactory(new VOFormEditorFactory(this)); base.RegisterEditorFactory(new VOMenuEditorFactory(this)); base.RegisterEditorFactory(new VODBServerEditorFactory(this)); base.RegisterEditorFactory(new VOFieldSpecEditorFactory(this)); //this._documentWatcher = new XSharpDocumentWatcher(this); _errorList = await VS.GetRequiredServiceAsync <SVsErrorList, IErrorList>(); _taskList = await VS.GetRequiredServiceAsync <SVsTaskList, ITaskList>(); var shell = await VS.GetRequiredServiceAsync <SVsShell, IVsShell>(); if (shell != null) { shell.AdviseShellPropertyChanges(this, out shellCookie); } _langservice = await GetServiceAsync(typeof(XSharpLanguageService)) as XSharpLanguageService; await this.RegisterCommandsAsync(); await GetEditorOptionsAsync(); }
private async Task <FilterOptions?> GetOptionsAsync() { IHierarchyProvider hierarchyProvider; IExtensionSettings settings; TextFilterFactory textFilterFactory; Func <Task <IEnumerable <IHierarchyNode> > > hierarchyFactory; await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); hierarchyProvider = await VS.GetRequiredServiceAsync <IHierarchyProvider, IHierarchyProvider>(); settings = await VS.GetRequiredServiceAsync <IExtensionSettings, IExtensionSettings>(); textFilterFactory = await CreateTextFilterFactoryAsync(); hierarchyFactory = async() => await hierarchyProvider.GetHierarchyAsync(); using (var vm = new FilterDialogViewModel(hierarchyFactory, Debouncer.Create, textFilterFactory, Package.JoinableTaskFactory)) { FilterDialog dialog; bool result; await settings.LoadAsync(); vm.LoadProjectDependencies = settings.LoadProjectDependencies; vm.UseRegularExpressions = settings.UseRegularExpressions; dialog = new FilterDialog { DataContext = vm }; result = dialog.ShowModal().GetValueOrDefault(); settings.LoadProjectDependencies = vm.LoadProjectDependencies; settings.UseRegularExpressions = vm.UseRegularExpressions; await settings.SaveAsync(); if (result) { return(vm.Result); } } return(null); }
/// <summary>Adds one or more files to the project.</summary> public static async Task AddFilesToProjectAsync(this Project project, params string[] files) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (project == null || project.IsKind(ProjectTypes.ASPNET_CORE) || project.IsKind(ProjectTypes.DOTNET_CORE) || project.IsKind(ProjectTypes.SSDT)) { return; } DTE2?dte = await VS.GetDTEAsync(); if (project.IsKind(ProjectTypes.WEBSITE)) { Command command = dte.Commands.Item("SolutionExplorer.Refresh"); if (command.IsAvailable) { dte.ExecuteCommand(command.Name); } return; } IVsSolution?solutionService = await VS.GetRequiredServiceAsync <SVsSolution, IVsSolution>(); solutionService.GetProjectOfUniqueName(project.UniqueName, out IVsHierarchy? hierarchy); if (hierarchy == null) { return; } var ip = (IVsProject)hierarchy; var result = new VSADDRESULT[files.Count()]; ip.AddItem(VSConstants.VSITEMID_ROOT, VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE, string.Empty, (uint)files.Count(), files.ToArray(), IntPtr.Zero, result); }
/// <summary> /// Executes the command. /// </summary> /// <returns>Returns <see langword="true"/> if the command was succesfully executed; otherwise <see langword="false"/>.</returns> public static async Task <bool> ExecuteAsync(this CommandID cmd, string argument = "") { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IOleCommandTarget cs = await VS.GetRequiredServiceAsync <SUIHostCommandDispatcher, IOleCommandTarget>(); int argByteCount = Encoding.Unicode.GetByteCount(argument); IntPtr inArgPtr = Marshal.AllocCoTaskMem(argByteCount); try { Marshal.GetNativeVariantForObject(argument, inArgPtr); int result = cs.Exec(cmd.Guid, (uint)cmd.ID, (uint)OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, inArgPtr, IntPtr.Zero); return(result == VSConstants.S_OK); } finally { Marshal.Release(inArgPtr); } }
/// <summary> /// Converts an ImageMoniker to an IVsUIObject in the specified size. /// </summary> public static async Task <IVsUIObject> ToUiObjectAsync(this ImageMoniker moniker, int size) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IVsImageService2 imageService = await VS.GetRequiredServiceAsync <SVsImageService, IVsImageService2>(); Color backColor = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey); var imageAttributes = new ImageAttributes { Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags | unchecked ((uint)_ImageAttributesFlags.IAF_Background), ImageType = (uint)_UIImageType.IT_Bitmap, Format = (uint)_UIDataFormat.DF_WPF, Dpi = 96, LogicalHeight = size, LogicalWidth = size, Background = (uint)backColor.ToArgb(), StructSize = Marshal.SizeOf(typeof(ImageAttributes)) }; return(imageService.GetImage(moniker, imageAttributes)); }
/// <summary> /// Checks if a command is enabled and supported. /// </summary> public static async Task <bool> IsAvailableAsync(this CommandID cmd) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IOleCommandTarget cs = await VS.GetRequiredServiceAsync <SUIHostCommandDispatcher, IOleCommandTarget>(); Guid guid = cmd.Guid; OLECMD[]? cmds = new OLECMD[1]; cmds[0].cmdID = (uint)cmd.ID; cmds[0].cmdf = 0; int hr = cs.QueryStatus(ref guid, (uint)cmds.Length, cmds, IntPtr.Zero); if (ErrorHandler.Succeeded(hr)) { if (((OLECMDF)cmds[0].cmdf).HasFlag(OLECMDF.OLECMDF_ENABLED)) { return(true); } } return(false); }
public async Task ApplyAsync(FilterOptions options) { ThreadedWaitDialogProgressData progress; IWaitDialogFactory waitDialogFactory; if (options is null) { throw new ArgumentNullException(nameof(options)); } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if ((options.ProjectsToLoad.Count == 0) && (options.ProjectsToUnload.Count == 0)) { return; } waitDialogFactory = await VS.GetRequiredServiceAsync <IWaitDialogFactory, IWaitDialogFactory>(); progress = new ThreadedWaitDialogProgressData("Filtering projects...", "Getting ready...", "", true); using (var dialog = await waitDialogFactory.CreateAsync(Vsix.Name, progress)) { IEnumerable <Guid> projectsToUnload; IEnumerable <Guid> projectsToLoad; State state; ISolutionExplorer solutionExplorer; state = new State( dialog, progress, (IVsSolution4)await VS.Services.GetSolutionAsync() ); projectsToUnload = options.ProjectsToUnload.ToList(); projectsToLoad = options.ProjectsToLoad.ToList(); // Work out which projects actually need to be unloaded // so that we can calculate an accurate progress. If a // project is already unloaded, then we can skip it. state.AddProjectsToUnload(projectsToUnload.Where((x) => IsLoaded(state.Solution, x))); // Do the same for the projects that we need to load. We may add // to this list as we load projects and find their dependencies, // but we need to start with a known list so that we can give a // reasonable initial estimation for the progress. Start with the // projects that we were asked to load that are not already loaded. state.AddProjectsToLoad(projectsToLoad.Where((x) => !IsLoaded(state.Solution, x))); // If we're loading dependencies, then we can add the unloaded // dependencies of the loaded projects that were requested to be loaded. if (options.LoadProjectDependencies) { foreach (var identifier in projectsToLoad.Where((x) => IsLoaded(state.Solution, x))) { foreach (var dependency in await GetProjectDependenciesAsync(identifier, state)) { if (!IsLoaded(state.Solution, dependency)) { state.AddProjectToLoad(dependency); } } } } // Now we can start loading and unloading projects. We're // filtering projects because the user wants to keep the number // of projects loaded to a minimum, so start by unloading the // requested projects before we start loading any new projects. foreach (var identifier in projectsToUnload) { if (state.IsCancellationRequested) { break; } await UnloadProjectAsync(identifier, state); } foreach (var identifier in projectsToLoad) { if (state.IsCancellationRequested) { break; } await LoadProjectAsync(identifier, options.LoadProjectDependencies, state); } // Even if we've been cancelled, we'll still hide the unloaded // projects and show the loaded projects. This prevents us from // getting into a state where we've loaded some projects but they // remain hidden because the user cancelled half way through. solutionExplorer = await VS.GetRequiredServiceAsync <ISolutionExplorer, ISolutionExplorer>(); await solutionExplorer.HideUnloadedProjectsAsync(); // If a project has been loaded, then the user probably // wants to see it, so expand any parent folders. await solutionExplorer.ExpandAsync(state.GetLoadedProjects()); } }