public IEnumerable<CompilerReference> GetReferences(TypeContext context, IEnumerable<CompilerReference> includeAssemblies)
        {

            #region 加载依赖程序集  此处是加载所有程序集,效率需要改进

            return compilerReference;
            #endregion
        }
        /// <summary>
        /// Compiles the type defined in the specified type context.
        /// </summary>
        /// <param name="context">The type context which defines the type to compile.</param>
        /// <returns>The compiled type.</returns>
        public override Type CompileType(TypeContext context)
        {
            var results = Compile(context);

            if (results.Errors != null && results.Errors.Count > 0)
                throw new TemplateCompilationException(results.Errors);

            return results.CompiledAssembly.GetType("CompiledRazorTemplates.Dynamic." + context.ClassName);
        }
 /// <summary>
 /// Inspects the GeneratorResults and returns the source code.
 /// </summary>
 /// <param name="results"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public override string InspectSource(GeneratorResults results, TypeContext context)
 {
     string generatedCode;
     var builder = new StringBuilder();
     using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
     {
         _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
         generatedCode = builder.ToString();
     }
     return generatedCode;
 }
        public IEnumerable<CompilerReference> GetReferences(TypeContext context, IEnumerable<CompilerReference> includeAssemblies = null)
        {
            var setupAssemblies = new List<CompilerReference>();
            var binPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            var needAssemblies = Load().Select(_ => Assembly.LoadFile(Path.Combine(binPath, _.Name))).Select(_ => CompilerReference.From(_.Location)).ToArray();
            setupAssemblies.AddRange(needAssemblies);

            var loadedAssemblies = (new UseCurrentAssembliesReferenceResolver()).GetReferences(context, includeAssemblies);
            setupAssemblies.AddRange(loadedAssemblies);

            return setupAssemblies.Distinct();
        }
        public override string CompileTypeAndReturnSource(TypeContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            var result = Compile(context);
            var compileResult = result.Item1;

            if (compileResult.Errors != null && compileResult.Errors.Count > 0)
                throw new TemplateCompilationException(compileResult.Errors, result.Item2, context.TemplateContent);

            return result.Item2;
        }
        public override Tuple<Type, Assembly> CompileType(TypeContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            var results = Compile(context);

            if (results.Errors != null && results.Errors.Count > 0)
                throw new TemplateCompilationException(results.Errors);

            return Tuple.Create(
                results.CompiledAssembly.GetType("CompiledRazorTemplates.Dynamic." + context.ClassName),
                results.CompiledAssembly);
        }
 public IEnumerable<CompilerReference> GetReferences(TypeContext context,
     IEnumerable<CompilerReference> includeAssemblies)
 {
     // TypeContext gives you some context for the compilation (which templates, which namespaces and types)
     // My templates need some special reference to compile.
     return new[]
     {
         //CompilerReference.From("Path-to-my-custom-assembly"), // file path (string)
         CompilerReference.From(typeof (SystemConfig).Assembly),
         CompilerReference.From(typeof (Config).Assembly),
         CompilerReference.From(typeof (MongoConnectionConfig).Assembly) // Assembly
         //CompilerReference.From(assemblyInByteArray), // byte array (roslyn only)
         //CompilerReference.From(File.OpenRead(assembly)), // stream (roslyn only)
     };
 }
        public override Tuple<Type, CompilationData> CompileType(TypeContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            (new PermissionSet(PermissionState.Unrestricted)).Assert();
            var isMono = Type.GetType("Mono.Runtime") != null;
            if (!isMono)
            {
                return CompileType_Windows(context);
            }
            else
            {
                return CompileTypeImpl(context);
            }
        }
        private Tuple<CompilerResults, string> Compile(TypeContext context)
        {
            if (_disposed)
                throw new ObjectDisposedException(GetType().Name);

            var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces,
                                                 context.TemplateType, context.ModelType);

            var @params = new CompilerParameters
            {
                GenerateInMemory = true,
                GenerateExecutable = false,
                IncludeDebugInformation = false,
                CompilerOptions = "/target:library /optimize"
            };

            var assemblies = CompilerServicesUtility
                .GetLoadedAssemblies()
                .Where(a => !a.IsDynamic && File.Exists(a.Location))
                .GroupBy(a => a.GetName().Name).Select(grp => grp.First(y => y.GetName().Version == grp.Max(x => x.GetName().Version))) // only select distinct assemblies based on FullName to avoid loading duplicate assemblies
                .Select(a => a.Location);

            var includeAssemblies = (IncludeAssemblies() ?? Enumerable.Empty<string>());
            assemblies = assemblies.Concat(includeAssemblies)
                .Where(a => !string.IsNullOrWhiteSpace(a))
                .Distinct(StringComparer.InvariantCultureIgnoreCase);

            @params.ReferencedAssemblies.AddRange(assemblies.ToArray());

            string sourceCode = null;
            if (Debug)
            {
                var builder = new StringBuilder();
                using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
                {
                    _codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
                    sourceCode = builder.ToString();
                }
            }

            return Tuple.Create(_codeDomProvider.CompileAssemblyFromDom(@params, compileUnit), sourceCode);
        }
        public override Tuple<Type, CompilationData> CompileType(TypeContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            (new PermissionSet(PermissionState.Unrestricted)).Assert();
            var result = Compile(context);
            var compileResult = result.Item1;

            CompilationData tmpDir;
            if (compileResult.TempFiles != null)
            {
                tmpDir = new CompilationData(result.Item2, compileResult.TempFiles.TempDir);
            }
            else
            {
                tmpDir = new CompilationData(result.Item2, null);
            }

            if (compileResult.Errors != null && compileResult.Errors.HasErrors)
            {
                throw new TemplateCompilationException(
                    compileResult.Errors
                    .Cast<CompilerError>()
                    .Select(error =>
                        new RazorEngineCompilerError(
                            error.ErrorText,
                            error.FileName,
                            error.Line,
                            error.Column,
                            error.ErrorNumber,
                            error.IsWarning)),
                    tmpDir, context.TemplateContent);
            }
            // Make sure we load the assembly from a file and not with
            // Load(byte[]) (or it will be fully trusted!)
            var assemblyPath = compileResult.PathToAssembly;
            compileResult.CompiledAssembly = Assembly.LoadFile(assemblyPath);
            var type = compileResult.CompiledAssembly.GetType(DynamicTemplateNamespace + "." + context.ClassName);
            return Tuple.Create(type, tmpDir);
        }
        /// <summary>
        /// Creates the compile results for the specified <see cref="TypeContext"/>.
        /// </summary>
        /// <param name="context">The type context.</param>
        /// <returns>The compiler results.</returns>
        private CompilerResults Compile(TypeContext context)
        {
            var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces,
                                                 context.TemplateType, context.ModelType);

            var @params = new CompilerParameters
                              {
                                  GenerateInMemory = true,
                                  GenerateExecutable = false,
                                  IncludeDebugInformation = false,
                                  CompilerOptions = "/target:library /optimize"
                              };

            var assemblies = CompilerServices
                .GetLoadedAssemblies()
                .Where(a => !a.IsDynamic)
                .Select(a => a.Location)
                .ToArray();

            @params.ReferencedAssemblies.AddRange(assemblies);

            return CodeDomProvider.CompileAssemblyFromDom(@params, compileUnit);
        }
        public IEnumerable<CompilerReference> GetReferences(TypeContext context, IEnumerable<CompilerReference> includeAssemblies)
        {
            // TypeContext gives you some context for the compilation (which templates, which namespaces and types)

            // You must make sure to include all libraries that are required!
            // Mono compiler does add more standard references than csc!
            // If you want mono compatibility include ALL references here, including mscorlib!
            // If you include mscorlib here the compiler is called with /nostdlib.
            IEnumerable<string> loadedAssemblies = (new UseCurrentAssembliesReferenceResolver())
                .GetReferences(context, includeAssemblies)
                .Select(r => r.GetFile())
                .ToArray();
            yield return CompilerReference.From(FindLoaded(loadedAssemblies, "mscorlib.dll"));
            yield return CompilerReference.From(FindLoaded(loadedAssemblies, "System.dll"));
            yield return CompilerReference.From(FindLoaded(loadedAssemblies, "System.Core.dll"));
            yield return CompilerReference.From(FindLoaded(loadedAssemblies, "System.Web.Razor.dll"));
            yield return CompilerReference.From(FindLoaded(loadedAssemblies, "Microsoft.CSharp.dll"));
            yield return CompilerReference.From(FindLoaded(loadedAssemblies, "RazorEngine.dll"));
            yield return CompilerReference.From(FindLoaded(loadedAssemblies, "RazorTransformLibary.dll"));
            yield return CompilerReference.From(typeof(MyIReferenceResolver).Assembly); // Assembly
            if (Directory.Exists(DllFolder))
            {
                var fileDllList = Directory.GetFiles(DllFolder, "*.dll");
                foreach (var dllPath in fileDllList)
                {
                    var file = Path.GetFullPath(dllPath);
                    yield return CompilerReference.From(file);
                }
            }

            // There are several ways to load an assembly:
            //yield return CompilerReference.From("Path-to-my-custom-assembly"); // file path (string)
            //byte[] assemblyInByteArray = --- Load your assembly ---;
            //yield return CompilerReference.From(assemblyInByteArray); // byte array (roslyn only)
            //string assemblyFile = --- Get the path to the assembly ---;
            //yield return CompilerReference.From(File.OpenRead(assemblyFile)); // stream (roslyn only)
        }
 public string GetCodeCompileUnit(string className, ITemplateSource template, ISet<string> namespaceImports, Type templateType, Type modelType)
 {
     var typeContext =
         new TypeContext(className, namespaceImports)
         {
             TemplateContent = template,
             TemplateType = templateType,
             ModelType = modelType
         };
     return GetCodeCompileUnit(typeContext);
 }
 public abstract Tuple<Type, CompilationData> CompileType(TypeContext context);
 /// <summary>
 /// Compiles the type defined in the specified type context.
 /// </summary>
 /// <param name="context">The type context which defines the type to compile.</param>
 /// <returns>The compiled type.</returns>
 public abstract Type CompileType(TypeContext context);
 public abstract string CompileTypeAndReturnSource(TypeContext context);
        private Tuple<CompilerResults, string> Compile(TypeContext context)
        {
            if (_disposed)
                throw new ObjectDisposedException(GetType().Name);

            var compileUnit = GetCodeCompileUnit(context.ClassName, context.TemplateContent, context.Namespaces,
                                                 context.TemplateType, context.ModelType);

            Inspect(compileUnit);

            var @params = new CompilerParameters
            {
                GenerateInMemory = true,
                GenerateExecutable = false,
                IncludeDebugInformation = false,
                CompilerOptions = "/target:library /optimize"
            };

            var assemblies = CompilerServicesUtility
                .GetLoadedAssemblies()
                .Where(a => !a.IsDynamic)
                .Select(a => a.Location);

            var includeAssemblies = (IncludeAssemblies() ?? Enumerable.Empty<string>());
            assemblies = assemblies.Concat(includeAssemblies)
                .Select(a => a.ToUpperInvariant())
                .Where(a => !string.IsNullOrWhiteSpace(a))
                .Distinct();

            @params.ReferencedAssemblies.AddRange(assemblies.ToArray());

            string sourceCode = null;
            if (Debug)
            {
                var builder = new StringBuilder();
                using (var writer = new StringWriter(builder))
                {
                    _codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
                    sourceCode = builder.ToString();
                }
            }

            return Tuple.Create(_codeDomProvider.CompileAssemblyFromDom(@params, compileUnit), sourceCode);
        }
 public virtual string InspectSource(GeneratorResults results, TypeContext context)
 {
     return results.GeneratedCode;
 }
 /// <summary>
 /// Helper method to generate the prefered assembly name.
 /// </summary>
 /// <param name="context">the context of the current compilation.</param>
 /// <returns></returns>
 protected string GetAssemblyName(TypeContext context)
 {
     return String.Format("{0}.{1}", DynamicTemplateNamespace, context.ClassName);
 }
 /// <summary>
 /// Creates a CSharpCompilationOptions instance.
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override CompilationOptions CreateOptions(TypeContext context)
 {
     return
         new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
         .WithUsings(context.Namespaces);
 }
