private static bool AffectsResourceFile(EnvDTE.Document document)
        {
            Contract.Ensures((Contract.Result <bool>() == false) || (document != null));

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

            return(document.ProjectItem
                   .DescendantsAndSelf()
                   .Select(item => item.TryGetFileName())
                   .Where(fileName => fileName != null)
                   .Select(Path.GetExtension)
                   .Any(extension => ProjectFileExtensions.SupportedFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)));
        }
示例#2
0
        private static IEnumerable <ResourceEntity> GetResourceEntiesFromProject([NotNull] EnvDTE.Document document, [NotNull][ItemNotNull] IEnumerable <ResourceEntity> entities)
        {
            Contract.Requires(document != null);
            Contract.Requires(entities != null);

            try
            {
                var project = document.ProjectItem?.ContainingProject;

                return(entities.Where(entity => IsInProject(entity, project)));
            }
            catch (Exception)
            {
                return(Enumerable.Empty <ResourceEntity>());
            }
        }
示例#3
0
        public static EnvDTE.Document GetActiveDocument(this EnvDTE80.DTE2 dte2)
        {
            EnvDTE.Document result = null;

            try
            {
                result = dte2.ActiveDocument;
            }
            catch (Exception ex)
            {
                //todo: investigate why it is sometimes thrown
                //Logger.SwallowException(ex, "Dte.ActiveDocument can throw exceptions when accessed but this does not impact this scenario.");
            }

            return(result);
        }
示例#4
0
        private static ResourceEntity GetPreferredResourceEntity([NotNull] EnvDTE.Document document, [NotNull][ItemNotNull] IEnumerable <ResourceEntity> entities)
        {
            Contract.Requires(document != null);
            Contract.Requires(entities != null);

            try
            {
                var project = document.ProjectItem?.ContainingProject;

                return(entities.FirstOrDefault(entity => IsInProject(entity, project)));
            }
            catch (Exception)
            {
                return(null);
            }
        }
示例#5
0
        /// <summary>
        /// The current comments are retrieved by obtaining the Properites object from the
        /// Tools Options window associated with the Academic toolset and walking down the
        /// set of registered file extensions looking for the one corresponding to
        /// the file type currently opened.
        /// </summary>
        private CommentPair GetCurrentComments()
        {
            EnvDTE.Document     document            = null;
            EnvDTE.TextDocument textDocument        = null;
            EnvDTE.Properties   extractorProperties = null;
            Extensions          extensions          = null;
            string extension;
            int    lastIndex;

            try
            {
                // While we don't *do* anything with the document object, we check for its presence because
                // we only know how to do insertions on the TextDocument class of object.
                document = m_applicationObject.ActiveDocument;
                if ((document == null) ||
                    ((textDocument = document.Object("TextDocument") as EnvDTE.TextDocument) == null))
                {
                    return(null);
                }

                extension = m_applicationObject.ActiveDocument.Name;
                lastIndex = extension.LastIndexOf('.');
                if (lastIndex == -1)
                {
                    return(null);
                }
                extension = extension.Remove(0, lastIndex + 1);                 // Trim off the 'name.' part of 'name.ext'

                extractorProperties = m_applicationObject.get_Properties("Assignment Manager", "Code Extractor");
                if (extractorProperties == null)
                {
                    throw new Exception(AMResources.GetLocalizedString("CollapseMarkedInvalidInstallation"));
                }

                extensions = extractorProperties.Item("Extensions").Object as Extensions;
                if (extensions == null)
                {
                    throw new Exception(AMResources.GetLocalizedString("CollapseMarkedInvalidInstallation"));
                }

                return(extensions[extension]);
            }
            catch (Exception)
            {
                return(null);
            }
        }
