コード例 #1
0
        private static bool IsCSharpProject(IVsProject project)
        {
            IVsAggregatableProject aggregatableProject = project as IVsAggregatableProject;

            if (aggregatableProject == null)
            {
                return(false);
            }

            string guidsString = null;

            if (ErrorHandler.Failed(ErrorHandler.CallWithCOMConvention(() => aggregatableProject.GetAggregateProjectTypeGuids(out guidsString))))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(guidsString))
            {
                return(false);
            }

            string[] guids = guidsString.Split(';');
            foreach (var guidString in guids)
            {
                Guid guid;
                if (Guid.TryParse(guidString, out guid) && guid == CSharpProjectTypeGuid)
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #2
0
        private bool IsViewOnScreen(ITextView view)
        {
            Contract.Requires <ArgumentNullException>(view != null, "view");

            IVsTextView      viewAdapter = VsEditorAdaptersFactoryService.GetViewAdapter(view);
            IServiceProvider sp          = viewAdapter as IServiceProvider;

            if (sp == null)
            {
                return(false);
            }

            IVsWindowFrame frame = sp.GetService(typeof(SVsWindowFrame)) as IVsWindowFrame;

            if (frame == null)
            {
                return(false);
            }

            int onScreen = 0;

            if (ErrorHandler.Succeeded(ErrorHandler.CallWithCOMConvention(() => frame.IsOnScreen(out onScreen))))
            {
                return(onScreen != 0);
            }

            return(false);
        }
コード例 #3
0
        public static TServiceInterface TryGetGlobalService <TServiceClass, TServiceInterface>(this IOleServiceProvider serviceProvider)
            where TServiceInterface : class
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            Guid   guidService = typeof(TServiceClass).GUID;
            Guid   riid        = typeof(TServiceClass).GUID;
            IntPtr obj         = IntPtr.Zero;
            int    result      = ErrorHandler.CallWithCOMConvention(() => serviceProvider.QueryService(ref guidService, ref riid, out obj));

            if (ErrorHandler.Failed(result) || obj == IntPtr.Zero)
            {
                return(null);
            }

            try
            {
                TServiceInterface service = (TServiceInterface)Marshal.GetObjectForIUnknown(obj);
                return(service);
            }
            finally
            {
                Marshal.Release(obj);
            }
        }
コード例 #4
0
        public static bool TryGetHeaderNode(
            this IVsExpansionSession expansionSession,
            string name,
            [NotNullWhen(true)] out IXMLDOMNode?node
            )
        {
            var query = name is null ? null : $@"node()[local-name()=""{name}""]";

            IXMLDOMNode?localNode = null;

            if (
                !ErrorHandler.Succeeded(
                    ErrorHandler.CallWithCOMConvention(
                        () => expansionSession.GetHeaderNode(query, out localNode)
                        )
                    )
                )
            {
                node = null;
                return(false);
            }

            node = localNode;
            return(node is not null);
        }
コード例 #5
0
 public int OnLaunchDebugTargets(
     uint debugTargetCount, VsDebugTargetInfo4[] debugTargets,
     VsDebugTargetProcessInfo[] launchResults)
 {
     return(ErrorHandler.CallWithCOMConvention(
                () => OnLaunchDebugTargetsCore(
                    debugTargetCount, debugTargets, launchResults), true));
 }
コード例 #6
0
            private object GetCurrentElementValue(VSConstants.VSSELELEMID elementId)
            {
                object value = null;
                if (ErrorHandler.Succeeded(ErrorHandler.CallWithCOMConvention(() => _monitorSelection.GetCurrentElementValue((uint)elementId, out value))))
                    return value;

                return null;
            }