Beispiel #21
0
 /// <summary>
 /// Helper method to generate the prefered assembly name.
 /// </summary>
 /// <param name="context">the context of the current compilation.</param>
 /// <returns></returns>
 protected string GetAssemblyName(TypeContext context)
 {
     return(String.Format("{0}.{1}", DynamicTemplateNamespace, context.ClassName));
 }
Beispiel #22
0
 public virtual string InspectSource(GeneratorResults results, TypeContext context)
 {
     return(results.GeneratedCode);
 }
Beispiel #23
0
 public abstract string InspectSource(GeneratorResults results, TypeContext context);
        public string GetCodeCompileUnit(TypeContext context)
        {
            string className = context.ClassName;
            ITemplateSource template = context.TemplateContent;
            ISet<string> namespaceImports = context.Namespaces;
            Type templateType = context.TemplateType;
            Type modelType = context.ModelType;

            if (string.IsNullOrEmpty(className))
                throw new ArgumentException("Class name is required.");

            if (template == null)
                throw new ArgumentException("Template is required.");

            namespaceImports = namespaceImports ?? new HashSet<string>();
            templateType = templateType ?? ((modelType == null) ? typeof(TemplateBase) : typeof(TemplateBase<>));

            // Create the RazorEngineHost
            var host = CreateHost(templateType, modelType, className);

            // Add any required namespace imports
            foreach (string ns in GetNamespaces(templateType, namespaceImports))
                host.NamespaceImports.Add(ns);

            // Gets the generator result.
            return GetGeneratorResult(host, context);
        }