示例#6
0
        /// <summary>
        /// Map an EnvDTE.Document, used for files outside of the current solution eg. [from metadata]
        /// </summary>
        /// <param name="document">An EnvDTE.Document</param>
        /// <returns>List of found code items</returns>
        public static List <CodeItem> MapDocument(EnvDTE.Document document)
        {
            var doc  = (EnvDTE.TextDocument)document.Object("TextDocument");
            var p    = doc.StartPoint.CreateEditPoint();
            var text = p.GetText(doc.EndPoint);

            _tree = CSharpSyntaxTree.ParseText(text);

            var mscorlib    = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var compilation = CSharpCompilation.Create("CodeNavCompilation", new[] { _tree }, new[] { mscorlib });

            _semanticModel = compilation.GetSemanticModel(_tree);

            var root = (CompilationUnitSyntax)_tree.GetRoot();

            return(root.Members.Select(MapMember).ToList());
        }
示例#7
0
 void DocumentEvents_DocumentOpened(EnvDTE.Document document)
 {
     try
     {
         if (document.FullName.EndsWith(".bim"))
         {
             string message = "";
             foreach (EditorPane editorPane in EditorPanes)
             {
                 if (editorPane.BismNormalizerForm != null && editorPane.BismNormalizerForm.CompareState != CompareState.NotCompared)
                 {
                     // check if open diff has project that contains BIM file being opened.
                     if (editorPane.BismNormalizerForm.ComparisonInfo.ConnectionInfoSource.UseProject)
                     {
                         foreach (EnvDTE.ProjectItem projectItem in editorPane.BismNormalizerForm.ComparisonInfo.ConnectionInfoSource.Project.ProjectItems)
                         {
                             if (projectItem.Document != null && projectItem.Document.FullName == document.FullName)
                             {
                                 editorPane.BismNormalizerForm.SetNotComparedState();
                                 message += " - " + editorPane.Name + "\n";
                                 break;
                             }
                         }
                     }
                     if (editorPane.BismNormalizerForm.CompareState != CompareState.NotCompared && editorPane.BismNormalizerForm.ComparisonInfo.ConnectionInfoTarget.UseProject)
                     {
                         foreach (EnvDTE.ProjectItem projectItem in editorPane.BismNormalizerForm.ComparisonInfo.ConnectionInfoTarget.Project.ProjectItems)
                         {
                             if (projectItem.Document != null && projectItem.Document.FullName == document.FullName)
                             {
                                 editorPane.BismNormalizerForm.SetNotComparedState();
                                 message += " - " + editorPane.Name + "\n";
                                 break;
                             }
                         }
                     }
                 }
             }
             if (message.Length > 0)
             {
                 ShowMessage("Opening this file will invalidate the following comparisons.\n" + message, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGICON.OLEMSGICON_WARNING);
             }
         }
     }
     catch { }
 }
示例#8
0
 public static string GetCurrentWord()
 {
     EnvDTE.Document activeDoc = Common.Instance.DTE2.ActiveDocument;
     if (activeDoc != null)
     {
         EnvDTE.TextDocument textDoc = (EnvDTE.TextDocument)Common.Instance.DTE2.ActiveDocument.Object("TextDocument");
         if (textDoc != null)
         {
             if (textDoc.Selection.ActivePoint.Line > 0)
             {
                 string sLine = textDoc.StartPoint.CreateEditPoint().GetLines(textDoc.Selection.ActivePoint.Line, textDoc.Selection.ActivePoint.Line + 1);
                 return(GetWord(sLine, textDoc.Selection.ActivePoint.LineCharOffset - 1));
             }
         }
     }
     return(null);
 }
示例#9
0
        protected override void CommandAction(DTEHelper helper)
        {
            EnvDTE.Document document = helper.GetOpenedDocumentInCodeWindow(FileOperations.SupportsXmlType);

            if (document != null)
            {
                var objTextDoc = document.Object("TextDocument");

                if (objTextDoc != null && objTextDoc is EnvDTE.TextDocument textDocument)
                {
                    string text = textDocument.StartPoint.CreateEditPoint().GetText(textDocument.EndPoint);

                    text = ContentComparerHelper.RemoveInTextAllCustomXmlAttributesAndNamespaces(text);

                    ClipboardHelper.SetText(text);
                }
            }
        }
