Exemple #1
0
        public PreprocessResult PreprocessRazorTemplate(string content, string className, string classNamespace)
        {
            var language  = new CSharpRazorCodeLanguage();
            var razorHost = new RazorEngineHost(language)
            {
                DefaultBaseClass      = typeof(TemplateBase).FullName,
                DefaultNamespace      = classNamespace,
                DefaultClassName      = className,
                GeneratedClassContext = new GeneratedClassContext(
                    nameof(TemplateBase.ExecuteAsync),
                    nameof(TemplateBase.Write),
                    nameof(TemplateBase.WriteLiteral),
                    new GeneratedTagHelperContext())
            };

            razorHost.NamespaceImports.Add(classNamespace);

            var razorEngine      = new RazorTemplateEngine(razorHost);
            var generatorResults = razorEngine.GenerateCode(new StringReader(content));

            if (!generatorResults.Success)
            {
                throw new Exception(string.Join(Environment.NewLine, generatorResults.ParserErrors.Select(x => x.Message)));
            }

            var preprocessResult = new PreprocessResult()
            {
                PreprocessedContent = generatorResults.GeneratedCode,
                References          = _host.StandardImports.ToList(),
            };

            return(preprocessResult);
        }
        public Assembly Compile(string assemblyName, PreprocessResult preprocessResult)
        {
            var references = new List <MetadataReference>();

            // project references
            references.AddRange(_resolver.ResolveMetadataReference());
            // assembly instruction
            references.AddRange(preprocessResult.References.Select(ResolveAssemblyReference)
                                .Where(metadata => metadata != null));

            var compilation = CSharpCompilation.Create(
                assemblyName,
                new[] { SyntaxFactory.ParseSyntaxTree(preprocessResult.PreprocessedContent) },
                references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var stream = new MemoryStream())
            {
                var result = compilation.Emit(stream);
                _host.LogErrors(result);

                var transformationAssembly = Assembly.Load(stream.ToArray());

                //var transformationAssembly = (Assembly)typeof(Assembly).GetTypeInfo().GetDeclaredMethods("Load").First(m =>
                //{
                //    var parameters = m.GetParameters();
                //    return parameters.Length == 1 && parameters[0].ParameterType == typeof(byte[]);
                //}).Invoke(null, new[] { stream.ToArray() });

                return(transformationAssembly);
            }
        }
        // todo add to cli tool
        /// <summary>
        /// 将 T4 模板转换成 cs 代码
        /// </summary>
        /// <param name="content">模板内容</param>
        /// <param name="className">生成的 cs 代码类名</param>
        /// <param name="classNamespace">生成的 cs 代码名称空间名</param>
        /// <returns>cs 代码内容及其引用的 Reference</returns>
        public PreprocessResult PreprocessT4Template(string content, string className, string classNamespace)
        {
            var result              = new Parser(_host).Parse(content);
            var transformation      = new PreprocessTextTransformation(className, classNamespace, result, _host);
            var preprocessedContent = transformation.TransformText();

            var preprocessed = new PreprocessResult
            {
                References          = result.References.Distinct().ToArray(),
                PreprocessedContent = preprocessedContent
            };

            return(preprocessed);
        }
Exemple #4
0
        public Assembly Compile(string assemblyName, PreprocessResult preprocessResult)
        {
            var compilation = CSharpCompilation.Create(
                assemblyName,
                new[] { SyntaxFactory.ParseSyntaxTree(preprocessResult.PreprocessedContent) },
                preprocessResult.References.SelectMany(ResolveAssemblyReference),
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var stream = new MemoryStream())
            {
                var result = compilation.Emit(stream);
                _host.LogErrors(result);

                var transformationAssembly = (Assembly)typeof(Assembly).GetTypeInfo().GetDeclaredMethods("Load").First(m =>
                {
                    var parameters = m.GetParameters();
                    return(parameters.Length == 1 && parameters[0].ParameterType == typeof(byte[]));
                }).Invoke(null, new[] { stream.ToArray() });

                return(transformationAssembly);
            }
        }