Ejemplo n.º 1
0
        private static void GenerateBindingRedirects(ProjectContext runtimeContext, string outputPath, LibraryExporter exporter)
        {
            var       appConfigNames = new[] { "app.config", "App.config" };
            XDocument baseAppConfig  = null;

            foreach (var appConfigName in appConfigNames)
            {
                var baseAppConfigPath = Path.Combine(runtimeContext.ProjectDirectory, appConfigName);

                if (File.Exists(baseAppConfigPath))
                {
                    using (var fileStream = File.OpenRead(baseAppConfigPath))
                    {
                        baseAppConfig = XDocument.Load(fileStream);
                        break;
                    }
                }
            }

            var generator = new BindingRedirectGenerator();
            var appConfig = generator.Generate(exporter.GetAllExports(), baseAppConfig);

            if (appConfig != null)
            {
                var path = Path.Combine(outputPath, runtimeContext.ProjectFile.Name + ".exe.config");
                using (var stream = File.Create(path))
                {
                    appConfig.Save(stream);
                }
            }
        }
Ejemplo n.º 2
0
        private static void GenerateBindingRedirects(this ProjectContext context, LibraryExporter exporter, string outputPath)
        {
            var existingConfig = new DirectoryInfo(context.ProjectDirectory)
                                 .EnumerateFiles()
                                 .FirstOrDefault(f => f.Name.Equals("app.config", StringComparison.OrdinalIgnoreCase));

            XDocument baseAppConfig = null;

            if (existingConfig != null)
            {
                using (var fileStream = File.OpenRead(existingConfig.FullName))
                {
                    baseAppConfig = XDocument.Load(fileStream);
                }
            }

            var appConfig = exporter.GetAllExports().GenerateBindingRedirects(baseAppConfig);

            if (appConfig == null)
            {
                return;
            }

            var path = Path.Combine(outputPath, context.ProjectFile.Name + ".exe.config");

            using (var stream = File.Create(path))
            {
                appConfig.Save(stream);
            }
        }
Ejemplo n.º 3
0
        public void WriteDeps(LibraryExporter exporter)
        {
            var path = Path.Combine(_runtimeOutputPath, _context.ProjectFile.Name + FileNameSuffixes.Deps);

            CreateDirectoryIfNotExists(path);
            File.WriteAllLines(path, exporter
                               .GetDependencies(LibraryType.Package)
                               .SelectMany(GenerateLines));

            var compilerOptions = _context.ResolveCompilationOptions(_configuration);
            var includeCompile  = compilerOptions.PreserveCompilationContext == true;

            var exports           = exporter.GetAllExports().ToArray();
            var dependencyContext = new DependencyContextBuilder().Build(
                compilerOptions: includeCompile? compilerOptions: null,
                compilationExports: includeCompile ? exports : null,
                runtimeExports: exports,
                portable: string.IsNullOrEmpty(_context.RuntimeIdentifier),
                target: _context.TargetFramework,
                runtime: _context.RuntimeIdentifier ?? string.Empty);

            var writer       = new DependencyContextWriter();
            var depsJsonFile = Path.Combine(_runtimeOutputPath, _context.ProjectFile.Name + FileNameSuffixes.DepsJson);

            using (var fileStream = File.Create(depsJsonFile))
            {
                writer.Write(dependencyContext, fileStream);
            }
        }
Ejemplo n.º 4
0
        private static void EmitHost(ProjectContext runtimeContext, string outputPath, LibraryExporter exporter)
        {
            // Write the Host information file (basically a simplified form of the lock file)
            var lines = new List <string>();

            foreach (var export in exporter.GetAllExports())
            {
                if (export.Library == runtimeContext.RootProject)
                {
                    continue;
                }

                if (export.Library is ProjectDescription)
                {
                    // Copy project dependencies to the output folder
                    CopyFiles(export.RuntimeAssemblies, outputPath);
                    CopyFiles(export.NativeLibraries, outputPath);
                }
                else
                {
                    lines.AddRange(GenerateLines(export, export.RuntimeAssemblies, "runtime"));
                    lines.AddRange(GenerateLines(export, export.NativeLibraries, "native"));
                }
            }

            File.WriteAllLines(Path.Combine(outputPath, runtimeContext.ProjectFile.Name + ".deps"), lines);

            // Copy the host in
            CopyHost(Path.Combine(outputPath, runtimeContext.ProjectFile.Name + Constants.ExeSuffix));
        }