示例#10
0
        protected override void CommandAction(DTEHelper helper)
        {
            EnvDTE.Document document = helper.GetOpenedDocumentInCodeWindow(FileOperations.SupportsXmlType);

            if (document != null &&
                (System.Windows.Clipboard.ContainsText(System.Windows.TextDataFormat.Text) || System.Windows.Clipboard.ContainsText(System.Windows.TextDataFormat.UnicodeText))
                )
            {
                string javaScriptCode = System.Windows.Clipboard.GetText();

                if (!string.IsNullOrEmpty(javaScriptCode))
                {
                    JavaScriptFetchXmlParser parser = new JavaScriptFetchXmlParser(helper, javaScriptCode);

                    System.Threading.Tasks.Task.Run(() => ContentComparerHelper.GetTextViewAndMakeActionAsync(document, "Pasting Xml from JavaScript", parser.PasteFetchXml));
                }
            }
        }
示例#11
0
        private async void DocumentEvents_DocumentSaved(EnvDTE.Document document)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync();

            using (_performanceTracer?.Start("DTE event: Document saved"))
            {
                if (!AffectsResourceFile(document))
                {
                    return;
                }

                var resourceManager = _resourceManager;
                if (resourceManager == null || resourceManager.IsSaving)
                {
                    return;
                }

                // Run custom tool (usually attached to neutral language) even if a localized language changes,
                // e.g. if custom tool is a text template, we might want not only to generate the designer file but also
                // extract some localization information.
                // => find the resource entity that contains the document and run the custom tool on the neutral project file.

#pragma warning disable VSTHRD010 // Accessing ... should only be done on the main thread.
                bool Predicate(ResourceEntity e)
                {
                    return(e.Languages.Select(lang => lang.ProjectFile)
                           .OfType <DteProjectFile>()
                           .Any(projectFile => projectFile.ProjectItems.Any(p => p.Document == document)));
                }

#pragma warning restore VSTHRD010 // Accessing ... should only be done on the main thread.

                var entity = (await GetResourceEntitiesAsync().ConfigureAwait(true)).FirstOrDefault(Predicate);

                var neutralProjectFile = entity?.NeutralProjectFile as DteProjectFile;

                // VS will run the custom tool on the project item only. Run the custom tool on any of the descendants, too.
                var projectItems = neutralProjectFile?.ProjectItems.SelectMany(projectItem => projectItem.Descendants());

                _customToolRunner.Enqueue(projectItems);

                ReloadSolution();
            }
        }
示例#12
0
        protected override void CommandAction(DTEHelper helper)
        {
            EnvDTE.Document document = helper.GetOpenedDocumentInCodeWindow(FileOperations.SupportsXmlType);

            if (document != null)
            {
                var objTextDoc = document.Object("TextDocument");
                if (objTextDoc != null &&
                    objTextDoc is EnvDTE.TextDocument textDocument
                    )
                {
                    string text = textDocument.StartPoint.CreateEditPoint().GetText(textDocument.EndPoint);

                    string jsCode = ContentComparerHelper.FormatToJavaScript(Entities.SavedQuery.Schema.Variables.fetchxml, text);

                    ClipboardHelper.SetText(jsCode);
                }
            }
        }