コード例 #7
0
        public void OpenUrl(Uri uri)
        {
            if (!uri.IsAbsoluteUri)
            {
                return;
            }

            /* First try to use the Web Browsing Service. This is not known to work because the
             * CreateExternalWebBrowser method always returns E_NOTIMPL. However, it is presumably
             * safer than a Shell Execute for arbitrary URIs.
             */
            var service = serviceProvider.GetWebBrowsingService();

            if (service != null)
            {
                __VSCREATEWEBBROWSER createFlags = __VSCREATEWEBBROWSER.VSCWB_AutoShow;
                VSPREVIEWRESOLUTION  resolution  = VSPREVIEWRESOLUTION.PR_Default;
                int result = ErrorHandler.CallWithCOMConvention(() =>
                {
                    ThreadHelper.ThrowIfNotOnUIThread();
                    service.CreateExternalWebBrowser((uint)createFlags, resolution, uri.AbsoluteUri);
                });

                if (ErrorHandler.Succeeded(result))
                {
                    return;
                }
            }

            // Fall back to Shell Execute, but only for http or https URIs
            if (uri.Scheme != "http" && uri.Scheme != "https")
            {
                return;
            }

            try
            {
                processManager.Start(uri.ToString(), string.Empty);
                return;
            }
            catch /*(Exception ex)*/
            {
                //log.Warn("Opening URL in default browser failed", ex);
            }

            try
            {
                processManager.Start(
                    Path.Combine(environment.GetProgramFilesPath(), @"Internet Explorer", "iexplore.exe"),
                    uri.ToString());
            }
            catch /*(Exception ex)*/
            {
                //log.Error("Really can't open the URL, even in IE", ex);
            }
        }
        public void PreviewItem(INavigateToItemDisplay itemDisplay)
        {
            // Because NavigateTo synchronously opens the file, and because
            // the NavigateTo UI automatically creates a NewDocumentStateScope,
            // preview can be accomplished by simply calling NavigateTo.

            // Navigation may fail to open the document, which can result in an exception
            // in expected cases if preview is not supported.  CallWithCOMConvention handles
            // non-critical exceptions
            ErrorHandler.CallWithCOMConvention(() => itemDisplay.NavigateTo());
        }
コード例 #9
0
        public IOutputWindowPane TryGetPane(string name)
        {
            IOutputWindowPane pane;

            if (panes.TryGetValue(name, out pane))
            {
                return(pane);
            }

            var olesp        = (IOleServiceProvider)GlobalServiceProvider.GetService(typeof(IOleServiceProvider));
            var outputWindow = olesp.TryGetGlobalService <SVsOutputWindow, IVsOutputWindow>();

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

            Guid guid;

            if (!outputWindows.TryGetValue(name, out guid))
            {
                var definition = OutputWindowDefinitions.FirstOrDefault(lazy => lazy.Metadata.Name.Equals(name));
                if (definition == null)
                {
                    return(null);
                }

                guid = Guid.NewGuid();
                // this controls whether the pane is listed in the output panes dropdown list, *not* whether the pane is initially selected
                const bool visible           = true;
                const bool clearWithSolution = false;

                if (ErrorHandler.Failed(ErrorHandler.CallWithCOMConvention(() => outputWindow.CreatePane(ref guid, definition.Metadata.Name, Convert.ToInt32(visible), Convert.ToInt32(clearWithSolution)))))
                {
                    return(null);
                }

                outputWindows.Add(definition.Metadata.Name, guid);
            }

            IVsOutputWindowPane vspane = null;

            if (ErrorHandler.Failed(ErrorHandler.CallWithCOMConvention(() => outputWindow.GetPane(ref guid, out vspane))))
            {
                return(null);
            }

            pane        = new VsOutputWindowPaneAdapter(vspane);
            panes[name] = pane;
            return(pane);
        }
コード例 #10
0
ファイル: Command1.cs プロジェクト: Vizioz/task-issues
        private bool OpenUri(Uri uri)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            if (!uri.IsAbsoluteUri)
            {
                return(false);
            }

            /* First try to use the Web Browsing Service. This is not known to work because the
             * CreateExternalWebBrowser method always returns E_NOTIMPL. However, it is presumably
             * safer than a Shell Execute for arbitrary URIs.
             */
            IVsWebBrowsingService service = ServiceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService;

            if (service != null)
            {
                __VSCREATEWEBBROWSER createFlags = __VSCREATEWEBBROWSER.VSCWB_AutoShow;
                VSPREVIEWRESOLUTION  resolution  = VSPREVIEWRESOLUTION.PR_Default;
                int result = ErrorHandler.CallWithCOMConvention(() => { ThreadHelper.ThrowIfNotOnUIThread(); return(service.CreateExternalWebBrowser((uint)createFlags, resolution, uri.AbsoluteUri)); });
                if (ErrorHandler.Succeeded(result))
                {
                    return(true);
                }
            }

            // Fall back to Shell Execute, but only for http or https URIs
            if (uri.Scheme != "http" && uri.Scheme != "https")
            {
                return(false);
            }

            try
            {
                Process.Start(uri.AbsoluteUri);
                return(true);
            }
            catch (Win32Exception)
            {
            }
            catch (FileNotFoundException)
            {
            }

            return(false);
        }