Beispiel #25
0
 public abstract Tuple <Type, CompilationData> CompileType(TypeContext context);
 /// <summary>
 /// Helper method to get all references for the given compilation.
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 protected IEnumerable<CompilerReference> GetAllReferences(TypeContext context)
 {
     #pragma warning disable 0618 // Backwards Compat.
     var references =
         ReferenceResolver.GetReferences(
             context,
             IncludeAssemblies()
                 .Select(RazorEngine.Compilation.ReferenceResolver.CompilerReference.From)
                 .Concat(IncludeReferences()))
     #pragma warning restore 0618 // Backwards Compat.
         .ToList();
     context.AddReferences(references);
     return references;
 }
        private Tuple<CompilerResults, string> Compile(TypeContext context)
        {
            if (_disposed)
                throw new ObjectDisposedException(GetType().Name);

            var sourceCode = GetCodeCompileUnit(context);
            var assemblies = GetAllReferences(context);

            var fileAssemblies = assemblies
                .Select(a => a.GetFile(
                    msg => new ArgumentException(
                        string.Format(
                            "Unsupported CompilerReference given to CodeDom compiler (only references which can be resolved to files are supported: {0})!",
                            msg))))
                .Where(a => !string.IsNullOrWhiteSpace(a))
                .Distinct(StringComparer.InvariantCultureIgnoreCase)
                .ToArray();
            var haveMscorlib = fileAssemblies.Any(a => a.Contains("mscorlib.dll"));

            var @params = new CompilerParameters
            {
                GenerateInMemory = false,
                GenerateExecutable = false,
                IncludeDebugInformation = Debug,
                TreatWarningsAsErrors = false,
                TempFiles = new TempFileCollection(GetTemporaryDirectory(), true),
                CompilerOptions =
                    string.Format("/target:library /optimize /define:RAZORENGINE {0}",
                        haveMscorlib ? "/nostdlib" : "")
            };

            @params.ReferencedAssemblies.AddRange(fileAssemblies);
            var tempDir = @params.TempFiles.TempDir;
            var assemblyName = Path.Combine(tempDir,
                String.Format("{0}.dll", GetAssemblyName(context)));
            @params.TempFiles.AddFile(assemblyName, true);
            @params.OutputAssembly = assemblyName;

            var results = _codeDomProvider.CompileAssemblyFromSource(@params, new [] { sourceCode });
            if (Debug)
            {
                bool written = false;
                var targetFile = Path.Combine(results.TempFiles.TempDir, "generated_template." + SourceFileExtension);
                if (!written && !File.Exists(targetFile))
                {
                    File.WriteAllText(targetFile, sourceCode);
                    written = true;
                }
                if (!written)
                {
                    foreach (string item in results.TempFiles)
                    {
                        if (item.EndsWith("." + this.SourceFileExtension))
                        {
                            File.Copy(item, targetFile, true);
                            written = true;
                            break;
                        }
                    }
                }
            }
            return Tuple.Create(results, sourceCode);
        }
 private string GetGeneratorResult(RazorEngineHost host, TypeContext context)
 {
     var engine = new RazorTemplateEngine(host);
     GeneratorResults result;
     using (var reader = context.TemplateContent.GetTemplateReader())
         result = engine.GenerateCode(reader, null, null, context.TemplateContent.TemplateFile);
     return InspectSource(result, context);
 }
        private Tuple<Type, CompilationData> CompileTypeImpl(TypeContext context)
        {
            var result = Compile(context);
            var compileResult = result.Item1;

            CompilationData tmpDir;
            if (compileResult.TempFiles != null)
            {
                tmpDir = new CompilationData(result.Item2, compileResult.TempFiles.TempDir);
            }
            else
            {
                tmpDir = new CompilationData(result.Item2, null);
            }

            if (compileResult.Errors != null && compileResult.Errors.HasErrors)
            {
                throw new TemplateCompilationException(
                    compileResult.Errors
                    .Cast<CompilerError>()
                    .Select(error =>
                        new RazorEngineCompilerError(
                            error.ErrorText,
                            error.FileName,
                            error.Line,
                            error.Column,
                            error.ErrorNumber,
                            error.IsWarning)),
                    tmpDir, context.TemplateContent);
            }
            // Make sure we load the assembly from a file and not with
            // Load(byte[]) (or it will be fully trusted!)
            var assemblyPath = compileResult.PathToAssembly;
            if (DisableTempFileLocking)
            {
                compileResult.CompiledAssembly = Assembly.Load(File.ReadAllBytes(assemblyPath));
            }
            else
            {
                compileResult.CompiledAssembly = Assembly.LoadFile(assemblyPath);
            }
            var type = compileResult.CompiledAssembly.GetType(DynamicTemplateNamespace + "." + context.ClassName);
            if (type == null)
            {
                try
                {
                    compileResult.CompiledAssembly.GetTypes();
                }
                catch (Exception e)
                {
                    throw new TemplateLoadingException("Unable to load types of the laded assembly", e);
                }
                // if we are here we just throw
                throw new TemplateLoadingException("We could not find the type in the compiled assembly!");
            }
            return Tuple.Create(type, tmpDir);
        }
 public abstract string InspectSource(GeneratorResults results, TypeContext context);
        private Tuple<Type, CompilationData> CompileType_Windows(TypeContext context)
        {
            // NOTE: The static constructor of WindowsImpersonationContext can fail,
            // that's why we need to do that in a seperate method
            // -> Static constructor will not run

            /* Exception details: (2015-01-23: https://travis-ci.org/Antaris/RazorEngine/builds/47985319)
              System.Security.SecurityException : Couldn't impersonate token.
              at System.Security.Principal.WindowsImpersonationContext..ctor (IntPtr token) [0x00000] in <filename unknown>:0
              at System.Security.Principal.WindowsIdentity.Impersonate (IntPtr userToken) [0x00000] in <filename unknown>:0
              at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType (RazorEngine.Compilation.TypeContext context) [0x00033] in /home/travis/build/Antaris/RazorEngine/src/source/RazorEngine.Core/Compilation/DirectCompilerServiceBase.cs:276
             */
            WindowsImpersonationContext wic = WindowsIdentity.Impersonate(IntPtr.Zero);
            try
            {
                return CompileTypeImpl(context);
            }
            finally
            {
                wic.Undo();
            }
        }
 /// <summary>
 /// Compiles the type defined in the specified type context.
 /// </summary>
 /// <param name="context">The type context which defines the type to compile.</param>
 /// <returns>The compiled type.</returns>
 public abstract Tuple<Type, Assembly> CompileType(TypeContext context);
 /// <summary>
 /// Compiles the type defined in the specified type context.
 /// </summary>
 /// <param name="context">The type context which defines the type to compile.</param>
 /// <returns>The compiled type.</returns>
 public abstract Tuple <Type, Assembly> CompileType(TypeContext context);
 public IEnumerable<CompilerReference> GetReferences(
     TypeContext context,
     IEnumerable<CompilerReference> includeAssemblies = null
 )
 {
     // We need to return this standard set or even simple views blow up on
     // a missing reference to System.Linq.
     var loadedAssemblies = (new UseCurrentAssembliesReferenceResolver()).GetReferences(null);
     foreach (var reference in loadedAssemblies)
         yield return reference;
     yield return CompilerReference.From("test/TestHelper.dll");
 }
        private Tuple <CompilerResults, string> Compile(TypeContext context)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            var sourceCode = GetCodeCompileUnit(context);
            var assemblies = GetAllReferences(context);

            var fileAssemblies = assemblies
                                 .Select(a => a.GetFile(
                                             msg => new ArgumentException(
                                                 string.Format(
                                                     "Unsupported CompilerReference given to CodeDom compiler (only references which can be resolved to files are supported: {0})!",
                                                     msg))))
                                 .Where(a => !string.IsNullOrWhiteSpace(a))
                                 .Distinct(StringComparer.InvariantCultureIgnoreCase)
                                 .ToArray();
            var haveMscorlib = fileAssemblies.Any(a => a.Contains("mscorlib.dll"));

            var @params = new CompilerParameters
            {
                GenerateInMemory        = false,
                GenerateExecutable      = false,
                IncludeDebugInformation = Debug,
                TreatWarningsAsErrors   = false,
                TempFiles       = new TempFileCollection(GetTemporaryDirectory(), true),
                CompilerOptions =
                    string.Format("/target:library /optimize /define:RAZORENGINE {0}",
                                  haveMscorlib ? "/nostdlib" : "")
            };


            @params.ReferencedAssemblies.AddRange(fileAssemblies);
            var tempDir      = @params.TempFiles.TempDir;
            var assemblyName = Path.Combine(tempDir,
                                            String.Format("{0}.dll", GetAssemblyName(context)));

            @params.TempFiles.AddFile(assemblyName, true);
            @params.OutputAssembly = assemblyName;

            var results = _codeDomProvider.CompileAssemblyFromSource(@params, new [] { sourceCode });

            if (Debug)
            {
                bool written    = false;
                var  targetFile = Path.Combine(results.TempFiles.TempDir, "generated_template." + SourceFileExtension);
                if (!written && !File.Exists(targetFile))
                {
                    File.WriteAllText(targetFile, sourceCode);
                    written = true;
                }
                if (!written)
                {
                    foreach (string item in results.TempFiles)
                    {
                        if (item.EndsWith("." + this.SourceFileExtension))
                        {
                            File.Copy(item, targetFile, true);
                            written = true;
                            break;
                        }
                    }
                }
            }
            return(Tuple.Create(results, sourceCode));
        }
        public override string InspectSource(GeneratorResults results, TypeContext context)
        {
            #if RAZOR4
            string generatedCode = results.GeneratedCode;
            if (context.TemplateContent.TemplateFile == null)
            {
                generatedCode = generatedCode.Replace("#line hidden", "");
            }

            // TODO: add attributes and constructor to the source code.

            return generatedCode;
            #else
            if (context.TemplateContent.TemplateFile == null)
            {
                // Allow to step into the template code by removing the "#line hidden" pragmas
                foreach (CodeNamespace @namespace in results.GeneratedCode.Namespaces.Cast<CodeNamespace>().ToList())
                {
                    foreach (CodeTypeDeclaration @type in @namespace.Types.Cast<CodeTypeDeclaration>().ToList())
                    {
                        foreach (CodeTypeMember member in @type.Members.Cast<CodeTypeMember>().ToList())
                        {
                            var snippet = member as CodeSnippetTypeMember;
                            if (snippet != null && snippet.Text.Contains("#line hidden"))
                            {
                                snippet.Text = snippet.Text.Replace("#line hidden", "");
                            }
                        }
                    }
                }
            }

            // Add the dynamic model attribute if the type is an anonymous type.
            var generatedType = results.GeneratedCode.Namespaces[0].Types[0];
            if (context.ModelType != null && CompilerServicesUtility.IsDynamicType(context.ModelType))
                generatedType.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(HasDynamicModelAttribute))));

            // Generate any constructors required by the base template type.
            GenerateConstructors(CompilerServicesUtility.GetConstructors(context.TemplateType), generatedType);

            #pragma warning disable 0618 // Backwards Compat.
            // Despatch any inspectors
            Inspect(results.GeneratedCode);
            #pragma warning restore 0618 // Backwards Compat.

            string generatedCode;
            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                CodeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = builder.ToString();
            }
            return generatedCode;
            #endif
        }