示例#13
0
        public void onProgressB(Object sender, EventArgs e, EnvDTE.Document document, UInt32 currentElement, UInt32 maxElements, UInt32 succesCount, UInt32 failedCount)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new EventHandlerProgress1B(onProgressB), new object[] { sender, e, document, currentElement, maxElements, succesCount, failedCount });
            }
            else
            {
                this.progressBar1.Style   = ProgressBarStyle.Blocks;
                this.progressBar1.Value   = (int)currentElement;
                this.progressBar1.Minimum = 0;
                this.progressBar1.Maximum = (int)maxElements;

                this.lProject.Text   = "---------";
                this.lFile.Text      = System.IO.Path.GetFileName(document.FullName);
                this.m_lSuccess.Text = succesCount.ToString();
                this.m_lFailed.Text  = failedCount.ToString();
            }
        }
        protected override void CommandAction(DTEHelper helper)
        {
            EnvDTE.Document document = helper.GetOpenedDocumentInCodeWindow(FileOperations.SupportsXmlType);

            if (document != null)
            {
                var objTextDoc = document.Object(nameof(EnvDTE.TextDocument));
                if (objTextDoc != null &&
                    objTextDoc is EnvDTE.TextDocument textDocument
                    )
                {
                    string fetchXml = textDocument.StartPoint.CreateEditPoint().GetText(textDocument.EndPoint);

                    string codeCSharp = ContentComparerHelper.ConvertFetchXmlToQueryExpression(fetchXml);

                    ClipboardHelper.SetText(codeCSharp);
                }
            }
        }
示例#15
0
        /// <summary>
        /// Map an EnvDTE.Document, used for files outside of the current solution eg. [from metadata]
        /// </summary>
        /// <param name="document">An EnvDTE.Document</param>
        /// <returns>List of found code items</returns>
        public static List <CodeItem> MapDocument(EnvDTE.Document document)
        {
            var text = DocumentHelper.GetText(document);

            if (string.IsNullOrEmpty(text))
            {
                return(new List <CodeItem>());
            }

            _tree = CSharpSyntaxTree.ParseText(text);

            var mscorlib    = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
            var compilation = CSharpCompilation.Create("CodeNavCompilation", new[] { _tree }, new[] { mscorlib });

            _semanticModel = compilation.GetSemanticModel(_tree);

            var root = (CompilationUnitSyntax)_tree.GetRoot();

            return(root.Members.Select(MapMember).ToList());
        }
