Exemplo n.º 1
0
        public bool TryParseGeneratedFilePath(
            string filePath,
            [NotNullWhen(true)] out ProjectId?projectId,
            [NotNullWhen(true)] out string?generatorTypeName,
            [NotNullWhen(true)] out string?generatedSourceHintName)
        {
            if (!filePath.StartsWith(_temporaryDirectory))
            {
                projectId               = null;
                generatorTypeName       = null;
                generatedSourceHintName = null;
                return(false);
            }

            string fileName = Path.GetFileName(filePath);

            string[] parts = fileName.Split(new[] { '_' }, count: 3);

            generatorTypeName       = parts[1];
            generatedSourceHintName = parts[2];

            projectId = ProjectId.CreateFromSerialized(Guid.Parse(new FileInfo(filePath).Directory.Name));

            return(true);
        }
Exemplo n.º 2
0
        public static ProjectId DeserializeProjectId(ObjectReader reader, CancellationToken cancellationToken)
        {
            var guid      = new Guid(reader.ReadArray <byte>());
            var debugName = reader.ReadString();

            return(ProjectId.CreateFromSerialized(guid, debugName));
        }
            private (Project project, ISymbol symbol) TryResolveSymbolInCurrentSolution(
                Workspace workspace,
                string symbolKey
            )
            {
                if (
                    !Properties.TryGetValue(
                        MetadataSymbolOriginatingProjectIdGuid,
                        out var projectIdGuid
                    )
                    || !Properties.TryGetValue(
                        MetadataSymbolOriginatingProjectIdDebugName,
                        out var projectDebugName
                    )
                )
                {
                    return (null, null);
                }

                var project = workspace.CurrentSolution.GetProject(
                    ProjectId.CreateFromSerialized(Guid.Parse(projectIdGuid), projectDebugName)
                );

                if (project == null)
                {
                    return (null, null);
                }

                var compilation = project
                    .GetCompilationAsync(CancellationToken.None)
                    .WaitAndGetResult(CancellationToken.None);

                var symbol = SymbolKey.ResolveString(symbolKey, compilation).Symbol;
                return (project, symbol);
            }
        /// <summary>
        /// Adds a result to an existing Roslyn workspace.
        /// </summary>
        /// <param name="analyzerResult">The results from building a Buildalyzer project analyzer.</param>
        /// <param name="workspace">A Roslyn workspace.</param>
        /// <param name="addProjectReferences">
        /// <c>true</c> to add projects to the workspace for project references that exist in the same <see cref="AnalyzerManager"/>.
        /// If <c>true</c> this will trigger (re)building all referenced projects. Directly add <see cref="AnalyzerResult"/> instances instead if you already have them available.
        /// </param>
        /// <returns>The newly added Roslyn project, or <c>null</c> if the project couldn't be added to the workspace.</returns>
        public static Project AddToWorkspace(this IAnalyzerResult analyzerResult, Workspace workspace, bool addProjectReferences = false)
        {
            if (analyzerResult == null)
            {
                throw new ArgumentNullException(nameof(analyzerResult));
            }
            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            // Get or create an ID for this project
            ProjectId projectId = ProjectId.CreateFromSerialized(analyzerResult.ProjectGuid);

            // Cache the project references
            analyzerResult.Manager.WorkspaceProjectReferences[projectId.Id] = analyzerResult.ProjectReferences.ToArray();

            // Create and add the project, but only if it's a support Roslyn project type
            ProjectInfo projectInfo = GetProjectInfo(analyzerResult, workspace, projectId);

            if (projectInfo is null)
            {
                // Something went wrong (maybe not a support project type), so don't add this project
                return(null);
            }
            Solution solution = workspace.CurrentSolution.AddProject(projectInfo);

            // Check if this project is referenced by any other projects in the workspace
            foreach (Project existingProject in solution.Projects.ToArray())
            {
                if (!existingProject.Id.Equals(projectId) &&
                    analyzerResult.Manager.WorkspaceProjectReferences.TryGetValue(existingProject.Id.Id, out string[] existingReferences) &&
Exemplo n.º 5
0
            public ProjectId?Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
            {
                try
                {
                    if (reader.TryReadNil())
                    {
                        return(null);
                    }

                    Contract.ThrowIfFalse(reader.ReadArrayHeader() == 2);
                    var id        = GuidFormatter.Instance.Deserialize(ref reader, options);
                    var debugName = reader.ReadString();

                    var previousId = _previousProjectId;
                    if (previousId is not null && previousId.Id == id && previousId.DebugName == debugName)
                    {
                        return(previousId);
                    }

                    var currentId = ProjectId.CreateFromSerialized(id, debugName);
                    _previousProjectId = currentId;
                    return(currentId);
                }
                catch (Exception e) when(e is not MessagePackSerializationException)
                {
                    throw new MessagePackSerializationException(e.Message, e);
                }
            }
Exemplo n.º 6
0
        public void ProjectSnapshotHandleJsonConverter_Serialization_CanKindaRoundTrip()
        {
            // Arrange
            var snapshot = new ProjectSnapshotHandle(
                "Test.csproj",
                new ProjectSystemRazorConfiguration(
                    RazorLanguageVersion.Version_1_1,
                    "Test",
                    new[]
            {
                new ProjectSystemRazorExtension("Test-Extension1"),
                new ProjectSystemRazorExtension("Test-Extension2"),
            }),
                ProjectId.CreateFromSerialized(Guid.NewGuid(), "Test"));

            // Act
            var json = JsonConvert.SerializeObject(snapshot, Converters);
            var obj  = JsonConvert.DeserializeObject <ProjectSnapshotHandle>(json, Converters);

            // Assert
            Assert.Equal(snapshot.FilePath, obj.FilePath);
            Assert.Equal(snapshot.Configuration.ConfigurationName, obj.Configuration.ConfigurationName);
            Assert.Collection(
                snapshot.Configuration.Extensions.OrderBy(e => e.ExtensionName),
                e => Assert.Equal("Test-Extension1", e.ExtensionName),
                e => Assert.Equal("Test-Extension2", e.ExtensionName));
            Assert.Equal(snapshot.Configuration.LanguageVersion, obj.Configuration.LanguageVersion);
            Assert.Equal(snapshot.WorkspaceProjectId.Id, obj.WorkspaceProjectId.Id);
        }
Exemplo n.º 7
0
            public async Task TrackChangesAsync(CancellationToken cancellationToken)
            {
                var guids = await _callbackService.InvokeAsync <List <Guid> >(
                    _owner,
                    nameof(ICodeLensContext.GetDocumentId),
                    new object[] { Descriptor.ProjectGuid, Descriptor.FilePath },
                    cancellationToken).ConfigureAwait(false);

                if (guids == null)
                {
                    return;
                }

                var documentId = DocumentId.CreateFromSerialized(
                    ProjectId.CreateFromSerialized(guids[0], Descriptor.ProjectGuid.ToString()),
                    guids[1],
                    Descriptor.FilePath);

                if (documentId == null)
                {
                    return;
                }

                // this asks Roslyn OOP to start track workspace changes and call back Invalidate on this type when there is one.
                // each data point owns 1 connection which is alive while data point is alive. and all communication is done through
                // that connection
                await _endPoint.InvokeAsync(
                    nameof(IRemoteCodeLensReferencesService.TrackCodeLensAsync),
                    new object[] { documentId },
                    cancellationToken).ConfigureAwait(false);
            }
Exemplo n.º 8
0
        public static SupportedPlatformData GetSupportedPlatforms(
            CompletionItem item,
            Workspace workspace
            )
        {
            if (
                item.Properties.TryGetValue("InvalidProjects", out var invalidProjects) &&
                item.Properties.TryGetValue("CandidateProjects", out var candidateProjects)
                )
            {
                return(new SupportedPlatformData(
                           invalidProjects
                           .Split(projectSeperators)
                           .Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s)))
                           .ToList(),
                           candidateProjects
                           .Split(projectSeperators)
                           .Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s)))
                           .ToList(),
                           workspace
                           ));
            }

            return(null);
        }
        /// <summary>
        /// Adds a result to an existing Roslyn workspace.
        /// </summary>
        /// <param name="analyzerResult">The results from building a Buildalyzer project analyzer.</param>
        /// <param name="workspace">A Roslyn workspace.</param>
        /// <param name="addProjectReferences">
        /// <c>true</c> to add projects to the workspace for project references that exist in the same <see cref="AnalyzerManager"/>.
        /// If <c>true</c> this will trigger (re)building all referenced projects. Directly add <see cref="AnalyzerResult"/> instances instead if you already have them available.
        /// </param>
        /// <returns>The newly added Roslyn project.</returns>
        public static Project AddToWorkspace(this AnalyzerResult analyzerResult, Workspace workspace, bool addProjectReferences = false)
        {
            if (analyzerResult == null)
            {
                throw new ArgumentNullException(nameof(analyzerResult));
            }
            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            // Get or create an ID for this project
            ProjectId projectId = ProjectId.CreateFromSerialized(analyzerResult.ProjectGuid);

            // Cache the project references
            _projectReferences.AddOrUpdate(projectId, _ => analyzerResult.ProjectReferences.ToArray(), (_, __) => analyzerResult.ProjectReferences.ToArray());

            // Create and add the project
            ProjectInfo projectInfo = GetProjectInfo(analyzerResult, workspace, projectId);
            Solution    solution    = workspace.CurrentSolution.AddProject(projectInfo);

            // Check if this project is referenced by any other projects in the workspace
            foreach (Project existingProject in solution.Projects.ToArray())
            {
                if (!existingProject.Id.Equals(projectId) &&
                    _projectReferences.TryGetValue(existingProject.Id, out string[] existingReferences) &&
Exemplo n.º 10
0
        public async Task <LSP.CompletionItem> HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken)
        {
            if (!(completionItem.Data is CompletionResolveData data))
            {
                data = ((JToken)completionItem.Data).ToObject <CompletionResolveData>();
            }

            var documentId = DocumentId.CreateFromSerialized(ProjectId.CreateFromSerialized(data.ProjectGuid), data.DocumentGuid);
            var document   = context.Solution.GetAdditionalDocument(documentId);

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

            int offset = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(data.Position), cancellationToken).ConfigureAwait(false);

            var completionService = document.Project.LanguageServices.GetRequiredService <IXamlCompletionService>();
            var symbol            = await completionService.GetSymbolAsync(new XamlCompletionContext(document, offset), completionItem.Label, cancellationToken : cancellationToken).ConfigureAwait(false);

            if (symbol == null)
            {
                return(completionItem);
            }

            var description = await symbol.GetDescriptionAsync(document, offset, cancellationToken).ConfigureAwait(false);

            var vsCompletionItem = CloneVSCompletionItem(completionItem);

            vsCompletionItem.Description = new ClassifiedTextElement(description.Select(tp => new ClassifiedTextRun(tp.Tag.ToClassificationTypeName(), tp.Text)));
            return(vsCompletionItem);
        }
Exemplo n.º 11
0
        public bool TryParseGeneratedFilePath(
            string filePath,
            [NotNullWhen(true)] out ProjectId?projectId,
            [NotNullWhen(true)] out string?generatorTypeName,
            [NotNullWhen(true)] out string?generatorAssemblyName,
            [NotNullWhen(true)] out string?generatedSourceHintName)
        {
            if (!filePath.StartsWith(_temporaryDirectory))
            {
                projectId               = null;
                generatorTypeName       = null;
                generatorAssemblyName   = null;
                generatedSourceHintName = null;
                return(false);
            }

            var fileInfo     = new FileInfo(filePath);
            var generatorDir = fileInfo.Directory;
            var assemblyDir  = generatorDir.Parent;
            var projectDir   = assemblyDir.Parent;

            generatorTypeName       = generatorDir.Name;
            generatorAssemblyName   = assemblyDir.Name;
            generatedSourceHintName = fileInfo.Name;

            projectId = ProjectId.CreateFromSerialized(Guid.Parse(projectDir.Name));

            return(true);
        }
Exemplo n.º 12
0
        private void LoadSolution(string path)
        {
            Logger.Log("loading solution: " + path);
            string dir = Path.GetDirectoryName(path);

            SolutionId   solutionId   = SolutionId.CreateNewId();
            VersionStamp version      = VersionStamp.Create();
            SolutionInfo solutionInfo = SolutionInfo.Create(solutionId, version, path);

            solution = workspace.AddSolution(solutionInfo);

            using (FileStream file = File.OpenRead(path))
            {
                using StreamReader reader = new StreamReader(file);
                while (reader.EndOfStream == false)
                {
                    string line = reader.ReadLine();
                    if (line.StartsWith("Project"))
                    {
                        string pattern = @"^Project\(""\{.+?\}""\) = ""(\w+?)"", ""(.+?)"", ""\{(.+?)\}""";
                        Match  match   = Regex.Match(line, pattern);

                        string projectName = match.Groups[1].Value;
                        string projectPath = Path.Combine(dir, match.Groups[2].Value);
                        string projectGuid = match.Groups[3].Value;

                        LoadProject(projectName, projectPath, ProjectId.CreateFromSerialized(Guid.Parse(projectGuid)));
                    }
                }
            }

            Logger.Log("");
        }
Exemplo n.º 13
0
        public void when_reading_project_then_can_retrieve_info()
        {
            var props = new Dictionary <string, string>
            {
                { "Foo", "Bar" },
                { "CurrentSolutionConfigurationContents",
                  $@"<CurrentSolutionConfigurationContents xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
						<SolutionConfiguration xmlns=''>
							<ProjectConfiguration Project='{{F1DB354D-8DB4-476C-9308-08CDC0E411F7}}' AbsolutePath='{ModuleInitializer.BaseDirectory}\Content\CsLibrary\CsLibrary.csproj' BuildProjectInSolution='True'>Debug|AnyCPU</ProjectConfiguration>
							<ProjectConfiguration Project='{{3EDE89EC-A461-4E2C-BE95-05F63B96926C}}' AbsolutePath='{ModuleInitializer.BaseDirectory}\Content\PclLibrary\PclLibrary.csproj' BuildProjectInSolution='True'>Debug|AnyCPU</ProjectConfiguration>
						</SolutionConfiguration>
					</CurrentSolutionConfigurationContents>"                     }
            };

            var xml            = ProjectReader.Read(Path.Combine(ModuleInitializer.BaseDirectory, @"Content\CsLibrary\CsLibrary.csproj"), props);
            var msbuildProject = xml.ToDynamic();

            var info = ProjectInfo.Create(
                ProjectId.CreateFromSerialized(new Guid((string)msbuildProject["Id"])),
                VersionStamp.Default,
                (string)msbuildProject["Name"],
                (string)msbuildProject["AssemblyName"],
                (string)msbuildProject["Language"],
                (string)msbuildProject["FilePath"],
                outputFilePath: (string)msbuildProject["OutputFilePath"],
                projectReferences: ((XElement)msbuildProject.ProjectReferences).Elements("Project").Select(e => new ProjectReference(ProjectId.CreateFromSerialized(new Guid(e.Attribute("Id").Value)))),
                metadataReferences: ((XElement)msbuildProject.MetadataReferences).Elements("FilePath").Select(e => MetadataReference.CreateFromFile(e.Value)));
        }
Exemplo n.º 14
0
        public Task <GeneratedDocument> GenerateDocumentAsync(Guid projectIdBytes, string projectDebugName, string filePath, string text, CancellationToken cancellationToken = default(CancellationToken))
        {
            var projectId = ProjectId.CreateFromSerialized(projectIdBytes, projectDebugName);

            var engine = RazorEngine.Create();

            RazorSourceDocument source;

            using (var stream = new MemoryStream())
            {
                var bytes = Encoding.UTF8.GetBytes(text);
                stream.Write(bytes, 0, bytes.Length);

                stream.Seek(0L, SeekOrigin.Begin);
                source = RazorSourceDocument.ReadFrom(stream, filePath, Encoding.UTF8);
            }

            var code = RazorCodeDocument.Create(source);

            engine.Process(code);

            var csharp = code.GetCSharpDocument();

            if (csharp == null)
            {
                throw new InvalidOperationException();
            }

            return(Task.FromResult(new GeneratedDocument()
            {
                Text = csharp.GeneratedCode,
            }));
        }
Exemplo n.º 15
0
        public async Task Init(SolutionModel solutionModel)
        {
            IList <ProjectInfo> projectInfos = new List <ProjectInfo>(solutionModel.Projects.Count);

            foreach (var projectModel in solutionModel.Projects)
            {
                var projectId          = ProjectId.CreateFromSerialized(projectModel.Id);
                var documentInfos      = new List <DocumentInfo>(projectModel.Documents.Count);
                var projectReferences  = new List <ProjectReference>(projectModel.ProjectToProjectReferences.Count);
                var metadataReferences = new List <MetadataReference>(projectModel.ProjectAssemblyReferences.Count);

                foreach (var documentModel in projectModel.Documents)
                {
                    documentInfos.Add(DocumentInfo.Create(DocumentId.CreateNewId(projectId), documentModel.Name, null, SourceCodeKind.Regular, null, documentModel.Path));
                }
                foreach (var projectReference in projectModel.ProjectToProjectReferences)
                {
                    projectReferences.Add(new ProjectReference(ProjectId.CreateFromSerialized(projectReference.Id)));
                }
                foreach (var projectAssemblyReference in projectModel.ProjectAssemblyReferences)
                {
                    metadataReferences.Add(MetadataReference.CreateFromFile(projectAssemblyReference.LibraryPath));
                }

                var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, projectModel.Name,
                                                     projectModel.AssemblyName, LanguageNames.CSharp, projectModel.FilePath, null, null, null,
                                                     documentInfos, projectReferences, metadataReferences, null);
                projectInfos.Add(projectInfo);
            }
            _adhocWorkspace.AddSolution(SolutionInfo.Create(SolutionId.CreateFromSerialized(solutionModel.Id),
                                                            VersionStamp.Default, solutionModel.FilePath, projectInfos));
        }
Exemplo n.º 16
0
        public static ProjectId ProjectContextToProjectId(ProjectContext projectContext)
        {
            var delimiter = projectContext.Id.IndexOf('|');

            return(ProjectId.CreateFromSerialized(
                       Guid.Parse(projectContext.Id.Substring(0, delimiter)),
                       debugName: projectContext.Id.Substring(delimiter + 1)));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Adds a project to an existing Roslyn workspace.
        /// </summary>
        /// <param name="analyzer">The Buildalyzer project analyzer.</param>
        /// <param name="workspace">A Roslyn workspace.</param>
        /// <param name="addProjectReferences">
        /// <c>true</c> to add projects to the workspace for project references that exist in the same
        /// <see cref="AnalyzerManager" />.
        /// </param>
        /// <returns>The newly added Roslyn project.</returns>
        public static Project AddToWorkspace(this ProjectAnalyzer analyzer, AdhocWorkspace workspace, bool addProjectReferences = false)
        {
            if (analyzer == null)
            {
                throw new ArgumentNullException(nameof(analyzer));
            }

            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            // Get or create an ID for this project
            var projectGuid = analyzer.CompiledProject?.GetPropertyValue("ProjectGuid");
            var projectId   = !string.IsNullOrEmpty(projectGuid) &&
                              Guid.TryParse(analyzer.CompiledProject?.GetPropertyValue("ProjectGuid"), out var projectIdGuid)
                                        ? ProjectId.CreateFromSerialized(projectIdGuid)
                                        : ProjectId.CreateNewId();

            // Create and add the project
            var projectInfo = GetProjectInfo(analyzer, workspace, projectId);
            var solution    = workspace.CurrentSolution.AddProject(projectInfo);

            // Check if this project is referenced by any other projects in the workspace
            foreach (var existingProject in solution.Projects.ToArray())
            {
                if (!existingProject.Id.Equals(projectId) &&
                    analyzer.Manager.Projects.TryGetValue(existingProject.FilePath, out var existingAnalyzer) &&
                    (existingAnalyzer.GetProjectReferences()?.Contains(analyzer.ProjectFilePath) ?? false))
                {
                    // Add the reference to the existing project
                    var projectReference = new ProjectReference(projectId);
                    solution = solution.AddProjectReference(existingProject.Id, projectReference);
                }
            }

            // Apply solution changes
            if (!workspace.TryApplyChanges(solution))
            {
                throw new InvalidOperationException("Could not apply workspace solution changes");
            }

            // Add any project references not already added
            if (addProjectReferences)
            {
                foreach (var referencedAnalyzer in GetReferencedAnalyzerProjects(analyzer))
                {
                    // Check if the workspace contains the project inside the loop since adding one might also add this one due to transitive references
                    if (!workspace.CurrentSolution.Projects.Any(x => x.FilePath == referencedAnalyzer.ProjectFilePath))
                    {
                        AddToWorkspace(referencedAnalyzer, workspace, addProjectReferences);
                    }
                }
            }

            // Find and return this project
            return(workspace.CurrentSolution.GetProject(projectId));
        }
Exemplo n.º 18
0
        public Task <IEnumerable <DirectiveDescriptor> > GetDirectivesAsync(Guid projectIdBytes, string projectDebugName, CancellationToken cancellationToken = default(CancellationToken))
        {
            var projectId = ProjectId.CreateFromSerialized(projectIdBytes, projectDebugName);

            var engine     = RazorEngine.Create();
            var directives = engine.Features.OfType <IRazorDirectiveFeature>().FirstOrDefault()?.Directives;

            return(Task.FromResult(directives ?? Enumerable.Empty <DirectiveDescriptor>()));
        }
Exemplo n.º 19
0
        public async Task <TagHelperResolutionResult> GetTagHelpersAsync(Guid projectIdBytes, string projectDebugName, CancellationToken cancellationToken = default(CancellationToken))
        {
            var projectId = ProjectId.CreateFromSerialized(projectIdBytes, projectDebugName);

            var solution = await GetSolutionAsync(cancellationToken).ConfigureAwait(false);

            var project = solution.GetProject(projectId);

            var resolver = new DefaultTagHelperResolver(designTime: true);
            var result   = await resolver.GetTagHelpersAsync(project, cancellationToken).ConfigureAwait(false);

            return(result);
        }
Exemplo n.º 20
0
        internal static DocumentId?CreateDocIdFromEquivalenceKey(this FixAllContext fixAllContext)
        {
            var split = fixAllContext.CodeActionEquivalenceKey.Split(SemicolonSplit, StringSplitOptions.RemoveEmptyEntries);

            if (split.Length == 3 &&
                string.Equals(split[0], ApiDocEquivalenceKeyPrefix, StringComparison.Ordinal) &&
                Guid.TryParse(split[1], out var projectGuid) && projectGuid != Guid.Empty &&
                Guid.TryParse(split[2], out var docGuid) && docGuid != Guid.Empty)
            {
                var projectId = ProjectId.CreateFromSerialized(projectGuid);
                return(DocumentId.CreateFromSerialized(projectId, docGuid));
            }

            return(null);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.StartObject)
            {
                return(null);
            }

            var obj           = JObject.Load(reader);
            var filePath      = obj[nameof(ProjectSnapshotHandle.FilePath)].Value <string>();
            var configuration = obj[nameof(ProjectSnapshotHandle.Configuration)].ToObject <RazorConfiguration>(serializer);

            var id = obj[nameof(ProjectSnapshotHandle.WorkspaceProjectId)].Value <string>();
            var workspaceProjectId = id == null ? null : ProjectId.CreateFromSerialized(Guid.Parse(id));

            return(new ProjectSnapshotHandle(filePath, configuration, workspaceProjectId));
        }
        public override async Task <CompletionChange> GetChangeAsync(Document document, CompletionItem item, char?commitKey = default(char?), CancellationToken cancellationToken = default(CancellationToken))
        {
            var projectIdGuid = item.Properties[ProjectGuidKey];
            var projectId     = ProjectId.CreateFromSerialized(new System.Guid(projectIdGuid));
            var project       = document.Project.Solution.GetProject(projectId);
            var assemblyName  = item.DisplayText;
            var publicKey     = await GetPublicKeyOfProjectAsync(project, cancellationToken).ConfigureAwait(false);

            if (!string.IsNullOrEmpty(publicKey))
            {
                assemblyName += $", PublicKey={ publicKey }";
            }

            var textChange = new TextChange(item.Span, assemblyName);

            return(CompletionChange.Create(textChange));
        }
Exemplo n.º 23
0
        public async Task <LSP.CompletionItem> HandleRequestAsync(LSP.CompletionItem completionItem, RequestContext context, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(context.Solution);

            if (completionItem is not VSInternalCompletionItem vsCompletionItem)
            {
                return(completionItem);
            }

            CompletionResolveData?data;

            if (completionItem.Data is JToken token)
            {
                data = token.ToObject <CompletionResolveData>();
                Assumes.Present(data);
            }
            else
            {
                return(completionItem);
            }

            var documentId = DocumentId.CreateFromSerialized(ProjectId.CreateFromSerialized(data.ProjectGuid), data.DocumentGuid);
            var document   = context.Solution.GetDocument(documentId) ?? context.Solution.GetAdditionalDocument(documentId);

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

            var offset = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(data.Position), cancellationToken).ConfigureAwait(false);

            var completionService = document.Project.LanguageServices.GetRequiredService <IXamlCompletionService>();
            var symbol            = await completionService.GetSymbolAsync(new XamlCompletionContext(document, offset), completionItem.Label, cancellationToken : cancellationToken).ConfigureAwait(false);

            if (symbol == null)
            {
                return(completionItem);
            }

            var options     = _globalOptions.GetSymbolDescriptionOptions(document.Project.Language);
            var description = await symbol.GetDescriptionAsync(document, options, cancellationToken).ConfigureAwait(false);

            vsCompletionItem.Description = new ClassifiedTextElement(description.Select(tp => new ClassifiedTextRun(tp.Tag.ToClassificationTypeName(), tp.Text)));
            return(vsCompletionItem);
        }