コード例 #11
0
        public static VsExpansion[] EnumerateExpansions(this IVsExpansionManager expansionManager, Guid language, string[] snippetTypes, bool shortcutsOnly)
        {
            Contract.Requires <ArgumentNullException>(expansionManager != null, "expansionManager");
            Contract.Ensures(Contract.Result <VsExpansion[]>() != null);

            bool includeNullType   = false;
            bool includeDuplicates = false;

            IVsExpansionEnumeration expEnum = null;

            if (ErrorHandler.Succeeded(ErrorHandler.CallWithCOMConvention(() => expansionManager.EnumerateExpansions(language, shortcutsOnly ? 1 : 0, snippetTypes, snippetTypes.Length, includeNullType ? 1 : 0, includeDuplicates ? 1 : 0, out expEnum))))
            {
                uint count;
                ErrorHandler.ThrowOnFailure(expEnum.GetCount(out count));

                IntPtr[] raw = new IntPtr[count];
                try
                {
                    for (int i = 0; i < raw.Length; i++)
                    {
                        raw[i] = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(VsExpansion)));
                    }

                    uint fetched;
                    ErrorHandler.ThrowOnFailure(expEnum.Next(count, raw, out fetched));

                    VsExpansion[] results = new VsExpansion[fetched];
                    for (int i = 0; i < results.Length; i++)
                    {
                        if (raw[i] != IntPtr.Zero)
                        {
                            results[i] = (VsExpansion)Marshal.PtrToStructure(raw[i], typeof(VsExpansion));
                        }
                    }

                    return(results);
                }
                finally
                {
                    foreach (IntPtr p in raw)
                    {
                        Marshal.FreeCoTaskMem(p);
                    }
                }
            }

            return(new VsExpansion[0]);
        }
コード例 #12
0
        /// <summary>
        /// The method that does the cleanup.
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            // Everybody can go here.
            if (!this.isDisposed)
            {
                // Synchronize calls to the Dispose simulteniously.
                lock (Mutex)
                {
                    if (disposing && this.eventsCookie != (uint)ShellConstants.VSCOOKIE_NIL && this.SelectionMonitor != null)
                    {
                        ErrorHandler.CallWithCOMConvention(() => this.SelectionMonitor.UnadviseSelectionEvents((uint)this.eventsCookie));
                        this.eventsCookie = (uint)ShellConstants.VSCOOKIE_NIL;
                    }

                    this.isDisposed = true;
                }
            }
        }