示例#16
0
        private void DocumentEvents_DocumentSaved(EnvDTE.Document document)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            using (_performanceTracer?.Start("DTE event: Document saved"))
            {
                if (!AffectsResourceFile(document))
                {
                    return;
                }

                var resourceManager = ExportProvider.GetExportedValue <ResourceManager>();
                if (resourceManager.IsSaving)
                {
                    return;
                }

                // Run custom tool (usually attached to neutral language) even if a localized language changes,
                // e.g. if custom tool is a text template, we might want not only to generate the designer file but also
                // extract some localization information.
                // => find the resource entity that contains the document and run the custom tool on the neutral project file.

#pragma warning disable VSTHRD010 // Accessing ... should only be done on the main thread.
                bool Predicate(ResourceEntity e) => e.Languages.Select(lang => lang.ProjectFile)
                .OfType <DteProjectFile>()
                .Any(projectFile => projectFile.ProjectItems.Any(p => p.Document == document));

#pragma warning restore VSTHRD010 // Accessing ... should only be done on the main thread.

                var entity = resourceManager.ResourceEntities.FirstOrDefault(Predicate);

                var neutralProjectFile = entity?.NeutralProjectFile as DteProjectFile;

                // VS will run the custom tool on the project item only. Run the custom tool on any of the descendants, too.
                var projectItems = neutralProjectFile?.ProjectItems.SelectMany(projectItem => projectItem.Descendants());

                _customToolRunner.Enqueue(projectItems);

                ReloadSolution();
            }
        }
        void DocumentEvents_DocumentSaved(EnvDTE.Document document)
        {
            try
            {
                if (document.Name.EndsWith(".cs") ||
                    document.Name.EndsWith(".css") ||
                    document.Name.EndsWith(".js") ||
                    document.Name.EndsWith(".ts"))
                {
                    document.DTE.ExecuteCommand("Edit.FormatDocument");
                }

                if (!document.Saved)
                {
                    document.Save();
                }
            }
            catch
            {
            }
        }
        private static bool TrySetContent(EnvDTE.Document document, XDocument value)
        {
            try
            {
                var textDocument = (EnvDTE.TextDocument)document?.Object(@"TextDocument");
                if (textDocument == null)
                {
                    return(false);
                }

                var text = value.Declaration + Environment.NewLine + value;

                textDocument.CreateEditPoint().ReplaceText(textDocument.EndPoint, text, 0);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#19
0
        static public IEnumerable <SymbolData> GeneratorFromDocument(EnvDTE.Document document)
        {
            if (null != document)
            {
                if (document.Saved)
                {
                    return(GeneratorFromFile(document.FullName));
                }
                else
                {
                    EnvDTE.TextDocument doc = (EnvDTE.TextDocument)Common.Instance.DTE2.ActiveDocument.Object("TextDocument");
                    if (doc != null)
                    {
                        string fileContent = doc.StartPoint.CreateEditPoint().GetText(doc.EndPoint);

                        return(GeneratorFromString(fileContent, Path.GetExtension(document.FullName)));
                    }
                }
            }
            return(null);
        }
示例#20
0
        /// <summary>
        ///  Return the currently active file and cursor position within the file in
        ///  the preferred Visual Studio instance.
        /// </summary>
        /// <param name="databasePath">Elfie Database Path to help select correct VS instance</param>
        /// <returns>LocationWithinFile containing open file and cursor position</returns>
        public static LocationWithinFile GetCurrentLocation(string databasePath = null)
        {
            List <string> fullHintList = new List <string>();

            if (!String.IsNullOrEmpty(databasePath))
            {
                fullHintList.Add(databasePath);
            }

            EnvDTE.DTE dte = GetPreferredDTE(fullHintList);

            // Ask VS to open the desired file
            MessageFilter.Register();

            try
            {
                // Show the Main Window
                EnvDTE.Document document = dte.ActiveDocument;
                if (document == null)
                {
                    Trace.WriteLine("No active document found.");
                    return(null);
                }

                EnvDTE.TextSelection selection = document.Selection as EnvDTE.TextSelection;
                if (selection == null)
                {
                    Trace.WriteLine(String.Format("Unable to find cursor position in {0}", document.FullName));
                }

                return(new LocationWithinFile()
                {
                    FilePath = document.FullName, Line = selection.ActivePoint.Line, CharInLine = selection.ActivePoint.LineCharOffset
                });
            }
            finally
            {
                MessageFilter.Revoke();
            }
        }
示例#21
0
        /// <summary>
        /// Map the active document in the workspace
        /// </summary>
        /// <param name="activeDocument">active EnvDTE.document</param>
        /// <param name="control">CodeNav control that will show the result</param>
        /// <param name="workspace">Current Visual Studio workspace</param>
        /// <returns>List of found code items</returns>
        public static async Task <List <CodeItem> > MapDocumentAsync(EnvDTE.Document activeDocument, ICodeViewUserControl control,
                                                                     VisualStudioWorkspace workspace)
        {
            _control = control;

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

            try
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var filePath = DocumentHelper.GetFullName(activeDocument);

                if (string.IsNullOrEmpty(filePath))
                {
                    return(MapDocument(activeDocument));
                }

                var id = workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault();

                // We can not find the requested document in the current solution,
                // Try and map it in a different way
                if (id == null)
                {
                    return(MapDocument(activeDocument));
                }

                var document = workspace.CurrentSolution.GetDocument(id);

                return(await MapDocumentAsync(document));
            }
            catch (Exception e)
            {
                LogHelper.Log("Error during mapping", e, null, activeDocument.Language);
                return(null);
            }
        }
示例#22
0
        /// <summary>
        /// Map the active document in the workspace
        /// </summary>
        /// <param name="activeDocument">active EnvDTE.document</param>
        /// <param name="control">CodeNav control that will show the result</param>
        /// <param name="workspace">Current Visual Studio workspace</param>
        /// <returns>List of found code items</returns>
        public static List <CodeItem> MapDocument(EnvDTE.Document activeDocument, CodeViewUserControl control,
                                                  VisualStudioWorkspace workspace)
        {
            _control = control;

            if (workspace == null)
            {
                LogHelper.Log("Error during mapping: Workspace is null");
                return(null);
            }

            try
            {
                var filePath = DocumentHelper.GetFullName(activeDocument);

                if (string.IsNullOrEmpty(filePath))
                {
                    return(MapDocument(activeDocument));
                }

                var id = workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath).FirstOrDefault();

                // We can not find the requested document in the current solution,
                // Try and map it in a different way
                if (id == null)
                {
                    return(MapDocument(activeDocument));
                }

                var document = workspace.CurrentSolution.GetDocument(id);

                return(MapDocument(document));
            }
            catch (Exception e)
            {
                LogHelper.Log($"Error during mapping: {e}");
                LogHelper.Log("Error during mapping", e, DocumentHelper.GetText(activeDocument));
                return(null);
            }
        }
