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));
        }
 /// <summary>
 /// Initialises a new instance of <see cref="TemplateCompilationException"/>.
 /// </summary>
 /// <param name="errors">The set of compiler errors.</param>
 /// <param name="files">The source code that wasn't compiled.</param>
 /// <param name="template">The source template that wasn't compiled.</param>
 public TemplateCompilationException(IEnumerable<RazorEngineCompilerError> errors, CompilationData files, ITemplateSource template)
     : base(TemplateCompilationException.GetMessage(errors, files, template))
 {
     var list = errors.ToList();
     CompilerErrors = new ReadOnlyCollection<RazorEngineCompilerError>(list);
     CompilationData = files;
     Template = template.Template;
 }
Пример #3
0
 public CompiledTemplate(CompilationData tempFiles, ITemplateKey key, ITemplateSource source, Type templateType, Type modelType)
 {
     _tempFiles = tempFiles;
     _key = key;
     _source = source;
     _templateType = templateType;
     _modelType = modelType;
 }
        /// <summary>
        /// Gets a exact error message of the given error collection
        /// </summary>
        /// <param name="errors"></param>
        /// <param name="files"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        internal static string GetMessage(IEnumerable<RazorEngineCompilerError> errors, CompilationData files, ITemplateSource template)
        {
            var errorMsgs = string.Join("\n\t", errors.Select(error =>
                string.Format(
                    " - {0}: ({1}, {2}) {3}", 
                    error.IsWarning ? "warning" : "error", 
                    error.Line, error.Column, error.ErrorText)));

            const string rawTemplateFileMsg = "The template-file we tried to compile is: {0}\n";
            const string rawTemplate = "The template we tried to compile is: {0}\n";
            const string rawTmpFiles = "Temporary files of the compilation can be found in (please delete the folder): {0}\n";
            const string rawSourceCode = "The generated source code is: {0}\n";

            string templateFileMsg;
            if (string.IsNullOrEmpty(template.TemplateFile)) {
                templateFileMsg = string.Format(rawTemplate, Separate(template.Template ?? string.Empty));
	        } else{
                templateFileMsg = string.Format(rawTemplateFileMsg, template.TemplateFile ?? string.Empty);
            }
            string tempFilesMsg = string.Empty;
            if (files.TmpFolder != null)
            {
                tempFilesMsg = string.Format(rawTmpFiles, files.TmpFolder);
            }

            string sourceCodeMessage = string.Empty;
            if (files.SourceCode != null)
            {
                sourceCodeMessage = string.Format(rawSourceCode, Separate(files.SourceCode));
            }

            string loadedAssemblies =
                "\nList of loaded Assemblies:\n" +
                string.Join("\n\tLoaded Assembly: ",
                    (new Compilation.ReferenceResolver.UseCurrentAssembliesReferenceResolver())
                    .GetReferences().Select(r => r.GetFile()));

            var rawMessage = @"Errors while compiling a Template.
Please try the following to solve the situation:
  * If the problem is about missing/invalid references or multiple defines either try to load 
    the missing references manually (in the compiling appdomain!) or
    Specify your references manually by providing your own IReferenceResolver implementation.
    See https://antaris.github.io/RazorEngine/ReferenceResolver.html for details.
    Currently all references have to be available as files!
  * If you get 'class' does not contain a definition for 'member': 
        try another modelType (for example 'null' to make the model dynamic).
        NOTE: You CANNOT use typeof(dynamic) to make the model dynamic!
    Or try to use static instead of anonymous/dynamic types.
More details about the error:
{0}
{1}{2}{3}{4}";
            return string.Format(rawMessage, errorMsgs, tempFilesMsg, templateFileMsg, sourceCodeMessage, loadedAssemblies);
        }
        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>
        /// Initialises a new instance of <see cref="TemplateCompilationException"/> from serialised data.
        /// </summary>
        /// <param name="info">The serialisation info.</param>
        /// <param name="context">The streaming context.</param>
        protected TemplateCompilationException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            int count = info.GetInt32("Count");

            var list = new List<RazorEngineCompilerError>();
            var type = typeof(RazorEngineCompilerError);

            for (int i = 0; i < count; i++)
            {
                list.Add((RazorEngineCompilerError)info.GetValue("CompilerErrors[" + i + "]", type));
            }

            CompilerErrors = new ReadOnlyCollection<RazorEngineCompilerError>(list);
            var sourceCode = info.GetString("SourceCode");
            if (string.IsNullOrEmpty(sourceCode))
            {
                sourceCode = null;
            }
            var tmpFolder = info.GetString("TmpFolder");
            if (string.IsNullOrEmpty(tmpFolder))
            {
                tmpFolder = null;
            }
            CompilationData = new CompilationData(sourceCode, tmpFolder);
            Template = info.GetString("Template");
        }
        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 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);
        }