Ejemplo n.º 5
0
        private void GenerateBindingRedirects(LibraryExporter exporter)
        {
            var outputName = _outputPaths.RuntimeFiles.Assembly;
            var configFile = outputName + Constants.ConfigSuffix;

            var existingConfig = new DirectoryInfo(_context.ProjectDirectory)
                                 .EnumerateFiles()
                                 .FirstOrDefault(f => f.Name.Equals("app.config", StringComparison.OrdinalIgnoreCase));

            if (existingConfig != null)
            {
                File.Copy(existingConfig.FullName, configFile, true);
            }

            List <string> configFiles = new List <string>();

            configFiles.Add(configFile);

            foreach (var export in exporter.GetDependencies())
            {
                var dependencyExecutables = export.RuntimeAssemblyGroups.GetDefaultAssets()
                                            .Where(asset => asset.FileName.ToLower().EndsWith(FileNameSuffixes.DotNet.Exe))
                                            .Select(asset => Path.Combine(_runtimeOutputPath, asset.FileName));

                foreach (var executable in dependencyExecutables)
                {
                    configFile = executable + Constants.ConfigSuffix;
                    configFiles.Add(configFile);
                }
            }

            exporter.GetAllExports().GenerateBindingRedirects(configFiles);
        }
Ejemplo n.º 6
0
        public void GenerateBindingRedirects(LibraryExporter exporter, string configuration)
        {
            var outputName = _calculator.GetAssemblyPath(configuration);

            var existingConfig = new DirectoryInfo(_context.ProjectDirectory)
                                 .EnumerateFiles()
                                 .FirstOrDefault(f => f.Name.Equals("app.config", StringComparison.OrdinalIgnoreCase));

            XDocument baseAppConfig = null;

            if (existingConfig != null)
            {
                using (var fileStream = File.OpenRead(existingConfig.FullName))
                {
                    baseAppConfig = XDocument.Load(fileStream);
                }
            }

            var appConfig = exporter.GetAllExports().GenerateBindingRedirects(baseAppConfig);

            if (appConfig == null)
            {
                return;
            }

            var path = outputName + ".config";

            using (var stream = File.Create(path))
            {
                appConfig.Save(stream);
            }
        }
Ejemplo n.º 7
0
        public static DependencyContext FromLibraryExporter(LibraryExporter libraryExporter, string target, string runtime)
        {
            var dependencies = libraryExporter.GetAllExports();

            return(new DependencyContext(target, runtime,
                                         GetLibraries(dependencies, export => export.CompilationAssemblies),
                                         GetLibraries(dependencies, export => export.RuntimeAssemblies)));
        }
Ejemplo n.º 8
0
 internal static void CopyProjectDependenciesTo(this LibraryExporter exporter, string path, params ProjectDescription[] except)
 {
     exporter.GetAllExports()
     .Where(e => !except.Contains(e.Library))
     .Where(e => e.Library is ProjectDescription)
     .SelectMany(e => e.NativeLibraries.Union(e.RuntimeAssemblies))
     .CopyTo(path);
 }
Ejemplo n.º 9
0
        public void LibraryExporter_TestGetAllExports()
        {
            _libraryExporter = new LibraryExporter(_projectContext, _applicationInfo);

            var exports = _libraryExporter.GetAllExports();

            Assert.True(exports.Any(), "No exports found");
            Assert.True(exports.First().Library.Identity.Type.Value == "Project");
            Assert.True(exports.First().Library.Identity.Name == "ModelTypesLocatorTestClassLibrary");
            Assert.True(exports.Where(_ => _.Library.Identity.Name == "Microsoft.Extensions.CodeGenerators.Mvc").Any());
        }