示例#23
0
        private static Selection GetSelection([NotNull] EnvDTE.Document document)
        {
            var textDocument = (EnvDTE.TextDocument)document.Object(@"TextDocument");

            var topPoint = textDocument?.Selection?.TopPoint;

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

            var line = textDocument.CreateEditPoint()?.GetLines(topPoint.Line, topPoint.Line + 1);

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

            var fileCodeModel = document.ProjectItem?.FileCodeModel;

            return(new Selection(textDocument, line, fileCodeModel));
        }
示例#24
0
        private void DocumentEvents_DocumentSaved([NotNull] EnvDTE.Document document)
        {
            Contract.Requires(document != null);

            Tracer.WriteLine("DTE event: Document saved");

            if (!AffectsResourceFile(document))
            {
                return;
            }

            var resourceManager = CompositionHost.GetExportedValue <ResourceManager>();

            if (resourceManager.IsSaving)
            {
                return;
            }

            // Run custom tool (usually attached to neutral language) even if a localized language changes,
            // e.g. if custom tool is a text template, we might want not only to generate the designer file but also
            // extract some localization information.
            // => find the resource entity that contains the document and run the custom tool on the neutral project file.

            // ReSharper disable once PossibleNullReferenceException
            bool Predicate(ResourceEntity e) => e.Languages.Select(lang => lang.ProjectFile)
            .OfType <DteProjectFile>()
            .Any(projectFile => projectFile.ProjectItems.Any(p => p.Document == document));

            var entity = resourceManager.ResourceEntities.FirstOrDefault(Predicate);

            var neutralProjectFile = (DteProjectFile)entity?.NeutralProjectFile;

            // VS will run the custom tool on the project item only. Run the custom tool on any of the descendants, too.
            var projectItems = neutralProjectFile?.ProjectItems.SelectMany(projectItem => projectItem.Descendants());

            _customToolRunner.Enqueue(projectItems);

            ReloadSolution();
        }
示例#25
0
        public bool CanMoveToResource(EnvDTE.Document document)
        {
            var extension = Path.GetExtension(document?.FullName);

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

            var configuration = _compositionHost.GetExportedValue <DteConfiguration>();

            var configurations = configuration.MoveToResources.Items
                                 .Where(item => item.ParseExtensions().Contains(extension, StringComparer.OrdinalIgnoreCase));

            if (!configurations.Any())
            {
                return(false);
            }

            Contract.Assume(document != null);
            var selection = GetSelection(document);

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

            if (!selection.Begin.EqualTo(selection.End))
            {
                return(true);
            }

            IParser parser = new GenericParser();

            var s = parser.LocateString(selection, false);

            return(s != null);
        }
示例#26
0
        internal async static Task <Document> GetActiveDocumentAsync()
        {
            EnvDTE80.DTE2 dte = await GetDTEServiceAsync();

            EnvDTE.Document activeDocument = dte?.ActiveDocument;
            if (activeDocument == null)
            {
                return(null);
            }

            VisualStudioWorkspace workspace = await GetVisualStudioWorkspaceAsync();

            ImmutableArray <DocumentId> documentIds = workspace.CurrentSolution.GetDocumentIdsWithFilePath(activeDocument.FullName);

            if (documentIds.Length == 0)
            {
                return(null);
            }
            DocumentId documentId = documentIds[0];
            Document   document   = workspace.CurrentSolution.GetDocument(documentId);

            return(document);
        }
