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);
     }
 }
Example #2
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());
        }
Example #3
0
        protected override Task ProcessAsync()
        {
            if (xlsx)
            {
                LibraryExporter.ToXlsx(FilePath);
            }
            if (csv)
            {
                LibraryExporter.ToCsv(FilePath);
            }
            if (json)
            {
                LibraryExporter.ToJson(FilePath);
            }

            Console.WriteLine($"Library exported to: {FilePath}");

            return(Task.CompletedTask);
        }
Example #4
0
        private void exportLibraryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Title  = "Where to export Library",
                    Filter = "Excel Workbook (*.xlsx)|*.xlsx|CSV files (*.csv)|*.csv|JSON files (*.json)|*.json"                     // + "|All files (*.*)|*.*"
                };

                if (saveFileDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                // FilterIndex is 1-based, NOT 0-based
                switch (saveFileDialog.FilterIndex)
                {
                case 1:                         // xlsx
                default:
                    LibraryExporter.ToXlsx(saveFileDialog.FileName);
                    break;

                case 2:                         // csv
                    LibraryExporter.ToCsv(saveFileDialog.FileName);
                    break;

                case 3:                         // json
                    LibraryExporter.ToJson(saveFileDialog.FileName);
                    break;
                }

                MessageBox.Show("Library exported to:\r\n" + saveFileDialog.FileName);
            }
            catch (Exception ex)
            {
                MessageBoxAlertAdmin.Show("Error attempting to export your library.", "Error exporting", ex);
            }
        }
Example #5
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);
            }
        }
Example #6
0
        private void WriteDevRuntimeConfig(LibraryExporter exporter)
        {
            if (_context.TargetFramework.IsDesktop())
            {
                return;
            }

            var json           = new JObject();
            var runtimeOptions = new JObject();

            json.Add("runtimeOptions", runtimeOptions);

            AddAdditionalProbingPaths(runtimeOptions);

            var runtimeConfigDevJsonFile =
                Path.Combine(_runtimeOutputPath, _compilerOptions.OutputName + FileNameSuffixes.RuntimeConfigDevJson);

            using (var writer = new JsonTextWriter(new StreamWriter(File.Create(runtimeConfigDevJsonFile))))
            {
                writer.Formatting = Formatting.Indented;
                json.WriteTo(writer);
            }
        }
Example #7
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);
        }
Example #8
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));
        }
Example #9
0
        private static void MakeRunnable(ProjectContext runtimeContext, string outputPath, LibraryExporter exporter)
        {
            CopyContents(runtimeContext, outputPath);

            if (runtimeContext.TargetFramework.IsDesktop())
            {
                // On desktop we need to copy dependencies since we don't own the host
                foreach (var export in exporter.GetDependencies())
                {
                    CopyExport(outputPath, export);
                }
            }
            else
            {
                EmitHost(runtimeContext, outputPath, exporter);
            }
        }
Example #10
0
 private void ButtonExportLibrary_Click(object sender, RoutedEventArgs e)
 {
     LibraryExporter.Export(web_library_detail, ObjLibraryCatalogControl.SelectedPDFDocumentsElseEverything);
 }
Example #11
0
 public Executable(ProjectContext context, OutputPaths outputPaths, string runtimeOutputPath, string intermediateOutputDirectoryPath, LibraryExporter exporter, string configuration)
 {
     _context                = context;
     _outputPaths            = outputPaths;
     _runtimeOutputPath      = runtimeOutputPath;
     _intermediateOutputPath = intermediateOutputDirectoryPath;
     _exporter               = exporter;
     _configuration          = configuration;
     _compilerOptions        = _context.ProjectFile.GetCompilerOptions(_context.TargetFramework, configuration);
 }
Example #12
0
 public Executable(ProjectContext context, OutputPaths outputPaths, LibraryExporter exporter, string configuration)
     : this(context, outputPaths, outputPaths.RuntimeOutputPath, outputPaths.IntermediateOutputDirectoryPath, exporter, configuration)
 {
 }
Example #13
0
 public static IEnumerable <LibraryExport> GetAllProjectTypeDependencies(this LibraryExporter exporter)
 {
     return
         (exporter.GetDependencies(LibraryType.Project)
          .Concat(exporter.GetDependencies(LibraryType.MSBuildProject)));
 }
Example #14
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);
                }
            }
        }
Example #15
0
 public Executable(ProjectContext context, OutputPaths outputPaths, LibraryExporter exporter)
 {
     _context     = context;
     _outputPaths = outputPaths;
     _exporter    = exporter;
 }
Example #16
0
 public LibraryExporterTests()
     : base(testAppPath)
 {
     _libraryExporter = new LibraryExporter(_projectContext, _applicationInfo);
 }
Example #17
0
        private static DependencyInformation ResolveDependencyInfo(DnxProject project, FrameworkName frameworkName)
        {
            var cacheKey = Tuple.Create("DependencyInformation", project.Name, "Debug", frameworkName);

            return(cache.Get <DependencyInformation>(cacheKey, ctx =>
            {
                var applicationHostContext = GetApplicationHostContext(project, "Debug", frameworkName);

                var info = new DependencyInformation
                {
                    HostContext = applicationHostContext,
                    ProjectReferences = new List <ProjectReference>(),
                    References = new List <string>(),
                    ExportedSourcesFiles = new List <string>()
                };

                foreach (var library in applicationHostContext.LibraryManager.GetLibraryDescriptions())
                {
                    // Skip unresolved libraries
                    if (!library.Resolved)
                    {
                        continue;
                    }

                    if (string.Equals(library.Type, "Project") &&
                        !string.Equals(library.Identity.Name, project.Name))
                    {
                        DnxProject referencedProject = GetProject(library.Path);

                        if (referencedProject == null)
                        {
                            // Should never happen
                            continue;
                        }

                        var targetFrameworkInformation = referencedProject.GetTargetFramework(library.Framework);

                        // If this is an assembly reference then treat it like a file reference
                        if (!string.IsNullOrEmpty(targetFrameworkInformation.AssemblyPath) &&
                            string.IsNullOrEmpty(targetFrameworkInformation.WrappedProject))
                        {
                            string assemblyPath = GetProjectRelativeFullPath(referencedProject, targetFrameworkInformation.AssemblyPath);
                            info.References.Add(assemblyPath);
                        }
                        else
                        {
                            string wrappedProjectPath = null;

                            if (!string.IsNullOrEmpty(targetFrameworkInformation.WrappedProject))
                            {
                                wrappedProjectPath = GetProjectRelativeFullPath(referencedProject, targetFrameworkInformation.WrappedProject);
                            }

                            info.ProjectReferences.Add(new ProjectReference
                            {
                                Name = referencedProject.Name,
                                Framework = library.Framework,
                                Path = library.Path,
                                WrappedProjectPath = wrappedProjectPath,
                                Project = referencedProject
                            });
                        }
                    }
                }

                var libraryExporter = new LibraryExporter(
                    applicationHostContext.LibraryManager,
                    null,
                    "Debug");

                var exportWithoutProjects = libraryExporter.GetNonProjectExports(project.Name);

                foreach (var reference in exportWithoutProjects.MetadataReferences)
                {
                    var fileReference = reference as IMetadataFileReference;
                    if (fileReference != null)
                    {
                        info.References.Add(fileReference.Path);
                    }
                }

                foreach (var sourceFileReference in exportWithoutProjects.SourceReferences.OfType <ISourceFileReference>())
                {
                    info.ExportedSourcesFiles.Add(sourceFileReference.Path);
                }

                return info;
            }));
        }