Exemplo n.º 24
0
            public ProjectId?Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
            {
                try
                {
                    if (reader.TryReadNil())
                    {
                        return(null);
                    }

                    Contract.ThrowIfFalse(reader.ReadArrayHeader() == 2);
                    var id        = GuidFormatter.Instance.Deserialize(ref reader, options);
                    var debugName = reader.ReadString();

                    return(ProjectId.CreateFromSerialized(id, debugName));
                }
                catch (Exception e) when(e is not MessagePackSerializationException)
                {
                    throw new MessagePackSerializationException(e.Message, e);
                }
            }
Exemplo n.º 25
0
        public void Write()
        {
            var log = new TraceLog(5, "log");

            var projectId = ProjectId.CreateFromSerialized(
                Guid.Parse("5E40F37C-5AB3-495E-A3F2-4A244D177674")
                );
            var diagnostic = Diagnostic.Create(
                EditAndContinueDiagnosticDescriptors.GetDescriptor(
                    EditAndContinueErrorCode.ErrorReadingFile
                    ),
                Location.None,
                "file",
                "error"
                );

            log.Write("a");
            log.Write("b {0} {1} {2}", 1, "x", 3);
            log.Write("c");
            log.Write(
                "d str={0} projectId={1} summary={2} diagnostic=`{3}`",
                (string)null,
                projectId,
                ProjectAnalysisSummary.RudeEdits,
                diagnostic
                );
            log.Write("e");
            log.Write("f");

            AssertEx.Equal(
                new[]
            {
                "f",
                "b 1 x 3",
                "c",
                $"d str=<null> projectId=1324595798 summary=RudeEdits diagnostic=`{diagnostic.ToString()}`",
                "e"
            },
                log.GetTestAccessor().Entries.Select(e => e.GetDebuggerDisplay())
                );
        }