Beispiel #37
0
        private string GetGeneratorResult(IEnumerable <string> namespaces, TypeContext context)
        {
#pragma warning disable 612, 618
            // HERE is where we create our razor engine
            var razorEngine = RazorEngine.Create(builder =>
            {
                builder
                .SetNamespace(DynamicTemplateNamespace)
                //.SetBaseType("Microsoft.Extensions.RazorViews.BaseView")
                .SetBaseType(BuildTypeName(context.TemplateType, context.ModelType))
                .ConfigureClass((document, @class) =>
                {
                    @class.ClassName = context.ClassName;
                    //if (!str  ing.IsNullOrWhiteSpace(document.Source.FilePath))
                    //{
                    //    @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath);
                    //}
                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("internal");
                });
                SectionDirective.Register(builder);
                builder.Features.Add(new SuppressChecksumOptionsFeature());
            });

            string importString = @"
@using System
@using System.Threading.Tasks
";
            importString += String.Join("\r\n", namespaces.Select(n => "@using " + n.Trim())) + "\r\n";

            using (var reader = context.TemplateContent.GetTemplateReader())
            {
                string path = null;
                if (string.IsNullOrWhiteSpace(context.TemplateContent.TemplateFile))
                {
                    path = Directory.GetCurrentDirectory();
                }
                else
                {
                    path = Path.GetDirectoryName(context.TemplateContent.TemplateFile);
                }
                var razorProject   = RazorProjectFileSystem.Create(path);
                var templateEngine = new RazorTemplateEngine(razorEngine, razorProject);
                templateEngine.Options.DefaultImports = RazorSourceDocument.Create(importString, fileName: null);
                RazorPageGeneratorResult result;
                if (string.IsNullOrWhiteSpace(context.TemplateContent.TemplateFile))
                {
                    var item    = RazorSourceDocument.Create(context.TemplateContent.Template, string.Empty);
                    var imports = new List <RazorSourceDocument>();
                    imports.Add(templateEngine.Options.DefaultImports);
                    var doc = RazorCodeDocument.Create(item, imports);
                    result = GenerateCodeFile(templateEngine, doc);
                }
                else
                {
                    var item = razorProject.GetItem(context.TemplateContent.TemplateFile);
                    result = GenerateCodeFile(templateEngine, item);
                }
                return(InspectSource(result, context));
            }
        }