Ejemplo n.º 10
0
 static GenFuTagHelper()
 {
     //TODO: Review with James. This stuff used to be wired up via DI but is not anymore.
     //      It was also very slow so I had to put it in a static constructor. Doing this for every tag helper instance was too slow.
     var projectContext = ProjectContext.CreateContextForEachFramework(Directory.GetCurrentDirectory(), null, new[] { PlatformServices.Default.Application.RuntimeFramework.FullName }).First();
     ApplicationInfo appInfo = new ApplicationInfo("TagHelperSamples.GenFu", PlatformServices.Default.Application.ApplicationBasePath);
     ILibraryExporter exporter = new LibraryExporter(projectContext, appInfo);
     _references = new List<MetadataReference>();
     var exports = exporter.GetAllExports();
     var metaDataRefs = exports.SelectMany(x => x.GetMetadataReferences()).ToList();
     foreach (var reference in metaDataRefs)
     {
         _references.Add(reference);
     }
 }
Ejemplo n.º 11
0
        private void VerifyCoreClrPresenceInPackageGraph()
        {
            var isCoreClrPresent = _exporter
                                   .GetAllExports()
                                   .SelectMany(e => e.NativeLibraryGroups)
                                   .SelectMany(g => g.Assets)
                                   .Select(a => a.FileName)
                                   .Where(f => Constants.LibCoreClrBinaryNames.Contains(f))
                                   .Any();

            // coreclr should be present for standalone apps
            if (!isCoreClrPresent)
            {
                throw new InvalidOperationException("Expected coreclr library not found in package graph. Please try running dotnet restore again.");
            }
        }
Ejemplo n.º 12
0
        private void WriteDepsFileAndCopyProjectDependencies(LibraryExporter exporter)
        {
            // When called this way we don't need to filter exports, so we pass the same list to both.
            var exports = exporter.GetAllExports().ToList();

            WriteConfigurationFiles(exports, exports, includeDevConfig: true);

            var projectExports = exporter.GetAllProjectTypeDependencies();

            CopyAssemblies(projectExports);
            CopyAssets(projectExports);

            var packageExports = exporter.GetDependencies(LibraryType.Package);

            CopyAssets(packageExports);
        }
Ejemplo n.º 13
0
        private void WriteRuntimeConfig(LibraryExporter exporter)
        {
            if (!_context.TargetFramework.IsDesktop())
            {
                // TODO: Suppress this file if there's nothing to write? RuntimeOutputFiles would have to be updated
                // in order to prevent breaking incremental compilation...

                var json           = new JObject();
                var runtimeOptions = new JObject();
                json.Add("runtimeOptions", runtimeOptions);

                var redistPackage = _context.RootProject.Dependencies
                                    .Where(r => r.Type.Equals(LibraryDependencyType.Platform))
                                    .ToList();
                if (redistPackage.Count > 0)
                {
                    if (redistPackage.Count > 1)
                    {
                        throw new InvalidOperationException("Multiple packages with type: \"platform\" were specified!");
                    }
                    var packageName = redistPackage.Single().Name;

                    var redistExport = exporter.GetAllExports()
                                       .FirstOrDefault(e => e.Library.Identity.Name.Equals(packageName));
                    if (redistExport == null)
                    {
                        throw new InvalidOperationException($"Platform package '{packageName}' was not present in the graph.");
                    }
                    else
                    {
                        var framework = new JObject(
                            new JProperty("name", redistExport.Library.Identity.Name),
                            new JProperty("version", redistExport.Library.Identity.Version.ToNormalizedString()));
                        runtimeOptions.Add("framework", framework);
                    }
                }

                var runtimeConfigJsonFile =
                    Path.Combine(_runtimeOutputPath, _compilerOptions.OutputName + FileNameSuffixes.RuntimeConfigJson);

                using (var writer = new JsonTextWriter(new StreamWriter(File.Create(runtimeConfigJsonFile))))
                {
                    writer.Formatting = Formatting.Indented;
                    json.WriteTo(writer);
                }
            }
        }
        static GenFuTagHelper()
        {
            //TODO: Review with James. This stuff used to be wired up via DI but is not anymore.
            //      It was also very slow so I had to put it in a static constructor. Doing this for every tag helper instance was too slow.
            var              projectContext = ProjectContext.CreateContextForEachFramework(Directory.GetCurrentDirectory(), null, new[] { PlatformServices.Default.Application.RuntimeFramework.FullName }).First();
            ApplicationInfo  appInfo        = new ApplicationInfo("TagHelperSamples.GenFu", PlatformServices.Default.Application.ApplicationBasePath);
            ILibraryExporter exporter       = new LibraryExporter(projectContext, appInfo);

            _references = new List <MetadataReference>();
            var exports      = exporter.GetAllExports();
            var metaDataRefs = exports.SelectMany(x => x.GetMetadataReferences()).ToList();

            foreach (var reference in metaDataRefs)
            {
                _references.Add(reference);
            }
        }