Exemplo n.º 26
0
        public KordueneWorkspace(SlnFile sln) : this()
        {
            SlnFile = sln;

            var guidSection = sln.Sections.GetSection("ExtensibilityGlobals", SlnSectionType.PostProcess);
            var id          = SolutionId.CreateFromSerialized(new Guid(guidSection.Properties.GetValue("SolutionGuid")));

            var solution = this.CreateSolution(SolutionInfo.Create(id, VersionStamp.Default, sln.FullPath));

            foreach (var item in sln.Projects)
            {
                var proj = ProjectInfo.Create(ProjectId.CreateFromSerialized(new Guid(item.Id)), VersionStamp.Default, item.Name, item.Name, LanguageNames.CSharp, Path.Combine(sln.BaseDirectory, item.FilePath));
                proj     = AddProjectDocuments(proj);
                proj     = AddDefaultReferences(proj);
                solution = solution.AddProject(proj);
            }

            var configs = sln.Sections.GetSection("SolutionConfigurationPlatforms");

            Configurations.Clear();
            foreach (var item in configs.Properties)
            {
                var configPlat = item.Value.Split("|");

                if (!Configurations.Contains(configPlat[0].Replace(" ", string.Empty)))
                {
                    Configurations.Add(configPlat[0]);
                }

                if (!Platforms.Contains(configPlat[1].Replace(" ", string.Empty)))
                {
                    Platforms.Add(configPlat[1].Replace(" ", string.Empty));
                }
            }

            this.SetCurrentSolution(solution);

            LoadProjectSymbols();
        }
