예제 #1
0
        public void CreateFromFile()
        {
            Assert.Throws <ArgumentNullException>(() => ModuleMetadata.CreateFromFile((string)null));
            Assert.Throws <ArgumentException>(() => ModuleMetadata.CreateFromFile(""));
            Assert.Throws <ArgumentException>(() => ModuleMetadata.CreateFromFile(@"c:\*"));

            char systemDrive = Environment.GetFolderPath(Environment.SpecialFolder.Windows)[0];

            Assert.Throws <IOException>(() => ModuleMetadata.CreateFromFile(@"http://goo.bar"));
            Assert.Throws <FileNotFoundException>(
                () =>
                ModuleMetadata.CreateFromFile(systemDrive + @":\file_that_does_not_exists.dll")
                );
            Assert.Throws <FileNotFoundException>(
                () =>
                ModuleMetadata.CreateFromFile(
                    systemDrive
                    + @":\directory_that_does_not_exists\file_that_does_not_exists.dll"
                    )
                );
            Assert.Throws <PathTooLongException>(
                () => ModuleMetadata.CreateFromFile(systemDrive + @":\" + new string('x', 1000))
                );
            Assert.Throws <IOException>(
                () =>
                ModuleMetadata.CreateFromFile(
                    Environment.GetFolderPath(Environment.SpecialFolder.Windows)
                    )
                );
        }
        /// <summary>
        /// Gets or creates metadata for specified file path.
        /// </summary>
        /// <param name="fullPath">Full path to an assembly manifest module file or a standalone module file.</param>
        /// <param name="kind">Metadata kind (assembly or module).</param>
        /// <returns>Metadata for the specified file.</returns>
        /// <exception cref="IOException">Error reading file <paramref name="fullPath"/>. See <see cref="Exception.InnerException"/> for details.</exception>
        public Metadata GetMetadata(string fullPath, MetadataImageKind kind)
        {
            if (NeedsShadowCopy(fullPath))
            {
                return(GetMetadataShadowCopyNoCheck(fullPath, kind).Metadata);
            }

            FileKey key = FileKey.Create(fullPath);

            lock (Guard)
            {
                CacheEntry <Metadata> existing;
                if (_noShadowCopyCache.TryGetValue(key, out existing))
                {
                    return(existing.Public);
                }
            }

            Metadata newMetadata;

            if (kind == MetadataImageKind.Assembly)
            {
                newMetadata = AssemblyMetadata.CreateFromFile(fullPath);
            }
            else
            {
                newMetadata = ModuleMetadata.CreateFromFile(fullPath);
            }

            // the files are locked (memory mapped) now
            key = FileKey.Create(fullPath);

            lock (Guard)
            {
                CacheEntry <Metadata> existing;
                if (_noShadowCopyCache.TryGetValue(key, out existing))
                {
                    newMetadata.Dispose();
                    return(existing.Public);
                }

                Metadata publicMetadata = newMetadata.Copy();
                _noShadowCopyCache.Add(key, new CacheEntry <Metadata>(publicMetadata, newMetadata));
                return(publicMetadata);
            }
        }
예제 #3
0
        public static RazorTemplatePage Compile(string content)
        {
            var engine   = Microsoft.AspNetCore.Razor.Language.RazorEngine.Create(builder => builder.Features.Add(new RazorLightTemplateDocumentClassifierPass()));
            var source   = Microsoft.AspNetCore.Razor.Language.RazorSourceDocument.Create(content, "input");
            var razorDoc = Microsoft.AspNetCore.Razor.Language.RazorCodeDocument.Create(source);

            engine.Process(razorDoc);

            var sourceCode = razorDoc.GetCSharpDocument().GeneratedCode;

            SourceText sourceText = SourceText.From(sourceCode, Encoding.UTF8);
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceText);

            // Force dynamic assembly to be linked in
            dynamic assemblyObj = typeof(RazorBuilder).Assembly;
            var     filePath    = assemblyObj.Location;
            var     references  = AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.IsDynamic && !string.IsNullOrWhiteSpace(x.Location)).Select(x => x.Location).ToList();

            var metadataReferences = new List <MetadataReference>();

            foreach (var reference in references)
            {
                try
                {
                    var moduleMetadata    = ModuleMetadata.CreateFromFile(reference);
                    var assemblyMetadata  = AssemblyMetadata.Create(moduleMetadata);
                    var metaDataReference = assemblyMetadata.GetReference(filePath: filePath);
                    metadataReferences.Add(metaDataReference);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException($"Expecting while loading metadata from assembly: {reference}", ex);
                }
            }

            var compilation = CSharpCompilation.Create("InMemory", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), references: metadataReferences).AddSyntaxTrees(syntaxTree);

            var assemblyStream = new MemoryStream();
            var result         = compilation.Emit(assemblyStream);

            if (!result.Success)
            {
                var errorsDiagnostics = result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error).ToList();

                var builder = new StringBuilder();

                foreach (Diagnostic diagnostic in errorsDiagnostics)
                {
                    FileLinePositionSpan lineSpan = diagnostic.Location.SourceTree.GetMappedLineSpan(diagnostic.Location.SourceSpan);
                    string errorMessage           = diagnostic.GetMessage();
                    string formattedMessage       = $"- ({lineSpan.StartLinePosition.Line}:{lineSpan.StartLinePosition.Character}) {errorMessage}";
                    builder.AppendLine(formattedMessage);
                }

                throw new InvalidOperationException(builder.ToString());
            }
            assemblyStream.Position = 0;
            var buffer       = assemblyStream.ToArray();
            var assembly     = Assembly.Load(buffer);
            var templateType = assembly.GetType("Scriban.Benchmarks.GeneratedTemplate");

            return((RazorTemplatePage)Activator.CreateInstance(templateType));
        }