public override bool Execute() { // Log inputs var log = new MSBuildLogger(Log); log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'"); log.LogDebug($"(in) TargetFrameworks '{TargetFrameworks}'"); log.LogDebug($"(in) ProjectReferences '{string.Join(";", ProjectReferences.Select(p => p.ItemSpec))}'"); log.LogDebug($"(in) ParentProjectPath '{ParentProjectPath}'"); var entries = new List <ITaskItem>(); // Filter obvious duplicates without considering OS case sensitivity. // This will be filtered further when creating the spec. var seen = new HashSet <string>(StringComparer.Ordinal); var parentDirectory = Path.GetDirectoryName(ParentProjectPath); foreach (var project in ProjectReferences) { var refOutput = BuildTasksUtility.GetPropertyIfExists(project, "ReferenceOutputAssembly"); // Match the same behavior as NuGet.targets // ReferenceOutputAssembly == '' OR ReferenceOutputAssembly == 'true' if (string.IsNullOrEmpty(refOutput) || Boolean.TrueString.Equals(refOutput, StringComparison.OrdinalIgnoreCase)) { // Get the absolute path var referencePath = Path.GetFullPath(Path.Combine(parentDirectory, project.ItemSpec)); if (!seen.Add(referencePath)) { // Skip already processed projects continue; } var properties = new Dictionary <string, string>(); properties.Add("ProjectUniqueName", ProjectUniqueName); properties.Add("Type", "ProjectReference"); properties.Add("ProjectPath", referencePath); properties.Add("ProjectReferenceUniqueName", referencePath); if (!string.IsNullOrEmpty(TargetFrameworks)) { properties.Add("TargetFrameworks", TargetFrameworks); } BuildTasksUtility.CopyPropertyIfExists(project, properties, "IncludeAssets"); BuildTasksUtility.CopyPropertyIfExists(project, properties, "ExcludeAssets"); BuildTasksUtility.CopyPropertyIfExists(project, properties, "PrivateAssets"); entries.Add(new TaskItem(Guid.NewGuid().ToString(), properties)); } } RestoreGraphItems = entries.ToArray(); return(true); }
public override bool Execute() { var projectrefs = ProjectReferences?.Select(p => Path.GetDirectoryName(p.GetMetadata("MSBuildSourceProjectFile"))).ToList() ?? new List <string>(); var baseDir = Path.GetDirectoryName(BasePath); var srv = FabricSerializers.ServiceManifestFromFile(Path.Combine(baseDir, "PackageRoot", "ServiceManifest.xml")); var ver = srv.SetGitVersion(UpdateBaseVersion ? BaseVersion : srv.Version, baseDir, TargetDir, CheckIndividualPackages, projectrefs, MaxHashLength, SkipHash); File.WriteAllText(Path.Combine(baseDir, "pkg", Configuration, "Version.txt"), ver.version + " " + ver.date.Ticks); File.WriteAllText(Path.Combine(baseDir, "pkg", Configuration, "Diff.txt"), ver.diff); FabricSerializers.SaveServiceManifest(Path.Combine(baseDir, "pkg", Configuration, "ServiceManifest.xml"), srv); return(true); }
public CompilerResults Compile() { var csc = new CSharpCodeProvider( new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }); var referencedAssemblies = AssemblyReferences .Union(ProjectReferences.Select(p => p.Compile().PathToAssembly)) .ToArray(); var parameters = new CompilerParameters( referencedAssemblies); return(csc.CompileAssemblyFromSource( parameters, MockSourceFiles.Select(x => x.RenderFile()).ToArray())); }
public EmitResult CompileAssembly(string assemblyName, IEnumerable <string> csFiles, Stream stream, Stream streamForPdb) { var syntaxTrees = new List <SyntaxTree>(); foreach (var csFile in csFiles) { var source = File.ReadAllText(csFile); var syntaxTree = SyntaxFactory.ParseSyntaxTree(source, ParseOptions, csFile, System.Text.Encoding.UTF8); syntaxTrees.Add(syntaxTree); } var references = ProjectReferences.Select(referencePath => MetadataReference.CreateFromFile(referencePath)); var compilationOptions = new CSharpCompilationOptions(OutputKind) .WithOverflowChecks(true) .WithOptimizationLevel(OptimizationLevel) .WithUsings(Namespaces); var compilation = CSharpCompilation.Create(assemblyName, syntaxTrees, references, compilationOptions); return(compilation.Emit(stream, streamForPdb)); }
public override bool Execute() { try { var buildSnapshot = new BuildSnapshot(ProjectReferences.Select(projectReference => projectReference.GetMetadata("FullPath")).ToList(), FilesToCompile); buildSnapshot.ProjectConfigProperties[DictionaryTags.EnableUnitTesting] = false; buildSnapshot.ProjectConfigProperties[DictionaryTags.TreatWarningsAsErrors] = false; buildSnapshot.ProjectConfigProperties[DictionaryTags.WarningLevel] = WarningLevel; return(Compile(buildSnapshot)); } catch (Exception exception) { if (exception.IsFatal()) { throw; } Log.LogErrorFromException(exception, true, true, null); return(false); } }
public override bool Execute() { // Log inputs var log = new MSBuildLogger(Log); log.LogDebug($"(in) ProjectReferences '{string.Join(";", ProjectReferences.Select(p => p.ItemSpec))}'"); log.LogDebug($"(in) SolutionFilePath '{SolutionFilePath}'"); var entries = new List <ITaskItem>(); var parentDirectory = Path.GetDirectoryName(SolutionFilePath); foreach (var project in ProjectReferences) { if (string.IsNullOrEmpty(project.ItemSpec)) { continue; } var projectPath = Path.GetFullPath(Path.Combine(parentDirectory, project.ItemSpec)); // Check for the metaproj extension, this is auto generated by solutions instead of // the actual project path when build order is set. For the purpose of restore // the order is not important so we remove the extension to get the real project path. if (projectPath.EndsWith(MetaProjExtension, StringComparison.OrdinalIgnoreCase)) { // Remove .metaproj from the path. projectPath = projectPath.Substring(0, projectPath.Length - MetaProjExtension.Length); } // Clone items using the modified path var newEntry = new TaskItem(projectPath, project.CloneCustomMetadata()); entries.Add(newEntry); } OutputProjectReferences = entries.ToArray(); return(true); }
public string RenderFile() { return(string.Format( @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""12.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration> <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform> <ProjectGuid>{0}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>{1}</RootNamespace> <AssemblyName>{1}</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <DesignTimeBuild>true</DesignTimeBuild> </PropertyGroup> <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ""> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ""> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup> <StartupObject /> </PropertyGroup> <ItemGroup> {2} <Reference Include=""System"" /> </ItemGroup> <ItemGroup> {3} </ItemGroup> <ItemGroup> {4} </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name=""BeforeBuild""> </Target> <Target Name=""AfterBuild""> </Target> --> </Project>", Guid, Title, //AssemblyReferences string.Join( Environment.NewLine, AssemblyReferences.Select( r => string.Format( @"<Reference Include=""{0}""> <HintPath>{1}</HintPath> </Reference>", Path.GetFileNameWithoutExtension(r), r) )), //Files string.Join( Environment.NewLine, MockSourceFiles.Select( f => string.Format( @"<Compile Include=""{0}"" />", f.FileName) )), //ProjectReferences string.Join( Environment.NewLine, ProjectReferences.Select( p => string.Format( @"<ProjectReference Include=""{0}""> <Project>{1}</Project> <Name>{2}</Name> </ProjectReference>", p.FileName, p.Guid, Path.GetFileNameWithoutExtension(p.FileName.FullPath)) )))); }
private async Task <ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken)) { // Here, we use the _documentStates and _additionalDocumentStates and visit them in order; we ensure that those are // sorted by ID so we have a consistent sort. var documentChecksumsTasks = _documentStates.Select(pair => pair.Value.GetChecksumAsync(cancellationToken)); var additionalDocumentChecksumTasks = _additionalDocumentStates.Select(pair => pair.Value.GetChecksumAsync(cancellationToken)); var serializer = _solutionServices.Workspace.Services.GetService <ISerializerService>(); var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken); // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed. var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null; var parseOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(ParseOptions, _ => serializer.CreateChecksum(ParseOptions, cancellationToken)) : Checksum.Null; var projectReferenceChecksums = ChecksumCache.GetOrCreate <ProjectReferenceChecksumCollection>(ProjectReferences, _ => new ProjectReferenceChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var metadataReferenceChecksums = ChecksumCache.GetOrCreate <MetadataReferenceChecksumCollection>(MetadataReferences, _ => new MetadataReferenceChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var analyzerReferenceChecksums = ChecksumCache.GetOrCreate <AnalyzerReferenceChecksumCollection>(AnalyzerReferences, _ => new AnalyzerReferenceChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false); var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false); return(new ProjectStateChecksums( infoChecksum, compilationOptionsChecksum, parseOptionsChecksum, new DocumentChecksumCollection(documentChecksums), projectReferenceChecksums, metadataReferenceChecksums, analyzerReferenceChecksums, new TextDocumentChecksumCollection(additionalChecksums))); } }
private async Task <ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken)) { // get states by id order to have deterministic checksum var documentChecksumsTasks = DocumentIds.Select(id => DocumentStates[id].GetChecksumAsync(cancellationToken)); var additionalDocumentChecksumTasks = AdditionalDocumentIds.Select(id => AdditionalDocumentStates[id].GetChecksumAsync(cancellationToken)); var serializer = new Serializer(_solutionServices.Workspace); var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken); // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed. var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null; var parseOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(ParseOptions, _ => serializer.CreateChecksum(ParseOptions, cancellationToken)) : Checksum.Null; var projectReferenceChecksums = ChecksumCache.GetOrCreate <ProjectReferenceChecksumCollection>(ProjectReferences, _ => new ProjectReferenceChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var metadataReferenceChecksums = ChecksumCache.GetOrCreate <MetadataReferenceChecksumCollection>(MetadataReferences, _ => new MetadataReferenceChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var analyzerReferenceChecksums = ChecksumCache.GetOrCreate <AnalyzerReferenceChecksumCollection>(AnalyzerReferences, _ => new AnalyzerReferenceChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false); var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false); return(new ProjectStateChecksums( infoChecksum, compilationOptionsChecksum, parseOptionsChecksum, new DocumentChecksumCollection(documentChecksums), projectReferenceChecksums, metadataReferenceChecksums, analyzerReferenceChecksums, new TextDocumentChecksumCollection(additionalChecksums))); } }
private ProjectCollection LoadProjectsAndReferences(IDictionary <string, string> globalProperties) { // Create an MSBuildProject loader with the same global properties of the project that requested a solution file MSBuildProjectLoader projectLoader = new MSBuildProjectLoader(globalProperties, ToolsVersion, BuildEngine, ProjectLoadSettings.IgnoreMissingImports) { CollectStats = CollectStats }; LogMessageHigh("Loading project references..."); ProjectCollection projectCollection = projectLoader.LoadProjectsAndReferences(ProjectReferences.Select(i => i.GetMetadata("FullPath")).Concat(new[] { ProjectFullPath })); LogMessageNormal($"Loaded {projectCollection.LoadedProjects.Count} project(s)"); if (CollectStats) { LogStatistics(projectLoader); } return(projectCollection); }
public IEnumerable <IProject> GetProjectReferences(Func <ProjectReferenceContext, IProject> projectLookupFunc) => ProjectReferences.Select(projectLookupFunc);
private async Task <ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken)) { // get states by id order to have deterministic checksum var documentChecksumsTasks = DocumentIds.Select(id => DocumentStates[id].GetChecksumAsync(cancellationToken)); var additionalDocumentChecksumTasks = AdditionalDocumentIds.Select(id => AdditionalDocumentStates[id].GetChecksumAsync(cancellationToken)); var serializer = new Serializer(_solutionServices.Workspace.Services); var infoChecksum = serializer.CreateChecksum(new SerializedProjectInfo(Id, Version, Name, AssemblyName, Language, FilePath, OutputFilePath, IsSubmission), cancellationToken); var compilationOptionsChecksum = SupportsCompilation ? serializer.CreateChecksum(CompilationOptions, cancellationToken) : Checksum.Null; var parseOptionsChecksum = SupportsCompilation ? serializer.CreateChecksum(ParseOptions, cancellationToken) : Checksum.Null; var projectReferenceChecksums = new ProjectReferenceChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()); var metadataReferenceChecksums = new MetadataReferenceChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()); var analyzerReferenceChecksums = new AnalyzerReferenceChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray()); var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false); var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false); return(new ProjectStateChecksums( infoChecksum, compilationOptionsChecksum, parseOptionsChecksum, new DocumentChecksumCollection(documentChecksums), projectReferenceChecksums, metadataReferenceChecksums, analyzerReferenceChecksums, new TextDocumentChecksumCollection(additionalChecksums))); } }