Exemple #1
0
        public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity)
        {
            var peRef = reference as PortableExecutableReference;

            if (peRef != null && peRef.FilePath != null)
            {
                var metadata = new Dictionary <string, string>();
                if (!peRef.Properties.Aliases.IsEmpty)
                {
                    metadata.Add("Aliases", string.Join(",", peRef.Properties.Aliases));
                }

                if (IsInGAC(peRef.FilePath) && identity != null)
                {
                    // Since the location of the reference is in GAC, need to use full identity name to find it again.
                    // This typically happens when you base the reference off of a reflection assembly location.
                    _loadedProject.AddItem("Reference", identity.GetDisplayName(), metadata);
                }
                else if (IsFrameworkReferenceAssembly(peRef.FilePath))
                {
                    // just use short name since this will be resolved by msbuild relative to the known framework reference assemblies.
                    var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath);
                    _loadedProject.AddItem("Reference", fileName, metadata);
                }
                else // other location -- need hint to find correct assembly
                {
                    string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath);
                    var    fileName     = Path.GetFileNameWithoutExtension(peRef.FilePath);
                    metadata.Add("HintPath", relativePath);
                    _loadedProject.AddItem("Reference", fileName, metadata);
                }
            }
        }
Exemple #2
0
        private static void UpdateCodeAnalysisRuleSetPropertyInConfiguration(EnvDTE.Configuration config, string oldRuleSetFilePath, string newRuleSetFilePath, string projectDirectoryFullPath)
        {
            EnvDTE.Properties properties = config.Properties;
            try
            {
                EnvDTE.Property codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet");

                if (codeAnalysisRuleSetFileProperty != null)
                {
                    string codeAnalysisRuleSetFileName = codeAnalysisRuleSetFileProperty.Value as string;
                    if (!string.IsNullOrWhiteSpace(codeAnalysisRuleSetFileName))
                    {
                        string codeAnalysisRuleSetFullPath = FileUtilities.ResolveRelativePath(codeAnalysisRuleSetFileName, projectDirectoryFullPath);
                        codeAnalysisRuleSetFullPath = FileUtilities.NormalizeAbsolutePath(codeAnalysisRuleSetFullPath);
                        oldRuleSetFilePath          = FileUtilities.NormalizeAbsolutePath(codeAnalysisRuleSetFullPath);

                        if (codeAnalysisRuleSetFullPath.Equals(oldRuleSetFilePath, StringComparison.OrdinalIgnoreCase))
                        {
                            string newRuleSetRelativePath = FilePathUtilities.GetRelativePath(projectDirectoryFullPath, newRuleSetFilePath);
                            codeAnalysisRuleSetFileProperty.Value = newRuleSetRelativePath;
                        }
                    }
                }
            }
            catch (ArgumentException)
            {
                // Unfortunately the properties collection sometimes throws an ArgumentException
                // instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet.
                // Ignore it and move on.
            }
        }
Exemple #3
0
        public bool TryGetSerializationPrefixAndVersion(Solution solution, string assemblyFilePath, out string prefix, out VersionStamp version)
        {
            prefix  = FilePathUtilities.GetRelativePath(solution.FilePath, assemblyFilePath);
            version = VersionStamp.Create(File.GetLastWriteTimeUtc(assemblyFilePath));

            return(true);
        }
Exemple #4
0
        /// <summary>
        /// this is for a metadata reference in a solution
        /// </summary>
        private static async Task <SymbolTreeInfo> LoadOrCreateAsync(Solution solution, IAssemblySymbol assembly, string filePath, CancellationToken cancellationToken)
        {
            // if assembly is not from a file, just create one on the fly
            if (filePath == null || !File.Exists(filePath) || !FilePathUtilities.PartOfFrameworkOrReferencePaths(filePath))
            {
                return(Create(VersionStamp.Default, assembly, cancellationToken));
            }

            // if solution is not from a disk, just create one.
            if (solution.FilePath == null || !File.Exists(solution.FilePath))
            {
                return(Create(VersionStamp.Default, assembly, cancellationToken));
            }

            // okay, see whether we can get one from persistence service.
            var relativePath = FilePathUtilities.GetRelativePath(solution.FilePath, filePath);
            var version      = VersionStamp.Create(File.GetLastWriteTimeUtc(filePath));

            var persistentStorageService = solution.Workspace.Services.GetService <IPersistentStorageService>();

            // attempt to load from persisted state. metadata reference is solution wise information
            SymbolTreeInfo info;

            using (var storage = persistentStorageService.GetStorage(solution))
            {
                var key = PrefixMetadataSymbolTreeInfo + relativePath;
                using (var stream = await storage.ReadStreamAsync(key, cancellationToken).ConfigureAwait(false))
                {
                    if (stream != null)
                    {
                        using (var reader = new ObjectReader(stream))
                        {
                            info = ReadFrom(reader);
                            if (info != null && VersionStamp.CanReusePersistedVersion(version, info.version))
                            {
                                return(info);
                            }
                        }
                    }
                }

                cancellationToken.ThrowIfCancellationRequested();

                // compute it if we couldn't load it from cache
                info = Create(version, assembly, cancellationToken);
                if (info != null)
                {
                    using (var stream = SerializableBytes.CreateWritableStream())
                        using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken))
                        {
                            info.WriteTo(writer);
                            stream.Position = 0;

                            await storage.WriteStreamAsync(key, stream, cancellationToken).ConfigureAwait(false);
                        }
                }
            }

            return(info);
        }