Ejemplo n.º 15
0
        public static DependencyContext Build(CommonCompilerOptions compilerOptions, LibraryExporter libraryExporter, string configuration, NuGetFramework target, string runtime)
        {
            var dependencies = libraryExporter.GetAllExports().Where(export => export.Library.Framework.Equals(target)).ToList();

            // Sometimes we have package and reference assembly with the same name (System.Runtime for example) thats why we
            // deduplicating them prefering reference assembly
            var dependencyLookup = dependencies
                                   .OrderBy(export => export.Library.Identity.Type == LibraryType.ReferenceAssembly)
                                   .GroupBy(export => export.Library.Identity.Name)
                                   .Select(exports => exports.First())
                                   .Select(export => new Dependency(export.Library.Identity.Name, export.Library.Identity.Version.ToString()))
                                   .ToDictionary(dependency => dependency.Name);

            return(new DependencyContext(target.DotNetFrameworkName, runtime,
                                         GetCompilationOptions(compilerOptions),
                                         GetLibraries(dependencies, dependencyLookup, target, configuration, export => export.CompilationAssemblies),
                                         GetLibraries(dependencies, dependencyLookup, target, configuration, export => export.RuntimeAssemblies)));
        }
Ejemplo n.º 16
0
        private void WriteDepsFileAndCopyProjectDependencies(LibraryExporter exporter)
        {
            var exports               = exporter.GetAllExports().ToList();
            var exportsLookup         = exports.ToDictionary(e => e.Library.Identity.Name, StringComparer.OrdinalIgnoreCase);
            var platformExclusionList = _context.GetPlatformExclusionList(exportsLookup);
            var filteredExports       = exports.FilterExports(platformExclusionList);

            WriteConfigurationFiles(exports, filteredExports, exports, includeDevConfig: true);

            var projectExports = exporter.GetAllProjectTypeDependencies();

            CopyAssemblies(projectExports);
            CopyAssets(projectExports);

            var packageExports = exporter.GetDependencies(LibraryType.Package);

            CopyAssets(packageExports);
        }
Ejemplo n.º 17
0
        public void CommonUtilities_TestGetAssemblyFromCompilation()
        {
            LibraryExporter exporter = new LibraryExporter(_projectContext, _applicationInfo);

            LibraryManager manager = new LibraryManager(_projectContext);
            IEnumerable <MetadataReference> references = exporter.GetAllExports().SelectMany(export => export.GetMetadataReferences());
            string code = @"using System;
                            namespace Sample { 
                                public class SampleClass 
                                {
                                } 
                            }";

            Compilation       compilation = GetCompilation(code, Path.GetRandomFileName(), references);
            CompilationResult result      = CommonUtilities.GetAssemblyFromCompilation(loadContext, compilation);

            Assert.True(result.Success);
            Assert.True(result.Assembly.DefinedTypes.Where(_ => _.Name == "SampleClass").Any());
        }