コード例 #13
0
        private void OnAfterAddedGrammarFile(IVsProject project, string currentFile)
        {
            int found;

            VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
            uint itemId;

            if (ErrorHandler.Failed(project.IsDocumentInProject(currentFile, out found, priority, out itemId)))
            {
                return;
            }

            if (found == 0 || priority[0] != VSDOCUMENTPRIORITY.DP_Standard)
            {
                return;
            }

            string desiredItemType = "Antlr3";

            if (string.Equals(Path.GetExtension(currentFile), ".tokens", StringComparison.OrdinalIgnoreCase))
            {
                desiredItemType = "AntlrTokens";
            }
            else if (string.Equals(Path.GetExtension(currentFile), ".g4", StringComparison.OrdinalIgnoreCase))
            {
                desiredItemType = "Antlr4";
            }

            IVsHierarchy hierarchy = project as IVsHierarchy;

            if (hierarchy != null)
            {
                object browseObject = null;
                PropertyDescriptorCollection propertyDescriptors = null;
                int hr = ErrorHandler.CallWithCOMConvention(() => hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_BrowseObject, out browseObject));
                if (ErrorHandler.Succeeded(hr))
                {
                    propertyDescriptors = TypeDescriptor.GetProperties(browseObject);
                }

                object obj;
                hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID4.VSHPROPID_BuildAction, out obj);
                if (ErrorHandler.Succeeded(hr))
                {
                    string buildAction = obj != null?obj.ToString() : null;

                    if (string.IsNullOrWhiteSpace(buildAction) || string.Equals(buildAction, "None", StringComparison.OrdinalIgnoreCase))
                    {
                        hr = ErrorHandler.CallWithCOMConvention(() => hierarchy.SetProperty(itemId, (int)__VSHPROPID4.VSHPROPID_BuildAction, desiredItemType));
                    }
                }

                if (ErrorHandler.Failed(hr) && propertyDescriptors != null)
                {
                    PropertyDescriptor itemTypeDescriptor = propertyDescriptors["ItemType"] ?? propertyDescriptors["BuildAction"];
                    if (itemTypeDescriptor != null)
                    {
                        obj = itemTypeDescriptor.GetValue(browseObject);
                        string buildAction = (string)itemTypeDescriptor.Converter.ConvertToInvariantString(obj);
                        if (string.IsNullOrWhiteSpace(buildAction) || string.Equals(buildAction, "None", StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                obj = itemTypeDescriptor.Converter.ConvertFromInvariantString(desiredItemType);
                                itemTypeDescriptor.SetValue(browseObject, obj);
                            }
                            catch (NotSupportedException)
                            {
                            }
                        }
                    }
                }

                if (propertyDescriptors != null)
                {
                    PropertyDescriptor customToolDescriptor = propertyDescriptors["CustomTool"];
                    if (customToolDescriptor != null)
                    {
                        obj = customToolDescriptor.GetValue(browseObject);
                        string customTool = customToolDescriptor.Converter.ConvertToInvariantString(obj);
                        if (string.IsNullOrWhiteSpace(customTool))
                        {
                            try
                            {
                                obj = customToolDescriptor.Converter.ConvertToInvariantString("MSBuild:Compile");
                                customToolDescriptor.SetValue(browseObject, obj);
                            }
                            catch (NotSupportedException)
                            {
                            }
                        }
                    }

                    PropertyDescriptor customToolNamespaceDescriptor = propertyDescriptors["CustomToolNamespace"];
                    if (customToolNamespaceDescriptor != null)
                    {
                        object defaultNamespace;
                        hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_DefaultNamespace, out defaultNamespace);
                        if (ErrorHandler.Succeeded(hr) && !string.IsNullOrEmpty(defaultNamespace as string))
                        {
                            obj = customToolNamespaceDescriptor.GetValue(browseObject);
                            string customToolNamespace = customToolNamespaceDescriptor.Converter.ConvertToInvariantString(obj);
                            if (string.IsNullOrWhiteSpace(customToolNamespace))
                            {
                                try
                                {
                                    obj = customToolNamespaceDescriptor.Converter.ConvertToInvariantString(defaultNamespace);
                                    customToolNamespaceDescriptor.SetValue(browseObject, obj);
                                }
                                catch (NotSupportedException)
                                {
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #14
0
        private bool OpenUri(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (string.Equals(uri.Scheme, PrefixOpenInVisualStudio, StringComparison.InvariantCultureIgnoreCase))
            {
                if (File.Exists(uri.LocalPath))
                {
                    DTEHelper.Singleton?.OpenFileInVisualStudio(null, uri.LocalPath);
                }

                return(true);
            }

            if (string.Equals(uri.Scheme, PrefixOpenInVisualStudioRelativePath, StringComparison.InvariantCultureIgnoreCase))
            {
                DTEHelper.Singleton?.OpenFileInVisualStudioRelativePath(null, uri.LocalPath);

                return(true);
            }

            if (string.Equals(uri.Scheme, PrefixOpenInTextEditor, StringComparison.InvariantCultureIgnoreCase))
            {
                if (File.Exists(uri.LocalPath))
                {
                    DTEHelper.Singleton?.OpenFileInTextEditor(null, uri.LocalPath);
                }

                return(true);
            }

            if (string.Equals(uri.Scheme, PrefixOpenInExcel, StringComparison.InvariantCultureIgnoreCase))
            {
                if (File.Exists(uri.LocalPath))
                {
                    DTEHelper.Singleton?.OpenFileInExcel(null, uri.LocalPath);
                }

                return(true);
            }

            if (string.Equals(uri.Scheme, PrefixShowDifference, StringComparison.InvariantCultureIgnoreCase))
            {
                DTEHelper.Singleton?.ShowDifference(uri);

                return(true);
            }

            if (string.Equals(uri.Scheme, PrefixOpenSolution, StringComparison.InvariantCultureIgnoreCase))
            {
                DTEHelper.Singleton?.OpenSolution(uri);

                return(true);
            }

            if (string.Equals(uri.Scheme, PrefixOpenSolutionList, StringComparison.InvariantCultureIgnoreCase))
            {
                DTEHelper.Singleton?.OpenSolutionList(uri);

                return(true);
            }

            if (string.Equals(uri.Scheme, PrefixSelectFileInFolder, StringComparison.InvariantCultureIgnoreCase))
            {
                if (File.Exists(uri.LocalPath))
                {
                    DTEHelper.Singleton?.SelectFileInFolder(null, uri.LocalPath);
                }

                return(true);
            }

            IVsWebBrowsingService service = _provider.ServiceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService;

            if (service != null)
            {
                var createFlags = __VSCREATEWEBBROWSER.VSCWB_AutoShow;
                var resolution  = VSPREVIEWRESOLUTION.PR_Default;

                int result = ErrorHandler.CallWithCOMConvention(() => service.CreateExternalWebBrowser((uint)createFlags, resolution, uri.AbsoluteUri));

                if (ErrorHandler.Succeeded(result))
                {
                    return(true);
                }
            }

            if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
            {
                return(false);
            }

            try
            {
                Process.Start(uri.AbsoluteUri);
                return(true);
            }
            catch (Exception)
            {
            }

            return(false);
        }
コード例 #15
0
 public int CallWithComConvention(Action method, bool reportError = false)
 {
     return(ErrorHandler.CallWithCOMConvention(method, reportError));
 }
コード例 #16
0
ファイル: Extensions.cs プロジェクト: rkhjjs/VSGenero
        internal static void GotoSource(this LocationInfo location, IServiceProvider serviceProvider, GeneroLanguageVersion languageVersion)
        {
            if (location.Line > 0 && location.Column > 0)
            {
                VSGeneroPackage.NavigateTo(
                    location.FilePath,
                    Guid.Empty,
                    location.Line - 1,
                    location.Column - 1);
            }
            else if (location.DefinitionURL != null)
            {
                var urlStr = location.GetUrlString(languageVersion);

                Uri definitionUrl;
                if (Uri.TryCreate(urlStr, UriKind.Absolute, out definitionUrl))
                {
                    if (serviceProvider != null)
                    {
                        IVsWebBrowsingService service = serviceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService;
                        if (service != null)
                        {
                            if (VSGeneroPackage.Instance.AdvancedOptions4GL.OpenExternalBrowser)
                            {
                                __VSCREATEWEBBROWSER createFlags = __VSCREATEWEBBROWSER.VSCWB_AutoShow;
                                VSPREVIEWRESOLUTION  resolution  = VSPREVIEWRESOLUTION.PR_Default;
                                int result = ErrorHandler.CallWithCOMConvention(() => service.CreateExternalWebBrowser((uint)createFlags, resolution, definitionUrl.AbsoluteUri));
                                if (ErrorHandler.Succeeded(result))
                                {
                                    return;
                                }
                            }
                            else
                            {
                                IVsWindowFrame ppFrame;
                                int            result = ErrorHandler.CallWithCOMConvention(() => service.Navigate(definitionUrl.AbsoluteUri, 0, out ppFrame));
                                if (ErrorHandler.Succeeded(result))
                                {
                                    return;
                                }
                            }
                        }
                    }

                    // Fall back to Shell Execute, but only for http or https URIs
                    if (definitionUrl.Scheme != "http" && definitionUrl.Scheme != "https")
                    {
                        return;
                    }

                    try
                    {
                        Process.Start(definitionUrl.AbsoluteUri);
                    }
                    catch (Win32Exception)
                    {
                    }
                    catch (FileNotFoundException)
                    {
                    }
                }
            }
            else
            {
                VSGeneroPackage.NavigateTo(location.FilePath, Guid.Empty, location.Index);
            }
        }