HOWTO: Get the conditional compile symbols defined in the project for a source file (ITextView) in a Visual Studio Extension
Monday, August 31, 2015Fortunately the Visual Studio SDK provides a way at these values. Unfortunately, it's not as straight forward as I would have liked.
Conditionals given an ITextView
Here's a quick extension method I whipped up to pull the "defines" out of the project file given an ITextView/IWpfTextView.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | private static IEnumerable< string > Conditionals([NotNull] this ITextView textView) { if (textView == null ) throw new ArgumentNullException(nameof(textView)); // Get the text document from the text buffer (if it has one) ITextDocument textDocument; if (textView.TextBuffer.Properties.TryGetProperty( typeof (ITextDocument), out textDocument)) yield break ; var componentModel = ServiceProvider.GlobalProvider.GetService( typeof (SComponentModel)) as IComponentModel; // Get the VsServiceProvider var vsServiceProvider = componentModel?.DefaultExportProvider?.GetExportedValue<SVsServiceProvider>(); if (vsServiceProvider == null ) yield break ; // Get the DTE ... var dte = (DTE) vsServiceProvider.GetService( typeof (DTE)); ProjectItem projectItem = dte.Solution.FindProjectItem(textDocument.FilePath); Configuration activeConfiguration = projectItem?.ContainingProject?.ConfigurationManager?.ActiveConfiguration; var defineConstants = activeConfiguration?.Properties?.Item( "DefineConstants" )?.Value as string ; if (defineConstants == null ) yield break ; // DefineConstants entries are listed semicolon and comma delimiated, so we need to split on both. string [] constantSplit = defineConstants.Split( new [] { ';' , ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in constantSplit) yield return item.Trim(); // They can contain whitespace on either end, so we'll strip 'em. } |
Have a lot of fun!
Subscribe to:
Post Comments
(
Atom
)