Exemplo n.º 27
0
        public async Task <EmitResult> EmitAsync(
            Guid guid,
            string debugName,
            string outputFilePath,
            string win32ResourcesPath,
            ImmutableArray <ResourceDescription> manifestResources,
            EmitOptions options,
            string runtimeReferencePath,
            byte[] solutionChecksum)
        {
            var projectId = ProjectId.CreateFromSerialized(guid, debugName);
            var solution  = await RoslynServices.SolutionService.GetSolutionAsync(new Checksum(solutionChecksum), CancellationToken).ConfigureAwait(false);

            var project = solution.GetProject(projectId);

            return(await project.EmitAsync(
                       outputFilePath,
                       win32ResourcesPath,
                       manifestResources,
                       options,
                       runtimeReferencePath,
                       CancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 28
0
        private IEnumerable <(string, ProjectIdInfo)> GetProjectPathsAndIdsFromSolution(string solutionFilePath)
        {
            _logger.LogInformation($"Detecting projects in '{solutionFilePath}'.");

            var solutionFile      = SolutionFile.ParseFile(solutionFilePath);
            var processedProjects = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            var result            = new List <(string, ProjectIdInfo)>();

            foreach (var project in solutionFile.Projects)
            {
                if (project.IsNotSupported)
                {
                    continue;
                }

                // Solution files are assumed to contain relative paths to project files with Windows-style slashes.
                var projectFilePath = project.RelativePath.Replace('\\', Path.DirectorySeparatorChar);
                projectFilePath = Path.Combine(_environment.TargetDirectory, projectFilePath);
                projectFilePath = Path.GetFullPath(projectFilePath);

                // Have we seen this project? If so, move on.
                if (processedProjects.Contains(projectFilePath))
                {
                    continue;
                }

                if (string.Equals(Path.GetExtension(projectFilePath), ".csproj", StringComparison.OrdinalIgnoreCase))
                {
                    var projectIdInfo = new ProjectIdInfo(ProjectId.CreateFromSerialized(new Guid(project.ProjectGuid)), true);
                    result.Add((projectFilePath, projectIdInfo));
                }

                processedProjects.Add(projectFilePath);
            }

            return(result);
        }
Exemplo n.º 29
0
 public ProjectId Rehydrate()
 {
     return(ProjectId.CreateFromSerialized(Id, DebugName));
 }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     var(id, debugName) = ReadFromJsonObject(reader);
     return(ProjectId.CreateFromSerialized(id, debugName));
 }