示例#27
0
        void DocEvents_DocumentSaved(EnvDTE.Document document)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try
            {
                if (document.Name.EndsWith(".cs") ||
                    document.Name.EndsWith(".css") ||
                    document.Name.EndsWith(".js") ||
                    document.Name.EndsWith(".ts"))
                {
                    document.DTE.ExecuteCommand("Edit.FormatDocument");
                }

                if (!document.Saved)
                {
                    document.Save();
                }
            }
            catch
            {
            }
        }
示例#28
0
        /// <summary>
        /// Map an EnvDTE.Document, used for files outside of the current solution eg. [from metadata]
        /// </summary>
        /// <param name="document">An EnvDTE.Document</param>
        /// <returns>List of found code items</returns>
        public static List <CodeItem> MapDocument(EnvDTE.Document document)
        {
            var text = DocumentHelper.GetText(document);

            if (string.IsNullOrEmpty(text))
            {
                return(new List <CodeItem>());
            }

            switch (LanguageHelper.GetLanguage(document.Language))
            {
            case LanguageEnum.CSharp:
                _tree = CSharpSyntaxTree.ParseText(text);

                var mscorlib    = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
                var compilation = CSharpCompilation.Create("CodeNavCompilation", new[] { _tree }, new[] { mscorlib });
                _semanticModel = compilation.GetSemanticModel(_tree);

                var root = (CompilationUnitSyntax)_tree.GetRoot();

                return(root.Members.Select(MapMember).ToList());

            case LanguageEnum.VisualBasic:
                _tree = VisualBasic.VisualBasicSyntaxTree.ParseText(text);

                var mscorlibVB    = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
                var compilationVB = VisualBasic.VisualBasicCompilation.Create("CodeNavCompilation", new[] { _tree }, new[] { mscorlibVB });
                _semanticModel = compilationVB.GetSemanticModel(_tree);

                var rootVB = (VisualBasicSyntax.CompilationUnitSyntax)_tree.GetRoot();

                return(rootVB.Members.Select(MapMember).ToList());

            default:
                return(new List <CodeItem>());
            }
        }