Exemple #5
0
        public override IScanner GetScanner(IVsTextLines buffer)
        {
            string filePath = FilePathUtilities.GetFilePath(buffer);

            // Return dynamic scanner based on file extension
            return(NShaderScannerFactory.GetShaderScanner(filePath));
        }
        public void VsTextViewCreated(IVsTextView textViewAdapter)
        {
            IVsTextLines textlines;

            textViewAdapter.GetBuffer(out textlines);
            if (textlines != null)
            {
                Guid langId;
                textlines.GetLanguageServiceID(out langId);
                if (langId == GuidStrings.guidLanguageService)          // is our language service active ?
                {
                    string fileName = FilePathUtilities.GetFilePath(textlines);
                    if (!IsOurFile(fileName))       // is this a file node from Vulcan ?
                    {
                        Guid guidVulcanLanguageService = GuidStrings.guidVulcanLanguageService;
                        textlines.SetLanguageServiceID(guidVulcanLanguageService);
                        return;
                    }
                    //
                    // Only capturing keystroke for OUR languageService... ???
                    //
                    IWpfTextView textView = AdaptersFactory.GetWpfTextView(textViewAdapter);
                    Debug.Assert(textView != null);
                    CommandFilter     filter = new CommandFilter(textView, CompletionBroker, NavigatorService.GetTextStructureNavigator(textView.TextBuffer), SignatureHelpBroker, aggregator);
                    IOleCommandTarget next;
                    textViewAdapter.AddCommandFilter(filter, out next);
                    filter.Next = next;
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates a content loader for specified file.
        /// </summary>
        /// <param name="path">An absolute file path.</param>
        /// <param name="defaultEncoding">
        /// Specifies an encoding to be used if the actual encoding can't be determined from the stream content (the stream doesn't start with Byte Order Mark).
        /// If not specified auto-detect heuristics are used to determine the encoding. If these heuristics fail the decoding is assumed to be <see cref="Encoding.Default"/>.
        /// Note that if the stream starts with Byte Order Mark the value of <paramref name="defaultEncoding"/> is ignored.
        /// </param>
        /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="path"/> is not an absolute path.</exception>
        public FileTextLoader(string path, Encoding defaultEncoding)
        {
            FilePathUtilities.RequireAbsolutePath(path, "path");

            _path            = path;
            _defaultEncoding = defaultEncoding;
        }
Exemple #8
0
        private string Combine(string path1, string path2)
        {
            if (FilePathUtilities.TryCombine(path1, path2, out var result))
            {
                return(result);
            }

            return(string.Empty);
        }
Exemple #9
0
        private DocumentId GetDocumentId(IVsTextLines buffer)
        {
            var filePath  = FilePathUtilities.GetFilePath(buffer) + ".cs";
            var documents = _workspace
                            .CurrentSolution
                            .GetDocumentIdsWithFilePath(filePath);

            return(documents.SingleOrDefault());
        }
Exemple #10
0
        public void GetRelativePath_UpTwoLevelsAndThenDown()
        {
            string baseDirectory = @"C:\Alpha\Beta\Gamma";
            string fullPath      = @"C:\Alpha\Phi\Omega\Doc.txt";

            string result = FilePathUtilities.GetRelativePath(baseDirectory, fullPath);

            Assert.Equal(expected: @"..\..\Phi\Omega\Doc.txt", actual: result);
        }
Exemple #11
0
        public void RemoveDocument(string filePath)
        {
            var relativePath = FilePathUtilities.GetRelativePath(this.loadedProject.DirectoryPath, filePath);

            foreach (var item in this.loadedProject.GetItems("Compile").Where(i => i.EvaluatedInclude == relativePath).ToList())
            {
                this.loadedProject.RemoveItem(item);
            }
        }
Exemple #12
0
        public override Source CreateSource(IVsTextLines buffer)
        {
            var filePath = FilePathUtilities.GetFilePath(buffer) + ".cs";
            ImmutableArray <DocumentId> documents = _workspace.CurrentSolution.GetDocumentIdsWithFilePath(filePath);

            var documentId = documents[0];

            return(new ExcessSource(this, buffer, new Colorizer(this, buffer, GetScanner(buffer)), _workspace, documentId));
        }
Exemple #13
0
        public void GetRelativePath_OnADifferentDrive()
        {
            string baseDirectory = @"C:\Alpha\Beta\Gamma";
            string fullPath      = @"D:\Alpha\Beta\Gamma\Doc.txt";

            string result = FilePathUtilities.GetRelativePath(baseDirectory, fullPath);

            Assert.Equal(expected: @"D:\Alpha\Beta\Gamma\Doc.txt", actual: result);
        }
Exemple #14
0
        public void GetRelativePath_NestedTwoLevelsDown()
        {
            string baseDirectory = @"C:\Alpha\Beta\Gamma";
            string fullPath      = @"C:\Alpha\Beta\Gamma\Delta\Epsilon\Doc.txt";

            string result = FilePathUtilities.GetRelativePath(baseDirectory, fullPath);

            Assert.Equal(expected: @"Delta\Epsilon\Doc.txt", actual: result);
        }
Exemple #15
0
        internal void SetBufferCoordinator(IVsTextBufferCoordinator coordinator)
        {
            _bufferCoordinator = coordinator;

            var primaryBuffer = GetPrimaryTextLines();

            _primaryFileIndex = Location.GetFileIndex(FilePathUtilities.GetFilePath(primaryBuffer));
            _primaryToSecondaryFilesMap[_primaryFileIndex] = FileIndex;
        }
        public void GetRelativePath_WithBaseDirectoryMatchingIncompletePortionOfFullPath()
        {
            string baseDirectory = @"C:\Alpha\Beta";
            string fullPath      = @"C:\Alpha\Beta2\Gamma";

            string result = FilePathUtilities.GetRelativePath(baseDirectory, fullPath);

            Assert.Equal(expected: @"..\Beta2\Gamma", actual: result);
        }
        public void AddAnalyzerReference(AnalyzerReference reference)
        {
            var fileRef = reference as AnalyzerFileReference;

            if (fileRef != null)
            {
                string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);
                _loadedProject.AddItem("Analyzer", relativePath);
            }
        }
        private string Combine(string path1, string path2)
        {
            string result;
            if (FilePathUtilities.TryCombine(path1, path2, out result))
            {
                return result;
            }

            return string.Empty;
        }
        public void RemoveProjectReference(string projectName, string projectFilePath)
        {
            string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);
            var    item         = FindProjectReferenceItem(projectName, projectFilePath);

            if (item != null)
            {
                _loadedProject.RemoveItem(item);
            }
        }
Exemple #20
0
        public override IScanner GetScanner(IVsTextLines buffer)
        {
            // Since Visual Studio handles language service associations by file
            // extension, CMakeLanguageService must handle all *.txt files in order to
            // handle CMakeLists.txt.  Detect if the buffer represents an ordinary text
            // files.  If so, disable syntax highlighting.  This is a kludge, but it's
            // the best that can be done here.
            string path = FilePathUtilities.GetFilePath(buffer);

            return(new CMakeScanner(!CMakeSource.IsCMakeFile(path)));
        }
Exemple #21
0
        private void SetActiveRuleSetHandler(object sender, EventArgs e)
        {
            if (_tracker.SelectedHierarchy.TryGetProject(out var project) &&
                _tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out var ruleSetFileFullPath))
            {
                string projectDirectoryFullPath = Path.GetDirectoryName(project.FullName);
                string ruleSetFileRelativePath  = FilePathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath);

                UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath);
            }
        }