Ejemplo n.º 18
0
        private void ShowDependencyInformation(IReport report)
        {
            // Make lookup for actual package dependency assemblies
            var projectExport = _libraryExporter.GetAllExports(_project.Name);

            if (projectExport == null)
            {
                return;
            }
            var metadataFileRefs = projectExport.MetadataReferences
                                   .OfType <IMetadataFileReference>();

            foreach (var library in _libraryManager.GetLibraryDescriptions())
            {
                if (!library.Resolved)
                {
                    if (library.Identity.Name != ImplicitRuntimePackageConstants.ImplicitRuntimePackageId)
                    {
                        report.WriteLine("  Unable to resolve dependency {0}", library.Identity.ToString().Red().Bold());
                        report.WriteLine();
                    }
                    continue;
                }
                report.WriteLine("  Using {0} dependency {1}", library.Type, library.Identity);
                report.WriteLine("    Source: {0}", HighlightFile(library.Path));

                if (library.Type == LibraryTypes.Package)
                {
                    // TODO: temporarily use prefix to tell whether an assembly belongs to a package
                    // Should expose LibraryName from IMetadataReference later for more efficient lookup
                    var libraryPath       = NormalizeDirectoryPath(library.Path);
                    var packageAssemblies = metadataFileRefs.Where(x => Path.GetFullPath(x.Path).StartsWith(libraryPath));
                    foreach (var assembly in packageAssemblies)
                    {
                        var relativeAssemblyPath = PathUtility.GetRelativePath(
                            libraryPath,
                            Path.GetFullPath(assembly.Path));
                        report.WriteLine("    File: {0}", relativeAssemblyPath.Bold());
                    }
                }
                report.WriteLine();
            }
        }
Ejemplo n.º 19
0
        public void WriteDeps(LibraryExporter exporter)
        {
            Directory.CreateDirectory(_runtimeOutputPath);

            var includeCompile = _compilerOptions.PreserveCompilationContext == true;

            var exports           = exporter.GetAllExports().ToArray();
            var dependencyContext = new DependencyContextBuilder().Build(
                compilerOptions: includeCompile ? _compilerOptions : null,
                compilationExports: includeCompile ? exports : null,
                runtimeExports: exports,
                portable: string.IsNullOrEmpty(_context.RuntimeIdentifier),
                target: _context.TargetFramework,
                runtime: _context.RuntimeIdentifier ?? string.Empty);

            var writer           = new DependencyContextWriter();
            var depsJsonFilePath = Path.Combine(_runtimeOutputPath, _compilerOptions.OutputName + FileNameSuffixes.DepsJson);

            using (var fileStream = File.Create(depsJsonFilePath))
            {
                writer.Write(dependencyContext, fileStream);
            }
        }
Ejemplo n.º 20
0
        public CompileResult Compile()
        {
            var result = new CompileResult();

            //var assemblyPath = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var assemblyName = Guid.NewGuid().ToString();

            this.Source = CleanSource(this.Source);

            var syntaxTrees = CSharpSyntaxTree.ParseText(this.Source);

            // build references up
            var references = new List <MetadataReference>();
            //typeof(object).GetTypeInfo().Assembly.GetName().Name
            var export = LibraryExporter.GetAllExports("GenFu.Web");

            foreach (var reference in export.MetadataReferences.Where(r => r.Name == "System.Runtime"))
            {
                references.Add(reference.ConvertMetadataReference(MetadataReferenceExtensions.CreateAssemblyMetadata));
            }
            // set up compilation
            var compilation = CSharpCompilation.Create(assemblyName)
                              .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                              .AddReferences(references)
                              .AddSyntaxTrees(syntaxTrees);

            // build the assembly
            Assembly assembly = null;

            using (var stream = new MemoryStream())
            {
                // this is broked...
                EmitResult compileResult = compilation.Emit(stream);
                // we get here, with diagnostic errors (check compileResult.Diagnostics)
                if (compileResult.Success)
                {
                    stream.Position = 0;
                    assembly        = Accessor.Default.LoadStream(stream, null);
                }
                else
                {
                    result.IsValid = false;
                    result.Errors  = compileResult.Diagnostics.Select(d => d.ToString());
                }
            }

            if (assembly != null)
            {
                // iterate over the types in the assembly
                var types = assembly.GetExportedTypes();
                if (types.Length == 1)
                {
                    _compiledType  = types[0];
                    result.IsValid = true;
                }
                if (types.Length > 1)
                {
                    result.IsValid = false;
                    result.Errors  = new[] { "We currently only support a single type through this website. Install GenFu in your own project to generate data for multiple types." };
                }
            }
            _isCompiled = result.IsValid;

            return(result);
        }