示例#29
0
        public static bool GetTextBufferAndView(EnvDTE.DTE dte, EnvDTE.Document document, out ITextBuffer buffer, out IWpfTextView wpfView)
        {
            buffer  = null;
            wpfView = null;

            using (ServiceProvider serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte))
            {
                var componentModel = (IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SComponentModel));
                var editorAdapterFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

                IVsUIHierarchy uiHierarchy;
                uint           itemID;
                IVsWindowFrame windowFrame;
                if (VsShellUtilities.IsDocumentOpen(
                        serviceProvider,
                        document.FullName,
                        Guid.Empty,
                        out uiHierarchy,
                        out itemID,
                        out windowFrame))
                {
                    IVsTextView  view = VsShellUtilities.GetTextView(windowFrame);
                    IVsTextLines lines;
                    if (view.GetBuffer(out lines) == 0)
                    {
                        var buf = lines as IVsTextBuffer;
                        if (buf != null)
                        {
                            buffer  = editorAdapterFactoryService.GetDataBuffer(buf);
                            wpfView = editorAdapterFactoryService.GetWpfTextView(view);
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
示例#30
0
        private void SaveMacroIfDirty(string path)
        {
            try
            {
                EnvDTE.Document doc = this.dte.Documents.Item(path);

                if (!doc.Saved)
                {
                    if (VSConstants.MessageBoxResult.IDYES == this.ShowMessageBox(
                            string.Format(Resources.MacroNotSavedBeforePlayback, Path.GetFileNameWithoutExtension(path)),
                            OLEMSGBUTTON.OLEMSGBUTTON_YESNO))
                    {
                        doc.Save();
                    }
                }
            }
            catch (Exception e)
            {
                if (ErrorHandler.IsCriticalException(e))
                {
                    throw;
                }
            }
        }
示例#31
0
		public ORMExtensionManager(EnvDTE.ProjectItem projectItem, EnvDTE.Document document, Stream stream)
		{
			myProjectItem = projectItem;
			myDocument = document;
			myStream = stream;
		}
示例#32
0
		/// <summary>
		/// Return a sorted array of loaded extensions
		/// </summary>
		public string[] GetLoadedExtensions(IServiceProvider serviceProvider)
		{
			string[] retVal = myLoadedExtensions;
			if (retVal == null)
			{
				if (myDocument == null && myProjectItem != null)
				{
					myDocument = myProjectItem.Document;
				}

				object documentExtensionManager;
				MethodInfo methodInfo;
				string itemPath = null;
				if (null != myDocument &&
					null != (documentExtensionManager = ORMCustomToolUtility.GetDocumentExtension<object>(myDocument, "ORMExtensionManager", itemPath = myProjectItem.get_FileNames(0), serviceProvider)) &&
					null != (methodInfo = documentExtensionManager.GetType().GetMethod("GetLoadedExtensions", Type.EmptyTypes)))
				{
					retVal = methodInfo.Invoke(documentExtensionManager, null) as string[];
					myDocument = null; // No longer needed
				}
				Stream stream = null;
				if (null == retVal)
				{
					// First used the passed in stream
					stream = myStream;

					// Next use an open text document. Note that this will already have provided
					// an extension manager if this is an open ORM designer
					if (stream == null && myDocument != null)
					{
						EnvDTE.TextDocument textDoc = ORMCustomToolUtility.GetDocumentExtension<EnvDTE.TextDocument>(myDocument, "TextDocument", itemPath ?? (itemPath = myProjectItem.get_FileNames(0)), serviceProvider);
						if (textDoc != null)
						{
							// Note that the stream will be closed with the default reader settings of the XmlReader below
							stream = new MemoryStream(Encoding.UTF8.GetBytes(textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint)), false);
						}
					}

					// Try the file directly from the project item
					if (stream == null && myProjectItem != null)
					{
						// Note that the stream will be closed with the default reader settings of the XmlReader below
						stream = new FileStream(myProjectItem.get_FileNames(0), FileMode.Open);
					}
				}
				if (stream != null)
				{
					// Attempt to open the stream as an Xml file to
					// get the required extensions from the Xml
					string[] namespaces = null;
					int namespaceCount = 0;
					try
					{
						XmlReaderSettings readerSettings = new XmlReaderSettings();
						readerSettings.CloseInput = true;
						using (XmlReader reader = XmlReader.Create(stream, readerSettings))
						{
							reader.MoveToContent();
							if (reader.NodeType == XmlNodeType.Element)
							{
								int attributeCount = reader.AttributeCount;
								if (attributeCount != 0)
								{
									namespaces = new string[attributeCount];
									if (reader.MoveToFirstAttribute())
									{
										do
										{
											if (reader.Prefix == "xmlns" || reader.Name == "xmlns")
											{
												// Note that some of these are standard, not extensions, but it
												// isn't worth the trouble to add extra ORM knowledge here to figure it out
												string value = reader.Value;
												if (!string.IsNullOrEmpty(value))
												{
													namespaces[namespaceCount] = reader.Value;
													++namespaceCount;
												}
											}
										} while (reader.MoveToNextAttribute());
									}
								}
							}
						}
					}
					catch (XmlException)
					{
						// Nothing to do
					}
					finally
					{
						if (myStream != null)
						{
							myStream.Seek(0, SeekOrigin.Begin);
							myStream = null;
						}
					}
					if (namespaceCount != 0)
					{
						if (namespaceCount != namespaces.Length)
						{
							Array.Resize(ref namespaces, namespaceCount);
						}
						retVal = namespaces;
					}
				}
				if (retVal == null)
				{
					retVal = new string[0];
				}
				else
				{
					Array.Sort<string>(retVal);
				}
				myLoadedExtensions = retVal;
			}
			return retVal;
		}