Exemple #22
0
        public override Source CreateSource(IVsTextLines buffer)
        {
            var filePath = FilePathUtilities.GetFilePath(buffer);

            if (GlobalServices.GetProjectManagerForFile(filePath) == null)
            {
                return(base.CreateSource(buffer));
            }
            return(new BooSource(this, filePath, buffer, GetColorizer(buffer))
            {
                LastParseTime = 0
            });
        }
        public void RemoveDocument(string filePath)
        {
            var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);

            var items = _loadedProject.GetItems("Compile");
            var item  = items.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) ||
                                             FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath));

            if (item != null)
            {
                _loadedProject.RemoveItem(item);
            }
        }
Exemple #24
0
        public void VsTextViewCreated(IVsTextView textViewAdapter)
        {
            IVsTextLines textlines;

            textViewAdapter.GetBuffer(out textlines);
            if (textlines != null)
            {
                Guid langId;
                textlines.GetLanguageServiceID(out langId);
                IWpfTextView textView = AdaptersFactory.GetWpfTextView(textViewAdapter);
                Debug.Assert(textView != null);
                // Note that this may get called after the classifier has been instantiated

                if (langId == GuidStrings.guidLanguageService)          // is our language service active ?
                {
                    string fileName = FilePathUtilities.GetFilePath(textlines);
                    if (!IsOurSourceFile(fileName))       // is this a file node from Vulcan ?
                    {
                        // we always register the file in the classifier.
                        if (textView.TextBuffer.Properties.ContainsProperty(typeof(XSharpModel.XFile)))
                        {
                            textView.TextBuffer.Properties.RemoveProperty(typeof(XSharpModel.XFile));
                        }

                        Guid guidVulcanLanguageService = GuidStrings.guidVulcanLanguageService;
                        textlines.SetLanguageServiceID(guidVulcanLanguageService);
                        return;
                    }
                    //
                    // Only capturing keystroke for OUR languageService... ???
                    //

                    // Get XFile and assign it to the textbuffer
                    if (!textView.TextBuffer.Properties.ContainsProperty(typeof(XSharpModel.XFile)))
                    {
                        var file = XSharpModel.XSolution.FindFile(fileName);
                        if (file != null)
                        {
                            textView.TextBuffer.Properties.AddProperty(typeof(XSharpModel.XFile), file);
                            file.Interactive = true;
                        }
                    }
                    CommandFilter     filter = new CommandFilter(textView, CompletionBroker, NavigatorService.GetTextStructureNavigator(textView.TextBuffer), SignatureHelpBroker, aggregator, this);
                    IOleCommandTarget next;
                    textViewAdapter.AddCommandFilter(filter, out next);
                    filter.Next = next;
                }
            }
        }
        public void AddDocument(string filePath, string logicalPath = null)
        {
            var relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);

            Dictionary <string, string> metadata = null;

            if (logicalPath != null && relativePath != logicalPath)
            {
                metadata = new Dictionary <string, string>();
                metadata.Add("link", logicalPath);
                relativePath = filePath; // link to full path
            }

            _loadedProject.AddItem("Compile", relativePath, metadata);
        }
        public void AddProjectReference(string projectName, ProjectFileReference reference)
        {
            var metadata = new Dictionary <string, string>();

            metadata.Add("Name", projectName);

            if (!reference.Aliases.IsEmpty)
            {
                metadata.Add("Aliases", string.Join(",", reference.Aliases));
            }

            string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path);

            _loadedProject.AddItem("ProjectReference", relativePath, metadata);
        }
