// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using Microsoft.AspNet.FileSystems; namespace Microsoft.AspNet.Mvc.Razor { /// /// Represents the result of compilation. /// public class CompilationResult { private Type _type; /// /// Creates a new instance of . /// protected CompilationResult() { } /// /// Gets the path of the Razor file that was compiled. /// public string FilePath { get { if (File != null) { return File.PhysicalPath; } return null; } } /// /// Gets a sequence of instances encountered during compilation. /// public IEnumerable Messages { get; private set; } /// /// Gets (or sets in derived types) the generated C# content that was compiled. /// public string CompiledContent { get; protected set; } /// /// Gets (or sets in derived types) the type produced as a result of compilation. /// /// An error occured during compilation. public Type CompiledType { get { if (_type == null) { throw CreateCompilationFailedException(); } return _type; } protected set { _type = value; } } private IFileInfo File { get; set; } /// /// Creates a that represents a failure in compilation. /// /// The for the Razor file that was compiled. /// The generated C# content to be compiled. /// The sequence of failure messages encountered during compilation. /// A CompilationResult instance representing a failure. public static CompilationResult Failed([NotNull] IFileInfo file, [NotNull] string compilationContent, [NotNull] IEnumerable messages) { return new CompilationResult { File = file, CompiledContent = compilationContent, Messages = messages, }; } /// /// Creates a that represents a success in compilation. /// /// The compiled type. /// A CompilationResult instance representing a success. public static CompilationResult Successful([NotNull] Type type) { return new CompilationResult { CompiledType = type }; } private CompilationFailedException CreateCompilationFailedException() { var fileContent = ReadContent(File); var compilationFailure = new CompilationFailure(FilePath, fileContent, CompiledContent, Messages); return new CompilationFailedException(compilationFailure); } private static string ReadContent(IFileInfo file) { try { using (var stream = file.CreateReadStream()) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } catch (Exception) { // Don't throw if reading the file fails. return string.Empty; } } } }