Exemple #27
0
        private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath)
        {
            var references = _loadedProject.GetItems("Reference");

            MSB.Evaluation.ProjectItem item = null;

            var fileName = Path.GetFileNameWithoutExtension(filePath);

            if (identity != null)
            {
                var shortAssemblyName = identity.Name;
                var fullAssemblyName  = identity.GetDisplayName();

                // check for short name match
                item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);

                // check for full name match
                if (item == null)
                {
                    item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0);
                }
            }

            // check for file path match
            if (item == null)
            {
                string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath);

                item = references.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, filePath) ||
                                                 FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) ||
                                                 FilePathUtilities.PathsEqual(GetHintPath(it), filePath) ||
                                                 FilePathUtilities.PathsEqual(GetHintPath(it), relativePath));
            }

            // check for partial name match
            if (item == null && identity != null)
            {
                var partialName = identity.Name + ",";
                var items       = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList();
                if (items.Count == 1)
                {
                    item = items[0];
                }
            }

            return(item);
        }
        public static async Task <string> UploadImage(Context context, Uri imageUri, string publicId, int size)
        {
            var account =
                new CloudinaryDotNet.Account(CloudName, ApiKey, ApiSecret);

            var cloudinary = new CloudinaryDotNet.Cloudinary(account);

            var uploadParams = new CloudinaryDotNet.Actions.ImageUploadParams
            {
                File     = new CloudinaryDotNet.Actions.FileDescription(FilePathUtilities.GetAbsoluteFilePath(context, GetImageUri(context, ResizeImage(context, imageUri, size)))),
                PublicId = publicId
            };

            var uploadResult = await cloudinary.UploadAsync(uploadParams);

            return(uploadResult.Uri.OriginalString);
        }
        public void RemoveAnalyzerReference(AnalyzerReference reference)
        {
            var fileRef = reference as AnalyzerFileReference;

            if (fileRef != null)
            {
                string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath);

                var analyzers = _loadedProject.GetItems("Analyzer");
                var item      = analyzers.FirstOrDefault(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) ||
                                                         FilePathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath));
                if (item != null)
                {
                    _loadedProject.RemoveItem(item);
                }
            }
        }
        private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath)
        {
            var    references   = _loadedProject.GetItems("ProjectReference");
            string relativePath = FilePathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath);

            MSB.Evaluation.ProjectItem item = null;

            // find by project file path
            item = references.First(it => FilePathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) ||
                                    FilePathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath));

            // try to find by project name
            if (item == null)
            {
                item = references.First(it => string.Compare(projectName, it.GetMetadataValue("Name"), StringComparison.OrdinalIgnoreCase) == 0);
            }

            return(item);
        }